mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main into gatekeeper/fix-4843-1
This commit is contained in:
+3
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.4"
|
||||
version = "0.42.0-beta.20"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
@@ -37,6 +37,7 @@ pyo3-async-runtimes = { version = "0.29", features = [
|
||||
"tokio-runtime",
|
||||
] }
|
||||
reqwest.workspace = true
|
||||
rattler_conda_types = { version = "0.58.3", default-features = false }
|
||||
pin-project.workspace = true
|
||||
futures.workspace = true
|
||||
serde.workspace = true
|
||||
@@ -50,7 +51,7 @@ libc = "0.2"
|
||||
pyo3-build-config = "0.29"
|
||||
|
||||
[features]
|
||||
default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"]
|
||||
default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel", "lancedb/geo"]
|
||||
fp16kernels = ["lancedb/fp16kernels"]
|
||||
remote = ["lancedb/remote"]
|
||||
experimental-functions = ["lancedb/experimental-functions"]
|
||||
|
||||
+6730
-880
File diff suppressed because it is too large
Load Diff
@@ -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()
|
||||
+8
-10
@@ -12,17 +12,17 @@ dependencies = [
|
||||
"tqdm>=4.27.0",
|
||||
"lance-namespace>=0.13.0"
|
||||
]
|
||||
description = "lancedb"
|
||||
description = "Embedded database for vector, full-text and hybrid search on Lance tables"
|
||||
authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }]
|
||||
license = { file = "LICENSE" }
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
keywords = [
|
||||
"data-format",
|
||||
"data-science",
|
||||
"machine-learning",
|
||||
"arrow",
|
||||
"data-analytics",
|
||||
"lance",
|
||||
"vector-search",
|
||||
"full-text-search",
|
||||
"dataset",
|
||||
"versioning",
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
@@ -62,11 +62,9 @@ tests = [
|
||||
"duckdb>=0.9.0",
|
||||
"pytz>=2023.3",
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow<25",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
# pylance 15.0.0b5+ has not published macOS wheels.
|
||||
"pylance==15.0.0b9; sys_platform != 'darwin'",
|
||||
"pylance==15.0.0b4; sys_platform == 'darwin'",
|
||||
"pylance==15.0.0b25",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
|
||||
import os
|
||||
import warnings
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
from typing import Dict, Optional, Union, Any, List, Iterable, Literal, TYPE_CHECKING
|
||||
@@ -16,9 +17,18 @@ __version__ = str(_Version(_native_version))
|
||||
|
||||
from ._lancedb import connect as lancedb_connect
|
||||
from ._lancedb import FtsToken
|
||||
from ._lancedb import (
|
||||
FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus,
|
||||
)
|
||||
from ._lancedb import (
|
||||
FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob,
|
||||
)
|
||||
from ._lancedb import FunctionColumnStatus as FunctionColumnStatus
|
||||
from ._lancedb import (
|
||||
FunctionColumnVersionStatus as FunctionColumnVersionStatus,
|
||||
)
|
||||
from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
|
||||
from ._lancedb import FunctionErrorRecord as FunctionErrorRecord
|
||||
from ._lancedb import FunctionErrors as FunctionErrors
|
||||
from ._lancedb import GpuClass as GpuClass
|
||||
from ._lancedb import RTEWriteSpec
|
||||
from ._lancedb import tokenize as _tokenize
|
||||
@@ -28,23 +38,34 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection
|
||||
from .remote import ClientConfig
|
||||
from .remote.db import RemoteDBConnection
|
||||
from .expr import Expr, col, lit, func
|
||||
from .schema import blob, vector
|
||||
from .schema import BasePath, blob, blob_uri_array, vector
|
||||
from ._blob_reader import BlobReader as BlobReader
|
||||
from .job import AsyncJob, Job
|
||||
from .sql import AsyncQuery as AsyncSqlQuery
|
||||
from .sql import Query as SqlQuery
|
||||
from .sql import QueryDescription
|
||||
from .functions import (
|
||||
FunctionErrors as FunctionErrors,
|
||||
AsyncFunctionErrors as AsyncFunctionErrors,
|
||||
FunctionErrorGroup as FunctionErrorGroup,
|
||||
FunctionProvenance as FunctionProvenance,
|
||||
FunctionValueProvenance as FunctionValueProvenance,
|
||||
AssignmentMapping as AssignmentMapping,
|
||||
FunctionArtifactRequest as FunctionArtifactRequest,
|
||||
FunctionApplication as FunctionApplication,
|
||||
FunctionBinding as FunctionBinding,
|
||||
FunctionDefinition as FunctionDefinition,
|
||||
FunctionEnvironment as FunctionEnvironment,
|
||||
FunctionRegistrationRequest as FunctionRegistrationRequest,
|
||||
FunctionRetryPolicy as FunctionRetryPolicy,
|
||||
FunctionVersion as FunctionVersion,
|
||||
HuggingFaceModel as HuggingFaceModel,
|
||||
PythonRuntimeSpec as PythonRuntimeSpec,
|
||||
ResolvedEnvironment as ResolvedEnvironment,
|
||||
ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance,
|
||||
ResolvedPackage as ResolvedPackage,
|
||||
RefreshColumnResult as RefreshColumnResult,
|
||||
UdfDefinition as UdfDefinition,
|
||||
function as function,
|
||||
udf as udf,
|
||||
)
|
||||
from .secrets import EnvVarSecret as EnvVarSecret
|
||||
@@ -58,6 +79,7 @@ from .materialized_view import (
|
||||
from .view import ViewDescription as ViewDescription
|
||||
from .graph import PropertyGraph, PropertyGraphDescription
|
||||
from .table import AsyncTable, CompactionOptions, Table
|
||||
from .query import ColumnOrdering as ColumnOrdering
|
||||
from .types import BaseTokenizerType
|
||||
from ._lancedb import Session
|
||||
from .namespace import (
|
||||
@@ -77,6 +99,7 @@ from .catalog import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lance.blob import BlobType as BlobType
|
||||
from .functions import UdfDefinition as UdfDefinition
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
@@ -85,6 +108,13 @@ def __getattr__(name: str):
|
||||
|
||||
globals()["BlobType"] = BlobType
|
||||
return BlobType
|
||||
if name == "UdfDefinition":
|
||||
from . import functions
|
||||
|
||||
warnings.warn(
|
||||
functions.UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2
|
||||
)
|
||||
return functions.FunctionDefinition
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
|
||||
@@ -649,6 +679,15 @@ __all__ = [
|
||||
"AsyncTable",
|
||||
"CompactionOptions",
|
||||
"FtsToken",
|
||||
"FunctionColumnAutoRefreshStatus",
|
||||
"FunctionColumnLastRefreshJob",
|
||||
"FunctionColumnStatus",
|
||||
"FunctionColumnVersionStatus",
|
||||
"FunctionErrors",
|
||||
"AsyncFunctionErrors",
|
||||
"FunctionErrorGroup",
|
||||
"FunctionProvenance",
|
||||
"FunctionValueProvenance",
|
||||
"col",
|
||||
"Expr",
|
||||
"func",
|
||||
@@ -657,6 +696,8 @@ __all__ = [
|
||||
"sanitize_uri",
|
||||
"blob",
|
||||
"BlobType",
|
||||
"BasePath",
|
||||
"blob_uri_array",
|
||||
"vector",
|
||||
"DBConnection",
|
||||
"Job",
|
||||
|
||||
+114
-10
@@ -1,19 +1,25 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Blob fetch API and v2 projection helpers."""
|
||||
"""Blob fetch API and projection helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import operator
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Optional, Union
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
from .expr import Expr
|
||||
from .schema import blob_column_paths, row_addressable_blob_v2_paths
|
||||
from .schema import (
|
||||
blob_column_paths,
|
||||
row_addressable_blob_paths,
|
||||
row_addressable_blob_v2_paths,
|
||||
)
|
||||
from .types import BlobMode, QueryProjection, QueryProjectionSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -26,10 +32,56 @@ BLOB_MODE_TO_HANDLING = {
|
||||
}
|
||||
|
||||
ROW_ID_FIELD_NAME = "_lance_row_id"
|
||||
QUERY_VERSION_METADATA_KEY = b"lancedb:query_version"
|
||||
QUERY_SNAPSHOT_METADATA_KEY = b"lancedb:query_snapshot"
|
||||
|
||||
FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
|
||||
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
|
||||
|
||||
_POSITION_HELP = (
|
||||
"If you only have row positions, call "
|
||||
"table.take_offsets(offsets, with_row_id=True) first and pass the resulting "
|
||||
"'_rowid' values."
|
||||
)
|
||||
|
||||
|
||||
def _remote_blob_snapshot(
|
||||
schema: pa.Schema, *, operation: str = "blob_mode='bytes'"
|
||||
) -> tuple[int, str]:
|
||||
"""Validate the snapshot metadata a remote query attaches to its result."""
|
||||
value = (schema.metadata or {}).get(QUERY_VERSION_METADATA_KEY, b"")
|
||||
if not value.isdigit() or not 0 < int(value) < 2**64:
|
||||
raise NotImplementedError(
|
||||
f"{operation} 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(QUERY_SNAPSHOT_METADATA_KEY, b"")
|
||||
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
|
||||
raise NotImplementedError(
|
||||
f"{operation} 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")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _BlobRowIdSelection:
|
||||
row_ids: list[int]
|
||||
version: Optional[int] = None
|
||||
snapshot_identity: Optional[str] = None
|
||||
|
||||
|
||||
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):
|
||||
@@ -54,6 +106,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")
|
||||
@@ -165,6 +227,25 @@ def blob_v2_projection_sources(
|
||||
return _project_blob_paths(row_addressable_blob_v2_paths(schema), projection)
|
||||
|
||||
|
||||
def blob_projection_sources(
|
||||
schema: pa.Schema,
|
||||
projection: QueryProjection,
|
||||
*,
|
||||
include_legacy: bool = False,
|
||||
) -> dict[str, str]:
|
||||
"""Map projected blob outputs to row-addressable source columns.
|
||||
|
||||
Legacy v1 columns are included only when the caller can safely fetch them
|
||||
through the same row-id path as v2.
|
||||
"""
|
||||
paths = (
|
||||
row_addressable_blob_paths(schema)
|
||||
if include_legacy
|
||||
else row_addressable_blob_v2_paths(schema)
|
||||
)
|
||||
return _project_blob_paths(paths, projection)
|
||||
|
||||
|
||||
def reject_unfetchable_blob_columns(
|
||||
schema: pa.Schema, projection: QueryProjection, blob_sources: dict[str, str]
|
||||
) -> None:
|
||||
@@ -177,8 +258,9 @@ def reject_unfetchable_blob_columns(
|
||||
if unfetchable:
|
||||
raise ValueError(
|
||||
f"blob_mode='bytes' cannot fetch blob columns {unfetchable}. Bytes are "
|
||||
"fetched by row id, which covers blob v2 columns with one blob per "
|
||||
"row but not legacy blob columns or blobs inside lists. Use "
|
||||
"fetched by row id for legacy and v2 columns in local plain scans, "
|
||||
"but not for blobs inside lists or query shapes whose result columns "
|
||||
"cannot be matched back to the source. Use "
|
||||
"blob_mode='descriptions' or remove these columns from the projection."
|
||||
)
|
||||
|
||||
@@ -269,7 +351,7 @@ def finalize_blob_query_table(
|
||||
return stash_auto_row_ids(tbl, blob_paths)
|
||||
|
||||
|
||||
async def replace_v2_blob_columns_with_bytes(
|
||||
async def replace_blob_columns_with_bytes(
|
||||
tbl: pa.Table,
|
||||
blob_sources: dict[str, str],
|
||||
fetch_blobs: FetchBlobsAsync,
|
||||
@@ -289,7 +371,7 @@ async def replace_v2_blob_columns_with_bytes(
|
||||
return tbl
|
||||
|
||||
|
||||
def replace_v2_blob_columns_with_bytes_sync(
|
||||
def replace_blob_columns_with_bytes_sync(
|
||||
tbl: pa.Table,
|
||||
blob_sources: dict[str, str],
|
||||
fetch_blobs: FetchBlobsSync,
|
||||
@@ -333,7 +415,7 @@ def _hit_row_ids(tbl: pa.Table, blob_sources: dict[str, str]) -> list[int]:
|
||||
raise ValueError(
|
||||
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
|
||||
f"field on blob columns {list(blob_sources)}. Call .with_row_id(True) "
|
||||
"to fetch blob bytes for this query."
|
||||
f"to fetch blob bytes for this query. {_POSITION_HELP}"
|
||||
)
|
||||
|
||||
|
||||
@@ -374,7 +456,8 @@ def read_row_ids_from_hits(hits: pa.Table, blob_column: str) -> list[int]:
|
||||
raise ValueError(
|
||||
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
|
||||
f"field on blob column '{blob_column}'. Pass fresh blob query "
|
||||
"results, call .with_row_id(True), or pass a list of row ids."
|
||||
f"results, call .with_row_id(True), or pass a list of row ids. "
|
||||
f"{_POSITION_HELP}"
|
||||
)
|
||||
|
||||
|
||||
@@ -595,11 +678,31 @@ def _walk_struct_fields(
|
||||
return data_type
|
||||
|
||||
|
||||
def _query_snapshot_for_blob_fetch(
|
||||
schema: pa.Schema,
|
||||
) -> Optional[tuple[int, str]]:
|
||||
"""Use the query snapshot when a result table carries one.
|
||||
|
||||
A table without either metadata key came from a local table or a server
|
||||
that cannot pin deferred reads, so row ids keep their existing
|
||||
current-snapshot behavior.
|
||||
"""
|
||||
metadata = schema.metadata or {}
|
||||
if not any(
|
||||
key in metadata
|
||||
for key in (QUERY_VERSION_METADATA_KEY, QUERY_SNAPSHOT_METADATA_KEY)
|
||||
):
|
||||
return None
|
||||
return _remote_blob_snapshot(schema, operation="fetching blobs for a query result")
|
||||
|
||||
|
||||
def _normalize_blob_row_ids(
|
||||
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], blob_column: str
|
||||
) -> list[int]:
|
||||
) -> _BlobRowIdSelection:
|
||||
snapshot = None
|
||||
if isinstance(row_ids, pa.Table):
|
||||
values = read_row_ids_from_hits(row_ids, blob_column)
|
||||
snapshot = _query_snapshot_for_blob_fetch(row_ids.schema)
|
||||
elif isinstance(row_ids, (pa.Array, pa.ChunkedArray)):
|
||||
if not pa.types.is_integer(row_ids.type):
|
||||
raise ValueError(
|
||||
@@ -619,7 +722,8 @@ def _normalize_blob_row_ids(
|
||||
if row_id < 0:
|
||||
raise ValueError("row ids must be non-negative")
|
||||
normalized.append(row_id)
|
||||
return normalized
|
||||
version, snapshot_identity = snapshot if snapshot else (None, None)
|
||||
return _BlobRowIdSelection(normalized, version, snapshot_identity)
|
||||
|
||||
|
||||
def _wrap_blob_files(handles: Iterable[object]) -> list[Optional[BlobFile]]:
|
||||
|
||||
@@ -25,6 +25,8 @@ from .index import (
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -116,7 +118,7 @@ class PyExpr:
|
||||
|
||||
def expr_col(name: str) -> PyExpr: ...
|
||||
def expr_lit(
|
||||
value: Union[bool, int, float, str, bytes, date, datetime, Decimal],
|
||||
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
|
||||
) -> PyExpr: ...
|
||||
def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ...
|
||||
|
||||
@@ -184,12 +186,20 @@ class Connection(object):
|
||||
limit: Optional[int],
|
||||
) -> list[str]: ... # Deprecated: Use list_tables instead
|
||||
async def open_job(self, job_id: str) -> Job: ...
|
||||
async def server_info(self) -> str: ...
|
||||
async def list_gpu_classes(self) -> list[GpuClass]: ...
|
||||
async def create_function_async(
|
||||
self, request_json: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
request_json: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> Job: ...
|
||||
async def get_function(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
version: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> str: ...
|
||||
def list_functions(
|
||||
self,
|
||||
@@ -201,6 +211,9 @@ class Connection(object):
|
||||
async def drop_function(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
) -> bool: ...
|
||||
async def _drop_function_with_warnings(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Tuple[bool, list[str]]: ...
|
||||
async def drop_function_async(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Tuple[bool, Job]: ...
|
||||
@@ -221,7 +234,12 @@ class Connection(object):
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> None: ...
|
||||
async def create_secret(
|
||||
self, name: str, value: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
value: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> None: ...
|
||||
async def alter_secret(
|
||||
self, name: str, value: str, namespace_path: Optional[List[str]] = None
|
||||
@@ -240,7 +258,12 @@ class Connection(object):
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Tuple[str, int, int]: ...
|
||||
async def create_view(
|
||||
self, name: str, query: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
query: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ...
|
||||
async def describe_view(
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
@@ -278,7 +301,19 @@ class Connection(object):
|
||||
page_limit: Optional[int] = None,
|
||||
) -> NameListing: ...
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> JobListing: ...
|
||||
async def cancel_job(self, job_id: str) -> bool: ...
|
||||
async def pause_job(self, job_id: str) -> str: ...
|
||||
@@ -299,6 +334,9 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table: ...
|
||||
async def create_empty_table(
|
||||
self,
|
||||
@@ -308,6 +346,8 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
) -> Table: ...
|
||||
async def open_table(
|
||||
self,
|
||||
@@ -325,6 +365,8 @@ class Connection(object):
|
||||
source_version: Optional[int] = None,
|
||||
source_tag: Optional[str] = None,
|
||||
is_shallow: bool = True,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> Table: ...
|
||||
async def rename_table(
|
||||
self,
|
||||
@@ -336,24 +378,30 @@ class Connection(object):
|
||||
async def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: str,
|
||||
source: Optional[str] = None,
|
||||
projections: Optional[List[Tuple[str, str]]] = None,
|
||||
filter: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> Table: ...
|
||||
async def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: str,
|
||||
source: Optional[str] = None,
|
||||
projections: Optional[List[Tuple[str, str]]] = None,
|
||||
filter: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> Job: ...
|
||||
def list_materialized_views(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
@@ -385,6 +433,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: ...
|
||||
@@ -405,6 +454,9 @@ class Job:
|
||||
) -> Optional[str]: ...
|
||||
async def cancel(self) -> None: ...
|
||||
async def refresh(self) -> None: ...
|
||||
async def timeline(self) -> str: ...
|
||||
async def stack(self, worker_id: str) -> str: ...
|
||||
async def stats(self) -> Optional[str]: ...
|
||||
async def events(
|
||||
self,
|
||||
*,
|
||||
@@ -465,6 +517,10 @@ class JobFailureInfo:
|
||||
@property
|
||||
def message(self) -> Optional[str]: ...
|
||||
@property
|
||||
def traceback(self) -> Optional[str]:
|
||||
"""User-code traceback, possibly truncated by the server."""
|
||||
...
|
||||
@property
|
||||
def retryable(self) -> Optional[bool]: ...
|
||||
@property
|
||||
def sql_job_id(self) -> Optional[str]: ...
|
||||
@@ -494,6 +550,8 @@ class JobDescription:
|
||||
class SqlQuery:
|
||||
@property
|
||||
def id(self) -> UUID: ...
|
||||
@property
|
||||
def job_id(self) -> Optional[str]: ...
|
||||
async def describe(self) -> QueryDescription: ...
|
||||
async def reader(self) -> RecordBatchStream: ...
|
||||
async def cancel(self) -> None: ...
|
||||
@@ -502,6 +560,8 @@ class QueryDescription:
|
||||
@property
|
||||
def id(self) -> UUID: ...
|
||||
@property
|
||||
def job_id(self) -> Optional[str]: ...
|
||||
@property
|
||||
def status(self) -> str: ...
|
||||
@property
|
||||
def progress(self) -> Optional[float]: ...
|
||||
@@ -515,6 +575,7 @@ class Table:
|
||||
def _is_native(self) -> bool: ...
|
||||
def close(self) -> None: ...
|
||||
async def schema(self) -> pa.Schema: ...
|
||||
def schema_sync(self) -> pa.Schema: ...
|
||||
async def add(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
@@ -522,7 +583,14 @@ class Table:
|
||||
progress: Optional[Any] = None,
|
||||
write_parallelism: Optional[int] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
retries: Optional[int] = None,
|
||||
) -> AddResult: ...
|
||||
async def execute_merge_insert(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
parameters: Dict[str, Any],
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult: ...
|
||||
async def update(
|
||||
self, updates: Dict[str, str], where: Optional[str]
|
||||
) -> UpdateResult: ...
|
||||
@@ -542,6 +610,8 @@ class Table:
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -549,6 +619,7 @@ class Table:
|
||||
*,
|
||||
name: Optional[str],
|
||||
train: Optional[bool],
|
||||
exist_ok: bool = False,
|
||||
): ...
|
||||
async def create_index_async(
|
||||
self,
|
||||
@@ -565,6 +636,8 @@ class Table:
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -572,6 +645,7 @@ class Table:
|
||||
*,
|
||||
name: Optional[str],
|
||||
train: Optional[bool],
|
||||
exist_ok: bool = False,
|
||||
) -> Job: ...
|
||||
async def list_versions(self) -> List[Dict[str, Any]]: ...
|
||||
async def version(self) -> int: ...
|
||||
@@ -580,6 +654,22 @@ class Table:
|
||||
async def restore(self, version: Optional[Union[int, str]] = None): ...
|
||||
async def prewarm_index(self, index_name: str) -> None: ...
|
||||
async def prewarm_data(self, columns: Optional[List[str]] = None) -> None: ...
|
||||
async def explain_prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
parameters: Optional[pa.RecordBatch] = None,
|
||||
) -> str: ...
|
||||
async def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
parameters: Optional[pa.RecordBatch] = None,
|
||||
) -> Job: ...
|
||||
async def list_indices(self) -> list[IndexConfig]: ...
|
||||
async def tokenize(
|
||||
self,
|
||||
@@ -598,6 +688,7 @@ class Table:
|
||||
columns: list[tuple[str, str]],
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[int] = None,
|
||||
auto_refresh_resource_budget: Optional[dict[str, int]] = None,
|
||||
) -> AddColumnsResult: ...
|
||||
async def add_function_columns(
|
||||
self,
|
||||
@@ -605,34 +696,113 @@ class Table:
|
||||
output_name: Optional[str],
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[int] = None,
|
||||
auto_refresh_resource_budget: Optional[dict[str, int]] = None,
|
||||
) -> AddColumnsResult: ...
|
||||
async def refresh_column(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[dict[str, int]] = None,
|
||||
supervisor_resources: Optional[dict[str, int]] = None,
|
||||
planning_workers: Optional[dict[str, Any]] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[str] = None,
|
||||
error_policy: Optional[str] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
retry_errors: bool = False,
|
||||
retry_job_id: Optional[str] = None,
|
||||
retry_error_type: Optional[str] = None,
|
||||
include_quarantined: bool = False,
|
||||
function_version: Optional[str] = None,
|
||||
recompute: Optional[Literal["failed", "all", "none"]] = None,
|
||||
) -> RefreshColumnResult: ...
|
||||
async def refresh_column_async(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[dict[str, int]] = None,
|
||||
supervisor_resources: Optional[dict[str, int]] = None,
|
||||
planning_workers: Optional[dict[str, Any]] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[str] = None,
|
||||
error_policy: Optional[str] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
retry_errors: bool = False,
|
||||
retry_job_id: Optional[str] = None,
|
||||
retry_error_type: Optional[str] = None,
|
||||
include_quarantined: bool = False,
|
||||
function_version: Optional[str] = None,
|
||||
recompute: Optional[Literal["failed", "all", "none"]] = None,
|
||||
) -> Job: ...
|
||||
async def function_errors(
|
||||
self,
|
||||
job_id: Optional[str] = None,
|
||||
column: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
history: bool = False,
|
||||
) -> FunctionErrors: ...
|
||||
async def quarantine_function_errors(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
quarantined: bool = True,
|
||||
job_id: Optional[str] = None,
|
||||
error_type: Optional[str] = None,
|
||||
after_attempts: Optional[int] = None,
|
||||
) -> int: ...
|
||||
async def function_provenance(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
limit: Optional[int] = None,
|
||||
version: Optional[int] = None,
|
||||
) -> str: ...
|
||||
async def column_statuses(
|
||||
self, column: Optional[str] = None
|
||||
) -> list[FunctionColumnStatus]: ...
|
||||
async def column_status(self, column: str) -> FunctionColumnStatus: ...
|
||||
async def wait_column_fresh(
|
||||
self, column: str, timeout: Optional[timedelta] = None
|
||||
) -> FunctionColumnStatus: ...
|
||||
async def refresh_materialized_view(
|
||||
self, source_version: Optional[int] = None, *, full: bool = False
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> RefreshMaterializedViewResult: ...
|
||||
async def refresh_materialized_view_async(
|
||||
self, source_version: Optional[int] = None, *, full: bool = False
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> Job: ...
|
||||
async def materialized_view_definition(self) -> str: ...
|
||||
async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ...
|
||||
@@ -642,6 +812,9 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def compact_async(
|
||||
self, compaction_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -677,7 +850,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,
|
||||
@@ -685,15 +863,23 @@ 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,
|
||||
*,
|
||||
version: Optional[int] = None,
|
||||
snapshot_identity: Optional[str] = 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:
|
||||
async def list(self) -> Dict[str, Tag]: ...
|
||||
async def get_version(self, tag: str) -> int: ...
|
||||
async def create(self, tag: str, version: int): ...
|
||||
async def create(self, tag: str, version: Optional[int] = None): ...
|
||||
async def delete(self, tag: str): ...
|
||||
async def update(self, tag: str, version: int): ...
|
||||
|
||||
@@ -704,6 +890,8 @@ class Branches:
|
||||
name: str,
|
||||
from_ref: Optional[str] = None,
|
||||
from_version: Optional[int] = None,
|
||||
*,
|
||||
from_tag: Optional[str] = None,
|
||||
) -> Table: ...
|
||||
async def checkout(self, name: str, version: Optional[int] = None) -> Table: ...
|
||||
async def delete(self, name: str) -> None: ...
|
||||
@@ -784,10 +972,17 @@ class Query:
|
||||
def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ...
|
||||
def nearest_to_text(self, query: dict) -> FTSQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
def scan_in_order(self, ordered: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -797,9 +992,13 @@ class Query:
|
||||
class TakeQuery:
|
||||
def select(self, columns: List[str]): ...
|
||||
def with_row_id(self): ...
|
||||
def preserve_order(self): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -821,10 +1020,17 @@ class FTSQuery:
|
||||
def add_query_vector(self, query_vec: pa.Array) -> None: ...
|
||||
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
async def count_rows(self) -> int: ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -834,6 +1040,12 @@ class FTSQuery:
|
||||
class VectorQuery:
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def where(self, filter: str): ...
|
||||
def where_expr(self, expr: PyExpr): ...
|
||||
def select(self, columns: List[Tuple[str, str]]): ...
|
||||
@@ -893,6 +1105,8 @@ class PyQueryRequest:
|
||||
limit: Optional[int]
|
||||
offset: Optional[int]
|
||||
take_offsets: Optional[List[int]]
|
||||
take_row_ids: Optional[List[int]]
|
||||
preserve_order: Optional[bool]
|
||||
filter: Optional[Union[str, bytes]]
|
||||
full_text_search: Optional[FullTextQuery]
|
||||
select: Optional[Union[str, List[str]]]
|
||||
@@ -916,6 +1130,7 @@ class PyQueryRequest:
|
||||
postfilter: Optional[bool]
|
||||
norm: Optional[str]
|
||||
order_by: Optional[List[ColumnOrdering]]
|
||||
scan_in_order: Optional[bool]
|
||||
|
||||
class CompactionStats:
|
||||
fragments_removed: int
|
||||
@@ -1003,9 +1218,15 @@ class RefreshColumnResult:
|
||||
version: int
|
||||
|
||||
class FunctionErrorRecord:
|
||||
first_seen_at_millis: Optional[int]
|
||||
last_seen_at_millis: Optional[int]
|
||||
quarantined: bool
|
||||
input: Optional[str]
|
||||
attempts: Optional[int]
|
||||
job_id: str
|
||||
fragment_id: int
|
||||
row_offset: Optional[int]
|
||||
row_id: Optional[int]
|
||||
row_address: Optional[int]
|
||||
column: str
|
||||
function: str
|
||||
@@ -1013,6 +1234,8 @@ class FunctionErrorRecord:
|
||||
table_version: int
|
||||
error_type: str
|
||||
error_message: str
|
||||
traceback: Optional[str]
|
||||
"""User-code traceback, possibly truncated by the server."""
|
||||
created_at_millis: int
|
||||
|
||||
class FunctionErrorFragment:
|
||||
@@ -1022,10 +1245,52 @@ class FunctionErrorFragment:
|
||||
rows_recorded: int
|
||||
|
||||
class FunctionErrors:
|
||||
workflow_version: Optional[int]
|
||||
error_groups_json: str
|
||||
records: list[FunctionErrorRecord]
|
||||
fragments: list[FunctionErrorFragment]
|
||||
truncated: bool
|
||||
|
||||
class FunctionColumnVersionStatus:
|
||||
name: str
|
||||
namespace_path: list[str]
|
||||
object_id: str
|
||||
location: str
|
||||
version: str
|
||||
manifest_digest: str
|
||||
|
||||
class FunctionColumnLastRefreshJob:
|
||||
job_id: str
|
||||
state: str
|
||||
automatic: Optional[bool]
|
||||
completed_at_millis: Optional[int]
|
||||
failure: Optional[JobFailureInfo]
|
||||
|
||||
class FunctionColumnAutoRefreshStatus:
|
||||
enabled: bool
|
||||
interval_seconds: Optional[int]
|
||||
active_job_id: Optional[str]
|
||||
state: str
|
||||
failure_streak: int
|
||||
effective_cooldown_millis: Optional[int]
|
||||
blocked_reason: Optional[str]
|
||||
next_run_at_millis: Optional[int]
|
||||
next_run_at_reason: Optional[str]
|
||||
|
||||
class FunctionColumnStatus:
|
||||
column: str
|
||||
binding_id: str
|
||||
function: FunctionColumnVersionStatus
|
||||
table_version: int
|
||||
rows: int
|
||||
fresh: int
|
||||
stale: int
|
||||
never_computed: int
|
||||
failed: int
|
||||
last_refresh_job: Optional[FunctionColumnLastRefreshJob]
|
||||
last_failure_job: Optional[FunctionColumnLastRefreshJob]
|
||||
auto_refresh: FunctionColumnAutoRefreshStatus
|
||||
|
||||
class RefreshMaterializedViewResult:
|
||||
@staticmethod
|
||||
def from_json(value: str) -> RefreshMaterializedViewResult: ...
|
||||
@@ -1054,7 +1319,12 @@ class AsyncPermutationBuilder:
|
||||
seed: Optional[int] = None,
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
def split_hash(
|
||||
self, columns: List[str], split_weights: List[int], *, discard_weight: int = 0
|
||||
self,
|
||||
columns: List[str],
|
||||
split_weights: List[int],
|
||||
*,
|
||||
discard_weight: Optional[int] = None,
|
||||
split_names: Optional[List[str]] = None,
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
def split_sequential(
|
||||
self,
|
||||
@@ -1117,6 +1387,7 @@ async def connect_catalog(
|
||||
sql_host_override: Optional[str] = None,
|
||||
read_consistency_interval: Optional[float] = None,
|
||||
oauth_config: Optional[Any] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
) -> Catalog: ...
|
||||
|
||||
class NameListing:
|
||||
@@ -1198,3 +1469,6 @@ class AuthzObject:
|
||||
) -> AuthzObject: ...
|
||||
def __str__(self) -> str: ...
|
||||
def __repr__(self) -> str: ...
|
||||
|
||||
def validate_function_retry_policy(json: str) -> None: ...
|
||||
def _validate_conda_requirement(requirement: str) -> None: ...
|
||||
|
||||
@@ -13,22 +13,51 @@ class BackgroundEventLoop:
|
||||
A background event loop that can run futures.
|
||||
|
||||
Used to bridge sync and async code, without messing with users event loops.
|
||||
|
||||
The loop and its thread are created by the first call to :meth:`run`, not
|
||||
by constructing this object, so importing lancedb does not leave an idle
|
||||
background thread behind.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._start()
|
||||
self.loop: asyncio.AbstractEventLoop | None = None
|
||||
self.thread: threading.Thread | None = None
|
||||
self._start_lock = threading.Lock()
|
||||
|
||||
def _start(self):
|
||||
self.loop = asyncio.new_event_loop()
|
||||
self.thread = threading.Thread(
|
||||
target=self.loop.run_forever,
|
||||
name="LanceDBBackgroundEventLoop",
|
||||
daemon=True,
|
||||
)
|
||||
self.thread.start()
|
||||
def _start(self) -> asyncio.AbstractEventLoop:
|
||||
loop = self.loop
|
||||
if loop is not None:
|
||||
return loop
|
||||
with self._start_lock:
|
||||
loop = self.loop
|
||||
if loop is not None:
|
||||
return loop
|
||||
loop = asyncio.new_event_loop()
|
||||
thread = threading.Thread(
|
||||
target=loop.run_forever,
|
||||
name="LanceDBBackgroundEventLoop",
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
# Publish the loop first and the thread last. Callers that reach
|
||||
# _start while this is in progress wait on _start_lock, so they
|
||||
# cannot observe a half-initialized loop/thread pair.
|
||||
self.loop = loop
|
||||
self.thread = thread
|
||||
return loop
|
||||
|
||||
def _reset_after_fork(self):
|
||||
# Threads do not survive fork(). Reset to the unstarted state without
|
||||
# calling into the inherited loop or thread: the thread is gone, and
|
||||
# it may have held _start_lock when the fork happened. A fresh lock
|
||||
# lets the child start a new loop on its first run().
|
||||
self.loop = None
|
||||
self.thread = None
|
||||
self._start_lock = threading.Lock()
|
||||
|
||||
def run(self, future):
|
||||
concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop)
|
||||
loop = self._start()
|
||||
concurrent_future = asyncio.run_coroutine_threadsafe(future, loop)
|
||||
try:
|
||||
return concurrent_future.result()
|
||||
except BaseException:
|
||||
@@ -60,12 +89,15 @@ _FORK_WARNED = False
|
||||
|
||||
|
||||
def _reset_after_fork():
|
||||
# Threads do not survive fork(), so the asyncio loop in LOOP.thread is
|
||||
# dead in the child. Re-initialize the singleton in place so existing
|
||||
# Threads do not survive fork(), so the loop in LOOP.thread is dead in
|
||||
# the child. Reset the singleton in place so existing
|
||||
# `from .background_loop import LOOP` references in other modules see
|
||||
# the new state. The Rust-side tokio runtime is reset analogously by a
|
||||
# pthread_atfork hook installed in the _lancedb extension.
|
||||
LOOP._start()
|
||||
# the unstarted state and create a fresh loop on their first run(). Do
|
||||
# not restart it here: the child may never use LanceDB, and the at-fork
|
||||
# handler must not touch the vanished thread or acquire inherited locks.
|
||||
# The Rust-side tokio runtime is reset analogously by a pthread_atfork
|
||||
# hook installed in the _lancedb extension.
|
||||
LOOP._reset_after_fork()
|
||||
# The embedding executor's worker threads are dead in the child as well.
|
||||
# Replace it with a fresh pool (threads are spawned lazily, so this is
|
||||
# cheap); we don't shut down the old one, since joining its dead workers
|
||||
|
||||
@@ -3,13 +3,17 @@
|
||||
|
||||
"""Remote catalogs manage databases."""
|
||||
|
||||
from functools import cached_property
|
||||
import os
|
||||
import warnings
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
from functools import cached_property
|
||||
from typing import Any, AsyncIterator, Iterator, Optional, Union
|
||||
|
||||
from . import _lancedb
|
||||
from .background_loop import LOOP
|
||||
from .authz import AsyncAuthorization, Authorization
|
||||
from .common import URI, sanitize_uri
|
||||
from .db import AsyncConnection, DBConnection
|
||||
from .remote import ClientConfig, OAuthConfig
|
||||
from .remote.db import RemoteDBConnection
|
||||
@@ -163,12 +167,14 @@ class Catalog:
|
||||
client_config=None,
|
||||
sql_host_override: Optional[str] = None,
|
||||
oauth_config: Optional[OAuthConfig] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
):
|
||||
self._inner = inner
|
||||
self._api_key = api_key
|
||||
self._client_config = client_config
|
||||
self._sql_host_override = sql_host_override
|
||||
self._oauth_config = oauth_config
|
||||
self._storage_options = storage_options
|
||||
|
||||
@cached_property
|
||||
def authz(self) -> Authorization:
|
||||
@@ -198,6 +204,7 @@ class Catalog:
|
||||
self._client_config,
|
||||
self._oauth_config,
|
||||
self._sql_host_override,
|
||||
self._storage_options,
|
||||
)
|
||||
|
||||
def list_databases(
|
||||
@@ -227,28 +234,71 @@ class Catalog:
|
||||
|
||||
|
||||
async def connect_catalog_async(
|
||||
endpoint: str,
|
||||
uri: Optional[URI] = None,
|
||||
*,
|
||||
api_key: Optional[str] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
region: Optional[str] = None,
|
||||
host_override: Optional[str] = None,
|
||||
sql_host_override: Optional[str] = None,
|
||||
read_consistency_interval: Optional[timedelta] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
session: Optional[_lancedb.Session] = None,
|
||||
manifest_enabled: bool = False,
|
||||
namespace_client_properties: Optional[dict[str, str]] = None,
|
||||
oauth_config: Optional[OAuthConfig] = None,
|
||||
) -> AsyncCatalog:
|
||||
"""Connect to an HTTP(S) server's root catalog.
|
||||
"""Connect to a server's root catalog using database connection settings.
|
||||
|
||||
``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise
|
||||
``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with
|
||||
[connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's
|
||||
database is ignored and requests target the root catalog.
|
||||
|
||||
``region`` is ignored with a warning when supplied. Catalog connections use
|
||||
the explicit endpoint rather than a region-derived Cloud (legacy) endpoint.
|
||||
``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable.
|
||||
Embedded-only ``session``, ``manifest_enabled`` and
|
||||
``namespace_client_properties`` are not supported.
|
||||
|
||||
Root requests omit database-selection headers. API key, client configuration,
|
||||
OAuth, and table read consistency settings are inherited by opened databases.
|
||||
OAuth, storage options, and table read consistency settings are inherited by
|
||||
opened databases.
|
||||
Database names containing slashes remain single logical names.
|
||||
Set ``sql_host_override`` to the SQL service endpoint to execute SQL through
|
||||
returned connections when the catalog endpoint uses HTTPS.
|
||||
"""
|
||||
if region is not None:
|
||||
warnings.warn(
|
||||
"region is ignored by connect_catalog_async; the catalog endpoint "
|
||||
"is selected by host_override or uri.",
|
||||
UserWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
for name, value in (
|
||||
("session", session),
|
||||
("manifest_enabled", manifest_enabled or None),
|
||||
("namespace_client_properties", namespace_client_properties),
|
||||
):
|
||||
if value is not None:
|
||||
raise NotImplementedError(
|
||||
f"{name} is not supported for catalog connections"
|
||||
)
|
||||
endpoint = host_override if host_override is not None else uri
|
||||
if endpoint is None:
|
||||
raise ValueError("uri or host_override is required for catalog connections")
|
||||
if isinstance(client_config, dict):
|
||||
client_config = ClientConfig(**client_config)
|
||||
if client_config is None:
|
||||
client_config = ClientConfig()
|
||||
if (
|
||||
api_key is None
|
||||
and oauth_config is None
|
||||
and client_config.header_provider is None
|
||||
):
|
||||
api_key = os.environ.get("LANCEDB_API_KEY")
|
||||
inner = await _lancedb.connect_catalog(
|
||||
endpoint,
|
||||
sanitize_uri(endpoint),
|
||||
api_key=api_key,
|
||||
client_config=client_config,
|
||||
sql_host_override=sql_host_override,
|
||||
@@ -258,32 +308,115 @@ async def connect_catalog_async(
|
||||
else None
|
||||
),
|
||||
oauth_config=oauth_config,
|
||||
storage_options=storage_options,
|
||||
)
|
||||
return AsyncCatalog(inner)
|
||||
|
||||
|
||||
def connect_catalog(
|
||||
endpoint: str,
|
||||
uri: Optional[URI] = None,
|
||||
*,
|
||||
api_key: Optional[str] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
region: Optional[str] = None,
|
||||
host_override: Optional[str] = None,
|
||||
sql_host_override: Optional[str] = None,
|
||||
read_consistency_interval: Optional[timedelta] = None,
|
||||
request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
session: Optional[_lancedb.Session] = None,
|
||||
manifest_enabled: bool = False,
|
||||
namespace_client_impl: Optional[str] = None,
|
||||
namespace_client_properties: Optional[dict[str, str]] = None,
|
||||
namespace_client_pushdown_operations: Optional[list[str]] = None,
|
||||
oauth_config: Optional[OAuthConfig] = None,
|
||||
**kwargs: Any,
|
||||
) -> Catalog:
|
||||
"""Connect synchronously to an HTTP(S) server's root catalog.
|
||||
"""Connect synchronously to a root catalog using database connection settings.
|
||||
|
||||
See [connect_catalog_async][lancedb.connect_catalog_async] for options.
|
||||
The inputs match [connect][lancedb.connect]; ``region`` is ignored with a
|
||||
warning when supplied. Namespace client options and embedded session settings
|
||||
are not supported. ``request_thread_pool`` is deprecated and unused, as in
|
||||
``connect``.
|
||||
Local filesystem and object-store catalogs are not supported.
|
||||
|
||||
Examples
|
||||
--------
|
||||
```python
|
||||
settings = {"api_key": "secret", "host_override": "https://my-server.example"}
|
||||
catalog = lancedb.connect_catalog("db://analytics", **settings)
|
||||
db = lancedb.connect("db://analytics", **settings)
|
||||
```
|
||||
"""
|
||||
unknown_kwargs = {
|
||||
key: value
|
||||
for key, value in kwargs.items()
|
||||
if key not in ("connection_timeout", "read_timeout")
|
||||
}
|
||||
if unknown_kwargs:
|
||||
raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}")
|
||||
for name, value in (
|
||||
("namespace_client_impl", namespace_client_impl),
|
||||
("namespace_client_pushdown_operations", namespace_client_pushdown_operations),
|
||||
):
|
||||
if value is not None:
|
||||
raise NotImplementedError(
|
||||
f"{name} is not supported for catalog connections"
|
||||
)
|
||||
if region is not None:
|
||||
warnings.warn(
|
||||
"region is ignored by connect_catalog; the catalog endpoint "
|
||||
"is selected by host_override or uri.",
|
||||
UserWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if request_thread_pool is not None:
|
||||
warnings.warn(
|
||||
"request_thread_pool is no longer used and will be removed in "
|
||||
"a future release.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if isinstance(client_config, dict):
|
||||
client_config = ClientConfig(**client_config)
|
||||
if client_config is None:
|
||||
client_config = ClientConfig()
|
||||
for name, field in (
|
||||
("connection_timeout", "connect_timeout"),
|
||||
("read_timeout", "read_timeout"),
|
||||
):
|
||||
if kwargs.get(name) is not None:
|
||||
warnings.warn(
|
||||
f"{name} is deprecated and will be removed in a future release. "
|
||||
f"Please use client_config.timeout_config.{field} instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
setattr(
|
||||
client_config.timeout_config,
|
||||
field,
|
||||
timedelta(seconds=kwargs[name]),
|
||||
)
|
||||
if (
|
||||
api_key is None
|
||||
and oauth_config is None
|
||||
and client_config.header_provider is None
|
||||
):
|
||||
api_key = os.environ.get("LANCEDB_API_KEY")
|
||||
return Catalog(
|
||||
LOOP.run(
|
||||
connect_catalog_async(
|
||||
endpoint,
|
||||
uri,
|
||||
api_key=api_key,
|
||||
host_override=host_override,
|
||||
client_config=client_config,
|
||||
sql_host_override=sql_host_override,
|
||||
read_consistency_interval=read_consistency_interval,
|
||||
storage_options=storage_options,
|
||||
session=session,
|
||||
manifest_enabled=manifest_enabled,
|
||||
namespace_client_properties=namespace_client_properties,
|
||||
oauth_config=oauth_config,
|
||||
)
|
||||
),
|
||||
@@ -291,4 +424,5 @@ def connect_catalog(
|
||||
client_config=client_config,
|
||||
sql_host_override=sql_host_override,
|
||||
oauth_config=oauth_config,
|
||||
storage_options=storage_options,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable remote compaction jobs."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompactionResult:
|
||||
"""Actual committed outcome of one remote compaction invocation.
|
||||
|
||||
``rows_failed`` counts planned live rows that were not committed, including
|
||||
partial progress. ``more_work`` means a bounded run left eligible work for
|
||||
another invocation. File/fragment counts are None if an older worker did
|
||||
not report them; they are never inferred from unrelated table versions.
|
||||
File counts include deletion files as well as data files.
|
||||
"""
|
||||
|
||||
partial_commit: bool
|
||||
rows_succeeded: int
|
||||
rows_failed: int
|
||||
completion_percentage: float
|
||||
more_work: bool = False
|
||||
files_added: Optional[int] = None
|
||||
files_removed: Optional[int] = None
|
||||
fragments_added: Optional[int] = None
|
||||
fragments_removed: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CompactionResult":
|
||||
"""Decode a server result, ignoring additive fields from newer servers."""
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
+626
-93
File diff suppressed because it is too large
Load Diff
@@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func
|
||||
|
||||
__all__ = ["Expr", "col", "lit", "func"]
|
||||
|
||||
_NOT_LITERAL = object()
|
||||
|
||||
_STR_TO_PA_TYPE: dict = {
|
||||
"bool": pa.bool_(),
|
||||
"boolean": pa.bool_(),
|
||||
@@ -92,9 +94,16 @@ class Expr:
|
||||
# for dict keys / set membership.
|
||||
__hash__ = None # type: ignore[assignment]
|
||||
|
||||
def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
inner: PyExpr,
|
||||
*,
|
||||
column_path: str | None = None,
|
||||
literal_value: object = _NOT_LITERAL,
|
||||
) -> None:
|
||||
self._inner = inner
|
||||
self._column_path = column_path
|
||||
self._literal_value = literal_value
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
# An Expr describes a predicate that the query engine evaluates per row,
|
||||
@@ -301,14 +310,16 @@ def col(name: str) -> Expr:
|
||||
return Expr(expr_col(name), column_path=name)
|
||||
|
||||
|
||||
def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr:
|
||||
def lit(
|
||||
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
|
||||
) -> Expr:
|
||||
"""Create a literal (constant) value expression.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
value:
|
||||
A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``,
|
||||
``datetime``, or ``Decimal``.
|
||||
``datetime``, ``Decimal``, or ``None`` for SQL NULL.
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) ->
|
||||
>>> col("price") * lit(1.1)
|
||||
Expr((price * 1.1))
|
||||
"""
|
||||
if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)):
|
||||
if value is not None and not isinstance(
|
||||
value, (bool, int, float, str, bytes, date, datetime, Decimal)
|
||||
):
|
||||
raise TypeError(f"Unsupported literal type: {type(value).__name__}")
|
||||
|
||||
return Expr(expr_lit(value))
|
||||
return Expr(expr_lit(value), literal_value=value)
|
||||
|
||||
|
||||
def func(name: str, *args: ExprLike) -> Expr:
|
||||
|
||||
+1491
-190
File diff suppressed because it is too large
Load Diff
@@ -130,6 +130,62 @@ class NGram:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZoneMap:
|
||||
"""Describe a ZoneMap index configuration.
|
||||
|
||||
A `ZoneMap` index stores compact min and max summaries for contiguous
|
||||
ranges (zones) of rows. During a scan it skips any zone whose summary
|
||||
cannot satisfy the predicate, so it accelerates range and equality
|
||||
filters such as `col > 10`, `col BETWEEN a AND b`, and `col = x`,
|
||||
without changing the results.
|
||||
|
||||
It suits large numeric or temporal columns whose values are correlated
|
||||
with row order (for example `timestamp`, `price`, `id`).
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class RTree:
|
||||
"""Describe an RTree index configuration.
|
||||
|
||||
`RTree` is a scalar index on a GeoArrow geometry column, that is, a column
|
||||
whose Arrow field metadata sets ``ARROW:extension:name`` to a GeoArrow type
|
||||
such as ``geoarrow.point``, ``geoarrow.polygon`` or ``geoarrow.wkb``. It
|
||||
stores the bounding box of each geometry and accelerates spatial filters
|
||||
passed to ``where()``.
|
||||
|
||||
The index accelerates ``ST_Intersects``, ``ST_Contains``, ``ST_Within``,
|
||||
``ST_Touches``, ``ST_Crosses``, ``ST_Overlaps``, ``ST_Covers`` and
|
||||
``ST_CoveredBy`` between the indexed column and a constant geometry, in
|
||||
either argument order, for example
|
||||
``ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))``, as well as
|
||||
``geom IS NULL``. These filters can be combined with other conditions
|
||||
using ``AND``.
|
||||
|
||||
See the R-tree section of <https://docs.lancedb.com/indexing/scalar-index>
|
||||
for storing geometry, the other spatial functions, and spatial filters on
|
||||
vector search.
|
||||
|
||||
Remote tables send the ``RTREE`` index type to the server, which must
|
||||
support it.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> config = RTree(page_size=1024)
|
||||
|
||||
Attributes
|
||||
----------
|
||||
page_size : int, optional
|
||||
The maximum number of entries in each R-tree page. Must be at least 2.
|
||||
``None`` uses Lance's default of 4096.
|
||||
"""
|
||||
|
||||
page_size: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FTS:
|
||||
"""Describe a FTS index configuration.
|
||||
@@ -984,4 +1040,5 @@ __all__ = [
|
||||
"LabelList",
|
||||
"Fm",
|
||||
"NGram",
|
||||
"RTree",
|
||||
]
|
||||
|
||||
+244
-22
@@ -5,8 +5,13 @@
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import reprlib
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
from os import PathLike
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Generic, Optional, TypeVar, cast
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -15,6 +20,9 @@ from lancedb.background_loop import LOOP
|
||||
|
||||
from . import _lancedb
|
||||
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
|
||||
from .functions import RefreshColumnResult
|
||||
from .compaction import CompactionResult
|
||||
from .prewarm import PrewarmDataResult
|
||||
from .remote.errors import HttpError, RetryError
|
||||
|
||||
T = TypeVar("T")
|
||||
@@ -50,11 +58,13 @@ def _timeout_message(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_job_progress(progress):
|
||||
def _normalize_job_progress(progress, *, query=False):
|
||||
"""Normalize ``wait(progress=...)`` using the same convention as writes."""
|
||||
if progress is True:
|
||||
from tqdm.auto import tqdm
|
||||
|
||||
if query:
|
||||
return tqdm(bar_format="Query{postfix} [{elapsed}]"), True
|
||||
return tqdm(unit=" rows"), True
|
||||
if progress is False or progress is None:
|
||||
return None, False
|
||||
@@ -62,6 +72,7 @@ def _normalize_job_progress(progress):
|
||||
|
||||
|
||||
_ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000
|
||||
_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0
|
||||
|
||||
|
||||
def _progress_eta(previous, current):
|
||||
@@ -139,6 +150,19 @@ def _job_progress_callback(progress, enrich):
|
||||
planned = snapshot.get("rows_planned")
|
||||
remaining = snapshot.get("rows_remaining")
|
||||
computed = snapshot.get("rows_computed")
|
||||
job_type = snapshot.get("job_type")
|
||||
maintenance = job_type in ("compact", "prewarm_page_cache")
|
||||
if job_type == "compact":
|
||||
computed = snapshot.get("rows_rewritten")
|
||||
remaining = None
|
||||
if hasattr(progress, "unit"):
|
||||
progress.unit = " rows"
|
||||
elif job_type == "prewarm_page_cache":
|
||||
planned = snapshot.get("executors_targeted")
|
||||
computed = snapshot.get("executors_completed")
|
||||
remaining = None
|
||||
if hasattr(progress, "unit"):
|
||||
progress.unit = " executors"
|
||||
if isinstance(planned, int):
|
||||
epoch = snapshot.get("execution_epoch")
|
||||
reset = (isinstance(last_planned, int) and planned < last_planned) or (
|
||||
@@ -164,7 +188,7 @@ def _job_progress_callback(progress, enrich):
|
||||
if completed is not None:
|
||||
if isinstance(planned, int):
|
||||
completed = min(completed, planned)
|
||||
if first_snapshot and completed < last_rows:
|
||||
if (first_snapshot or maintenance) and completed < last_rows:
|
||||
# The server may have started a new execution while a
|
||||
# caller-owned bar retained its old position.
|
||||
last_rows = completed
|
||||
@@ -200,6 +224,7 @@ class AsyncJob(Generic[T]):
|
||||
self._inner = inner
|
||||
self._result_decoder = result_decoder
|
||||
self._last_progress_snapshot = None
|
||||
self._created_at = time.monotonic()
|
||||
|
||||
def _enrich_progress(self, snapshot):
|
||||
enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
|
||||
@@ -232,17 +257,29 @@ class AsyncJob(Generic[T]):
|
||||
async def progress(self) -> Optional[dict[str, Any]]:
|
||||
"""Fetch a structured progress snapshot.
|
||||
|
||||
Registry jobs always report lifecycle fields. Queue metadata and
|
||||
counters are included when supplied by the server. Older servers may
|
||||
Registry jobs always report lifecycle fields. SQL query handles report
|
||||
lifecycle state and ``client_elapsed_time_millis``, measured since this
|
||||
handle was created. They do not expose server build phases or logs.
|
||||
Queue metadata and counters are included when supplied by the server.
|
||||
Older servers may
|
||||
omit counters, and in-process operations return ``None``. A missing
|
||||
counter is unknown rather than zero. This is additive to :meth:`status`,
|
||||
whose string contract is unchanged.
|
||||
"""
|
||||
if self._inner is None:
|
||||
return None
|
||||
await self._inner.status()
|
||||
state = await self._inner.status()
|
||||
description = getattr(self._inner, "_description", None)
|
||||
if description is None or description.progress is None:
|
||||
if self.job_type == "query":
|
||||
return {
|
||||
"job_id": self.id,
|
||||
"job_type": "query",
|
||||
"state": state,
|
||||
"client_elapsed_time_millis": int(
|
||||
(time.monotonic() - self._created_at) * 1_000
|
||||
),
|
||||
}
|
||||
return None
|
||||
return self._enrich_progress(description.progress)
|
||||
|
||||
@@ -265,8 +302,19 @@ class AsyncJob(Generic[T]):
|
||||
a caller-owned bar with the server's current completed rows and total;
|
||||
later observations in a stable execution epoch use a high-water mark. A
|
||||
new execution epoch or smaller plan resets the bar to that plan.
|
||||
Maintenance jobs display reported rewritten rows or completed executors;
|
||||
revised maintenance counters replace earlier retry observations. Totals
|
||||
remain unknown until the server reports them. Rewritten rows describe
|
||||
execution work, not committed compaction results.
|
||||
``False`` preserves the original wait behavior.
|
||||
|
||||
For SQL-backed Function registration, progress shows the query's
|
||||
lifecycle state and client elapsed time. It observes the existing
|
||||
query handle while its original waiter runs; it does not resubmit or
|
||||
cancel the registration. Detailed bake phases and build logs are not
|
||||
available from the current query handle. Failure exceptions retain the
|
||||
server's cause and request identifiers.
|
||||
|
||||
Raises `JobFailedError` if the operation failed, `JobCancelledError`
|
||||
if it was cancelled, and `TimeoutError` if `timeout` elapses first.
|
||||
Transient connection and read errors are retried with capped exponential
|
||||
@@ -282,7 +330,10 @@ class AsyncJob(Generic[T]):
|
||||
"""
|
||||
if self._inner is None:
|
||||
return cast(T, None)
|
||||
progress_obj, owns = _normalize_job_progress(progress)
|
||||
query_progress = (
|
||||
progress is not False and progress is not None and self.job_type == "query"
|
||||
)
|
||||
progress_obj, owns = _normalize_job_progress(progress, query=query_progress)
|
||||
progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
|
||||
last_error = None
|
||||
|
||||
@@ -308,13 +359,46 @@ class AsyncJob(Generic[T]):
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, 30.0)
|
||||
|
||||
async def observe_query():
|
||||
async def report():
|
||||
try:
|
||||
snapshot = await self.progress()
|
||||
if snapshot is not None:
|
||||
progress_callback(snapshot)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning(
|
||||
"job progress observer failed", exc_info=True
|
||||
)
|
||||
|
||||
waiter = asyncio.create_task(wait_with_retries())
|
||||
try:
|
||||
while not waiter.done():
|
||||
await report()
|
||||
await asyncio.wait(
|
||||
{waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS
|
||||
)
|
||||
try:
|
||||
return await waiter
|
||||
finally:
|
||||
await report()
|
||||
finally:
|
||||
if not waiter.done():
|
||||
waiter.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await waiter
|
||||
|
||||
wait_for_result = (
|
||||
observe_query
|
||||
if query_progress and progress_callback is not None
|
||||
else wait_with_retries
|
||||
)
|
||||
try:
|
||||
try:
|
||||
if timeout is None:
|
||||
result = await wait_with_retries()
|
||||
result = await wait_for_result()
|
||||
else:
|
||||
result = await asyncio.wait_for(
|
||||
wait_with_retries(), timeout.total_seconds()
|
||||
wait_for_result(), timeout.total_seconds()
|
||||
)
|
||||
except asyncio.TimeoutError as error:
|
||||
if last_error is None:
|
||||
@@ -422,6 +506,81 @@ class AsyncJob(Generic[T]):
|
||||
description = self._inner._description if self._inner is not None else None
|
||||
return getattr(description, name) if description is not None else None
|
||||
|
||||
async def stack(self, worker_id: str) -> dict[str, Any]:
|
||||
"""Capture Python thread stacks from a running Function worker.
|
||||
|
||||
Requires server support and system operate privilege. The response has
|
||||
``status``, ``worker_id``, ``execution_epoch`` and ``stacks``. Each session
|
||||
reports its status, capture timestamp, Python frames and truncation.
|
||||
``omitted_sessions`` counts sessions beyond the server's capture limit.
|
||||
Captures exclude source text, locals and native frames; a recent capture
|
||||
may be reused to bound overhead. Unsupported or unavailable captures
|
||||
have an explicit status. Transport and authorization errors propagate.
|
||||
Local operations and SQL query handles raise ``NotImplementedError``.
|
||||
Timeout stack evidence remains in the job's failure events.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> evidence = await job.stack("worker-id") # doctest: +SKIP
|
||||
>>> print(evidence["stacks"]) # doctest: +SKIP
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"worker stacks require a server-side Function job"
|
||||
)
|
||||
return json.loads(await self._inner.stack(worker_id))
|
||||
|
||||
async def stats(self) -> Optional[str]:
|
||||
"""Return a printable run report for this Function job.
|
||||
|
||||
The report includes recorded phase timings, finishing-supervisor slot
|
||||
occupancy, all-attempt split execution and batch latency, and accepted-row
|
||||
throughput. Each call reads the current server report.
|
||||
Returns ``None`` while the job is running or if no recorded profile is
|
||||
available, without waiting for completion. Missing measurements remain
|
||||
unavailable rather than becoming zero. The server formats the report;
|
||||
the SDK returns it verbatim.
|
||||
|
||||
Requires a server-side Function job and a server supporting run reports.
|
||||
Local operations and SQL query handles do not support this operation.
|
||||
Unsupported operations raise ``NotImplementedError`` or a server error.
|
||||
This method returns text; use ``print`` to display it.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> print(await job.stats()) # doctest: +SKIP
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"job statistics require a server-side Function job"
|
||||
)
|
||||
return await self._inner.stats()
|
||||
|
||||
async def export_timeline(self, path: str | PathLike[str]) -> None:
|
||||
"""Write a fresh recorded Function job timeline as Chrome trace JSON.
|
||||
|
||||
Open the file in Perfetto or Chrome tracing. The recording contains
|
||||
retained split spans grouped by worker and timestamped job phases.
|
||||
Batch counts and latency statistics are included as details; individual
|
||||
batch timestamps are not recorded. Running jobs export a partial snapshot
|
||||
without waiting or cancelling. Download again to include later work.
|
||||
|
||||
Requires a server-side Function job and a server supporting timeline
|
||||
export. Unsupported operations raise ``NotImplementedError`` or a server
|
||||
error. The destination is overwritten only after the trace is fetched.
|
||||
Filesystem errors propagate to the caller.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> await job.export_timeline("refresh.trace.json") # doctest: +SKIP
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"job timeline export requires a server-side Function job"
|
||||
)
|
||||
trace = await self._inner.timeline()
|
||||
await asyncio.to_thread(Path(path).write_text, trace, encoding="utf-8")
|
||||
|
||||
async def events(
|
||||
self,
|
||||
*,
|
||||
@@ -461,43 +620,49 @@ class AsyncJob(Generic[T]):
|
||||
|
||||
|
||||
_REPR_INDENT = " " * 4
|
||||
_REPR_MAX_FIELD_LENGTH = 240
|
||||
_PAYLOAD_REPR = reprlib.Repr()
|
||||
_PAYLOAD_REPR.maxlevel = 2
|
||||
_PAYLOAD_REPR.maxdict = 4
|
||||
_PAYLOAD_REPR.maxlist = 4
|
||||
_PAYLOAD_REPR.maxtuple = 4
|
||||
_PAYLOAD_REPR.maxstring = 120
|
||||
_PAYLOAD_REPR.maxother = 120
|
||||
|
||||
|
||||
def _repr_payload(value: Any) -> str:
|
||||
"""Render a job payload as indented JSON, aligned under its field."""
|
||||
try:
|
||||
rendered = json.dumps(value, indent=4)
|
||||
except TypeError:
|
||||
return repr(value)
|
||||
return rendered.replace("\n", "\n" + _REPR_INDENT)
|
||||
"""Bound nested payload previews without changing the stored values."""
|
||||
rendered = _PAYLOAD_REPR.repr(value).replace("\n", "\\n")
|
||||
if len(rendered) > _REPR_MAX_FIELD_LENGTH:
|
||||
return rendered[: _REPR_MAX_FIELD_LENGTH - 3] + "..."
|
||||
return rendered
|
||||
|
||||
|
||||
def _job_repr(kind: str, job: Any) -> str:
|
||||
"""Render every field the handle currently knows, omitting the rest.
|
||||
"""Show cached job identity and bounded previews without backend calls.
|
||||
|
||||
One field per line, with the JSON payloads indented, because a refresh
|
||||
job's spec and result are the point of printing it.
|
||||
The complete payloads remain available through ``spec`` and ``result``.
|
||||
"""
|
||||
state = job.state
|
||||
if state is None:
|
||||
# Nothing has been fetched yet, so there is nothing to lay out.
|
||||
known = f"id={job.id!r}, " if job.id is not None else ""
|
||||
known = f"id={_repr_payload(job.id)}, " if job.id is not None else ""
|
||||
return f"{kind}({known}not refreshed)"
|
||||
|
||||
fields = []
|
||||
if job.id is not None:
|
||||
fields.append(f"id={job.id!r}")
|
||||
fields.append(f"state={state!r}")
|
||||
fields.append(f"id={_repr_payload(job.id)}")
|
||||
fields.append(f"state={_repr_payload(state)}")
|
||||
for name in ("job_type", "creation_ms"):
|
||||
value = getattr(job, name)
|
||||
if value is not None:
|
||||
fields.append(f"{name}={value!r}")
|
||||
fields.append(f"{name}={_repr_payload(value)}")
|
||||
for name in ("spec", "result"):
|
||||
value = getattr(job, name)
|
||||
if value is not None:
|
||||
fields.append(f"{name}={_repr_payload(value)}")
|
||||
if job.failure is not None:
|
||||
fields.append(f"failure={job.failure!r}")
|
||||
fields.append(f"failure={_repr_payload(job.failure)}")
|
||||
body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields)
|
||||
return f"{kind}({body}\n)"
|
||||
|
||||
@@ -615,6 +780,53 @@ class Job(Generic[T]):
|
||||
def _field(self, name: str) -> Optional[Any]:
|
||||
return getattr(self._inner, name) if self._inner is not None else None
|
||||
|
||||
def stack(self, worker_id: str) -> dict[str, Any]:
|
||||
"""Capture Python thread stacks from a running Function worker.
|
||||
|
||||
See [AsyncJob.stack][lancedb.job.AsyncJob.stack] for availability,
|
||||
permissions and response fields.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> print(job.stack("worker-id")["stacks"]) # doctest: +SKIP
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"worker stacks require a server-side Function job"
|
||||
)
|
||||
return LOOP.run(self._inner.stack(worker_id))
|
||||
|
||||
def stats(self) -> Optional[str]:
|
||||
"""Return a printable Function job run report.
|
||||
|
||||
See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> print(job.stats()) # doctest: +SKIP
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"job statistics require a server-side Function job"
|
||||
)
|
||||
return LOOP.run(self._inner.stats())
|
||||
|
||||
def export_timeline(self, path: str | PathLike[str]) -> None:
|
||||
"""Write Chrome trace JSON for this Function job.
|
||||
|
||||
See :meth:`AsyncJob.export_timeline`. Open the file in Perfetto or
|
||||
Chrome tracing.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> job.export_timeline("refresh.trace.json") # doctest: +SKIP
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"job timeline export requires a server-side Function job"
|
||||
)
|
||||
return LOOP.run(self._inner.export_timeline(path))
|
||||
|
||||
def events(
|
||||
self,
|
||||
*,
|
||||
@@ -643,3 +855,13 @@ def _typed_job(
|
||||
) -> AsyncJob[T]:
|
||||
"""Bind an internal JSON-producing job to its public result model."""
|
||||
return AsyncJob(inner, result_decoder)
|
||||
|
||||
|
||||
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
|
||||
if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
|
||||
return _typed_job(inner, RefreshColumnResult.from_json)
|
||||
if inner.job_type == "prewarm_page_cache":
|
||||
return _typed_job(inner, PrewarmDataResult.from_json)
|
||||
if inner.job_type == "compact":
|
||||
return _typed_job(inner, CompactionResult.from_json)
|
||||
return AsyncJob(inner)
|
||||
|
||||
@@ -6,7 +6,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
|
||||
from collections import deque
|
||||
from itertools import islice
|
||||
from operator import index
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Callable,
|
||||
Generic,
|
||||
Iterator,
|
||||
Optional,
|
||||
TypeVar,
|
||||
overload,
|
||||
)
|
||||
|
||||
from .background_loop import LOOP
|
||||
|
||||
@@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]):
|
||||
print(name)
|
||||
|
||||
Use ``list(connection.list_views())`` to collect all results.
|
||||
|
||||
Indexes and slices refer to the remaining items and do not consume them.
|
||||
A bounded forward slice, such as ``listing[:5]``, fetches only enough pages
|
||||
to reach its stop. ``len(listing)``, negative indexes, and open-ended or
|
||||
reverse slices fetch and cache all remaining results. Iteration then drains
|
||||
that cache. These operations may perform requests and raise request errors.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: AsyncListing[T]):
|
||||
self._inner = inner
|
||||
self._buffer: deque[T] = deque()
|
||||
|
||||
def __iter__(self) -> Listing[T]:
|
||||
return self
|
||||
|
||||
def __next__(self) -> T:
|
||||
if self._buffer:
|
||||
return self._buffer.popleft()
|
||||
try:
|
||||
return LOOP.run(self._inner.__anext__())
|
||||
except StopAsyncIteration:
|
||||
raise StopIteration from None
|
||||
|
||||
def _fill(self, count: Optional[int]) -> None:
|
||||
while count is None or len(self._buffer) < count:
|
||||
try:
|
||||
item = LOOP.run(self._inner.__anext__())
|
||||
except StopAsyncIteration:
|
||||
return
|
||||
self._buffer.append(item)
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""Fetch and cache every remaining item, returning the remaining count."""
|
||||
self._fill(None)
|
||||
return len(self._buffer)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
self._fill(1)
|
||||
return bool(self._buffer)
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: int) -> T: ...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: slice) -> list[T]: ...
|
||||
|
||||
def __getitem__(self, key: int | slice) -> T | list[T]:
|
||||
"""Read remaining items without consuming them; bounded slices stay lazy."""
|
||||
if isinstance(key, slice):
|
||||
start = 0 if key.start is None else index(key.start)
|
||||
stop = None if key.stop is None else index(key.stop)
|
||||
step = 1 if key.step is None else index(key.step)
|
||||
if step == 0:
|
||||
raise ValueError("slice step cannot be zero")
|
||||
if start >= 0 and stop is not None and stop >= 0 and step > 0:
|
||||
if start >= stop:
|
||||
return []
|
||||
self._fill(stop)
|
||||
start, stop, step = key.indices(len(self._buffer))
|
||||
return list(
|
||||
islice(self._buffer, start, stop, min(step, len(self._buffer) + 1))
|
||||
)
|
||||
self._fill(None)
|
||||
return list(self._buffer)[key]
|
||||
position = index(key)
|
||||
self._fill(None if position < 0 else position + 1)
|
||||
return self._buffer[position]
|
||||
|
||||
def num_page_results(self) -> int:
|
||||
"""Return the number of cached items available without another request."""
|
||||
return self._inner.num_page_results()
|
||||
return len(self._buffer) + self._inner.num_page_results()
|
||||
|
||||
def page_token(self) -> Optional[str]:
|
||||
"""Return the next request's token.
|
||||
|
||||
See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token]
|
||||
for initial, cached, final-page, and error behavior.
|
||||
Indexing, slicing, and counting can also advance this token; drain all
|
||||
``num_page_results()`` cached items before resuming from it.
|
||||
"""
|
||||
return self._inner.page_token()
|
||||
|
||||
@@ -175,6 +243,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]):
|
||||
class AsyncTableListing(_AsyncPagedNameListing):
|
||||
"""Awaitable table iterator; awaiting loads one page.
|
||||
|
||||
Iteration fetches all pages. The ``tables`` attribute contains only the
|
||||
current page, so use ``await db.table_exists([name])`` for existence checks.
|
||||
|
||||
For example::
|
||||
|
||||
page = await db.list_tables(limit=20)
|
||||
@@ -229,6 +300,10 @@ class _PagedNameListing(Iterator[str]):
|
||||
class TableListing(_PagedNameListing):
|
||||
"""Table iterator retaining the current page as a list.
|
||||
|
||||
Iteration fetches all pages. The ``tables`` attribute contains only the
|
||||
current page, so use ``db.table_exists([name])`` or ``name in db`` for
|
||||
existence checks. Use ``list(db.list_tables())`` to collect all names.
|
||||
|
||||
For example::
|
||||
|
||||
page = db.list_tables(limit=20)
|
||||
@@ -239,6 +314,7 @@ class TableListing(_PagedNameListing):
|
||||
|
||||
@property
|
||||
def tables(self) -> list[str]:
|
||||
"""A copy of the table names in the most recently fetched page."""
|
||||
return self._inner.tables
|
||||
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .functions import _validate_gpu_class_name
|
||||
from .background_loop import LOOP
|
||||
from .job import AsyncJob, Job, _typed_job
|
||||
|
||||
@@ -133,6 +134,16 @@ def _quote_identifier(name: str) -> str:
|
||||
return f"`{escaped}`"
|
||||
|
||||
|
||||
def _validate_create_materialized_view(source, query, select, where, limit):
|
||||
if query is not None:
|
||||
if any(value is not None for value in (source, select, where, limit)):
|
||||
raise ValueError(
|
||||
"query cannot be combined with source, select, where or limit"
|
||||
)
|
||||
elif source is None:
|
||||
raise ValueError("either source or query must be provided")
|
||||
|
||||
|
||||
def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
|
||||
"""``select`` items may be a column name, an ``(alias, expression)`` pair,
|
||||
or a dict of the same. A bare name projects itself and is quoted, so any
|
||||
@@ -156,6 +167,34 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _refresh_execution_options(cpu_millis, memory_bytes, gpu_count, gpu_class):
|
||||
values = {
|
||||
"cpu_millis": cpu_millis,
|
||||
"memory_bytes": memory_bytes,
|
||||
"gpu_count": gpu_count,
|
||||
}
|
||||
for name, value in values.items():
|
||||
maximum = 2**32 - 1 if name == "gpu_count" else 2**64 - 1
|
||||
minimum = 0 if name == "gpu_count" else 1
|
||||
if value is not None and (
|
||||
type(value) is not int or not minimum <= value <= maximum
|
||||
):
|
||||
raise ValueError(
|
||||
f"{name} must be an integer between {minimum} and {maximum}"
|
||||
)
|
||||
if (cpu_millis is not None or memory_bytes is not None) and any(
|
||||
value is None for value in values.values()
|
||||
):
|
||||
raise ValueError(
|
||||
"cpu_millis, memory_bytes, and gpu_count must be specified together"
|
||||
)
|
||||
if gpu_class is not None:
|
||||
values["gpu_class"] = _validate_gpu_class_name(gpu_class)
|
||||
if gpu_count == 0:
|
||||
raise ValueError("gpu_class requires a positive GPU budget")
|
||||
return {name: value for name, value in values.items() if value is not None}
|
||||
|
||||
|
||||
class AsyncMaterializedView:
|
||||
"""A handle on a materialized view: its table plus its definition.
|
||||
|
||||
@@ -185,7 +224,14 @@ class AsyncMaterializedView:
|
||||
return _definition_from_json(raw)
|
||||
|
||||
async def refresh(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "RefreshMaterializedViewResult":
|
||||
"""Recompute the view from its source.
|
||||
|
||||
@@ -194,16 +240,35 @@ class AsyncMaterializedView:
|
||||
and ``source_version`` selects a source version instead of the latest.
|
||||
LanceDB Enterprise SQL refreshes do not support source-version pinning.
|
||||
|
||||
``cpu_millis`` (1000 = one core), ``memory_bytes``, and ``gpu_count``
|
||||
cap aggregate resources for this execution, including its Function
|
||||
processes. CPU or memory requires all three budget fields; GPU count
|
||||
may be zero for CPU-only views. ``gpu_class`` selects an operator-defined
|
||||
GPU class for this execution only. Omitted options preserve defaults.
|
||||
These options require an Enterprise backend that enforces isolation;
|
||||
Embedded refreshes reject them. Other servers may reject the new options.
|
||||
|
||||
LanceDB Enterprise results leave ``mode``, ``rows_written``, and
|
||||
``source_version`` as ``None`` because the SQL job adapter does not expose
|
||||
these metrics.
|
||||
"""
|
||||
return await self._table._inner.refresh_materialized_view(
|
||||
source_version=source_version, full=full
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
)
|
||||
|
||||
async def refresh_async(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "AsyncJob[RefreshMaterializedViewResult]":
|
||||
"""Submit a refresh and return its job without waiting.
|
||||
|
||||
@@ -221,7 +286,11 @@ class AsyncMaterializedView:
|
||||
|
||||
return _typed_job(
|
||||
await self._table._inner.refresh_materialized_view_async(
|
||||
source_version=source_version, full=full
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
),
|
||||
RefreshMaterializedViewResult.from_json,
|
||||
)
|
||||
@@ -253,14 +322,36 @@ class MaterializedView:
|
||||
return LOOP.run(self._async.definition())
|
||||
|
||||
def refresh(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "RefreshMaterializedViewResult":
|
||||
"""Recompute the view from its source. See
|
||||
[AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]."""
|
||||
return LOOP.run(self._async.refresh(full=full, source_version=source_version))
|
||||
return LOOP.run(
|
||||
self._async.refresh(
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
def refresh_async(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "Job[RefreshMaterializedViewResult]":
|
||||
"""Submit a refresh and return its job without waiting.
|
||||
|
||||
@@ -269,6 +360,12 @@ class MaterializedView:
|
||||
"""
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._async.refresh_async(full=full, source_version=source_version)
|
||||
self._async.refresh_async(
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object):
|
||||
on_bad_vectors: str = "error",
|
||||
fill_value: float = 0.0,
|
||||
timeout: Optional[timedelta] = None,
|
||||
*,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeInsertResult:
|
||||
"""
|
||||
Executes the merge insert operation
|
||||
@@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object):
|
||||
first attempt will not be cancelled.
|
||||
|
||||
When this is set, the timeout is enforced on all attempts, including
|
||||
the first.
|
||||
the first. For remote tables it is sent as a server execution timeout;
|
||||
it does not extend HTTP read or proxy idle timeouts, or prove that a
|
||||
failed request did not commit.
|
||||
retries: int, optional
|
||||
Override the remote retry budget for this execution only (0 to 255).
|
||||
Use ``execute(new_data, retries=0)`` to disable even retries after
|
||||
precommit conflicts (409) or rate limits (429). This does not change
|
||||
connection-wide/read budgets or local transaction conflict retries.
|
||||
|
||||
By default, remote calls use the connection's
|
||||
[RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set
|
||||
through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within
|
||||
the retry budget; it never permits replay of ambiguous merge outcomes.
|
||||
In particular, 502, ordinary 503, and 504 are never replayed, even if
|
||||
configured. Reconcile table contents before manually repeating a merge
|
||||
whose commit outcome is unknown.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object):
|
||||
"""
|
||||
if timeout is not None:
|
||||
self._timeout = timeout
|
||||
return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
|
||||
return self._table._do_merge(
|
||||
self, new_data, on_bad_vectors, fill_value, retries=retries
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ through a namespace abstraction.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
from typing import Any, Dict, Iterable, List, Optional, Union
|
||||
@@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import (
|
||||
QueryTableRequestVector,
|
||||
)
|
||||
from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery
|
||||
from lance_namespace_urllib3_client.models.structured_fts_query import (
|
||||
StructuredFtsQuery,
|
||||
)
|
||||
from lance_namespace.errors import (
|
||||
NamespaceNotEmptyError,
|
||||
NamespaceNotFoundError,
|
||||
@@ -78,6 +82,7 @@ from lancedb.materialized_view import (
|
||||
SelectArg,
|
||||
)
|
||||
from lancedb.table import AsyncTable, LanceTable, Table
|
||||
from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery
|
||||
from lancedb.util import validate_table_name
|
||||
from lancedb.common import DATA
|
||||
from lancedb.pydantic import LanceModel
|
||||
@@ -178,6 +183,26 @@ def _query_to_namespace_request(
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
string_query=StringFtsQuery(query=fts_query)
|
||||
)
|
||||
elif getattr(fts_query, "operator", None) is not None:
|
||||
columns = fts_query.columns or []
|
||||
text = fts_query.query
|
||||
if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
|
||||
if len(columns) > 1:
|
||||
raise ValueError(
|
||||
"Phrase queries cannot be used with multiple columns."
|
||||
)
|
||||
structured = PhraseQuery(text[1:-1], columns[0] if columns else None)
|
||||
elif len(columns) > 1:
|
||||
structured = MultiMatchQuery(text, columns, operator=fts_query.operator)
|
||||
else:
|
||||
structured = MatchQuery(
|
||||
text, columns[0] if columns else None, operator=fts_query.operator
|
||||
)
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
structured_query=StructuredFtsQuery.from_dict(
|
||||
{"query": json.loads(structured.to_json())}
|
||||
)
|
||||
)
|
||||
elif hasattr(fts_query, "query"):
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
string_query=StringFtsQuery(
|
||||
@@ -484,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
Supported values:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally.
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -559,7 +586,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
"storage_options": self.storage_options or None,
|
||||
"read_consistency_interval_seconds": (
|
||||
self.read_consistency_interval.total_seconds()
|
||||
if self.read_consistency_interval
|
||||
if self.read_consistency_interval is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
@@ -579,12 +606,15 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
If limit is None, return all table names; zero returns an empty list.
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`list_tables` instead, which provides proper pagination support.
|
||||
Iterate over :meth:`list_tables` to get all names, or use
|
||||
:meth:`table_exists` to check for a particular table. The listing's
|
||||
``tables`` attribute contains only one page.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"table_names() is deprecated, use list_tables() instead",
|
||||
"table_names() is deprecated, iterate list_tables() for all names "
|
||||
"or use table_exists([name]) to check existence",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -612,6 +642,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
@@ -633,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
embedding_functions=embedding_functions,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -640,6 +674,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self,
|
||||
name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
namespace_client=self._namespace_client,
|
||||
pushdown_operations=self._namespace_client_pushdown_operations,
|
||||
route_pushdown_to_rust=self._route_pushdown_to_rust,
|
||||
@@ -678,6 +713,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self,
|
||||
name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
namespace_client=self._namespace_client,
|
||||
pushdown_operations=self._namespace_client_pushdown_operations,
|
||||
route_pushdown_to_rust=self._route_pushdown_to_rust,
|
||||
@@ -693,14 +729,16 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> "MaterializedView":
|
||||
"""Define a materialized view over a table in the root namespace.
|
||||
See
|
||||
@@ -712,12 +750,14 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self._inner.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
).name
|
||||
)
|
||||
@@ -727,25 +767,29 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> Job[None]:
|
||||
job = LOOP.run(
|
||||
self._inner.create_materialized_view_async(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -1015,6 +1059,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
bool
|
||||
True if the table exists, False otherwise.
|
||||
"""
|
||||
if self._route_pushdown_to_rust:
|
||||
return LOOP.run(self._inner.table_exists(table_id))
|
||||
request = TableExistsRequest(id=table_id)
|
||||
try:
|
||||
self._namespace_client.table_exists(request)
|
||||
@@ -1030,7 +1076,11 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
limit: Optional[int] = None,
|
||||
) -> TableListing:
|
||||
"""
|
||||
List all tables in this database with pagination support.
|
||||
Iterate over all tables in this database, fetching pages as needed.
|
||||
|
||||
The ``tables`` attribute contains only the current page (100 names by
|
||||
default). Iterate over the listing to visit all pages, or use
|
||||
``table_exists([name])`` to check for a particular table.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -1090,6 +1140,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self,
|
||||
name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
location=table_uri,
|
||||
namespace_client=namespace_client,
|
||||
managed_versioning=managed_versioning,
|
||||
@@ -1163,7 +1214,9 @@ class AsyncLanceNamespaceDBConnection:
|
||||
Supported values:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally.
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1227,12 +1280,15 @@ class AsyncLanceNamespaceDBConnection:
|
||||
If limit is None, return all table names; zero returns an empty list.
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`list_tables` instead, which provides proper pagination support.
|
||||
Iterate over :meth:`list_tables` to get all names, or use
|
||||
:meth:`table_exists` to check for a particular table. The listing's
|
||||
``tables`` attribute contains only one page.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"table_names() is deprecated, use list_tables() instead",
|
||||
"table_names() is deprecated, iterate list_tables() for all names "
|
||||
"or use table_exists([name]) to check existence",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -1257,6 +1313,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Create a new table in the namespace."""
|
||||
if namespace_path is None:
|
||||
@@ -1278,6 +1336,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
namespace_path=namespace_path,
|
||||
embedding_functions=embedding_functions,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
return table._set_namespace_context(
|
||||
namespace_path=namespace_path,
|
||||
@@ -1327,25 +1387,29 @@ class AsyncLanceNamespaceDBConnection:
|
||||
async def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> "AsyncMaterializedView":
|
||||
"""Define a materialized view over a table in the root namespace."""
|
||||
view = await self._inner.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
# Reopen through the namespace so the view's table carries the
|
||||
# namespace client and pushdown configuration a bare inner table lacks.
|
||||
@@ -1354,25 +1418,29 @@ class AsyncLanceNamespaceDBConnection:
|
||||
async def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> AsyncJob[None]:
|
||||
"""Submit materialized-view creation and return its job."""
|
||||
return await self._inner.create_materialized_view_async(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
|
||||
async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
|
||||
@@ -1614,6 +1682,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
bool
|
||||
True if the table exists, False otherwise.
|
||||
"""
|
||||
if self._route_pushdown_to_rust:
|
||||
return await self._inner.table_exists(table_id)
|
||||
request = TableExistsRequest(id=table_id)
|
||||
try:
|
||||
self._namespace_client.table_exists(request)
|
||||
@@ -1628,7 +1698,11 @@ class AsyncLanceNamespaceDBConnection:
|
||||
limit: Optional[int] = None,
|
||||
) -> AsyncTableListing:
|
||||
"""
|
||||
List all tables in this database with pagination support.
|
||||
Iterate over all tables in this database, fetching pages as needed.
|
||||
|
||||
The ``tables`` attribute contains only the current page (100 names by
|
||||
default). Iterate over the listing to visit all pages, or use
|
||||
``table_exists([name])`` to check for a particular table.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -1749,7 +1823,9 @@ def connect_namespace(
|
||||
Supported values:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally.
|
||||
namespace.query_table() instead of locally. Queries with a nonempty
|
||||
``order_by`` or an explicit ``scan_in_order(True)`` execute on the
|
||||
client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -1840,7 +1916,9 @@ def connect_namespace_async(
|
||||
Supported values:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally.
|
||||
namespace.query_table() instead of locally. Queries with a nonempty
|
||||
``order_by`` or an explicit ``scan_in_order(True)`` execute on the
|
||||
client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
|
||||
@@ -11,7 +11,12 @@ import pyarrow as pa
|
||||
from ._lancedb import async_permutation_builder, PermutationReader
|
||||
from .table import LanceTable, Table
|
||||
from .background_loop import LOOP
|
||||
from .util import batch_to_tensor, batch_to_tensor_dict, batch_to_tensor_rows
|
||||
from .util import (
|
||||
batch_to_tensor,
|
||||
batch_to_tensor_columns,
|
||||
batch_to_tensor_dict,
|
||||
batch_to_tensor_rows,
|
||||
)
|
||||
from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -410,6 +415,8 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]:
|
||||
from .remote.table import RemoteTable
|
||||
|
||||
if isinstance(table, RemoteTable):
|
||||
# RemoteTable already owns its reopen state; keep the table object so
|
||||
# pickle delegates to its __getstate__ without duplicating the fields.
|
||||
return {
|
||||
"kind": "remote",
|
||||
"table": table,
|
||||
@@ -418,20 +425,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]:
|
||||
if not isinstance(table, LanceTable):
|
||||
raise ValueError(f"Cannot pickle table of type {type(table)!r}")
|
||||
|
||||
base_uri = table._conn.uri
|
||||
if base_uri.startswith("memory://"):
|
||||
state = table.__getstate__()
|
||||
if state.get("kind") == "memory":
|
||||
return {
|
||||
"kind": "memory",
|
||||
"name": table.name,
|
||||
"data": table.to_arrow(),
|
||||
"state": state,
|
||||
}
|
||||
|
||||
return {
|
||||
"kind": "local",
|
||||
"name": table.name,
|
||||
"uri": base_uri,
|
||||
"namespace": table._namespace_path,
|
||||
"storage_options": table._conn.storage_options,
|
||||
"kind": "lance",
|
||||
"state": state,
|
||||
}
|
||||
|
||||
|
||||
@@ -444,13 +446,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table:
|
||||
return permutation_data.replace_schema_metadata(metadata)
|
||||
|
||||
|
||||
def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable:
|
||||
table = LanceTable.__new__(LanceTable)
|
||||
table.__setstate__(state)
|
||||
return table
|
||||
|
||||
|
||||
def _table_from_pickle_state(state: dict[str, Any]) -> Table:
|
||||
from . import connect
|
||||
|
||||
kind = state["kind"]
|
||||
if kind == "remote":
|
||||
return state["table"]
|
||||
if kind == "lance":
|
||||
return _lance_table_from_pickle_state(state["state"])
|
||||
if kind == "memory":
|
||||
if "state" in state:
|
||||
return _lance_table_from_pickle_state(state["state"])
|
||||
# Backward compatibility for pickles written before tables carried
|
||||
# their own state.
|
||||
return connect("memory://").create_table(state["name"], state["data"])
|
||||
if kind == "local":
|
||||
db = connect(state["uri"], storage_options=state["storage_options"])
|
||||
@@ -779,6 +793,20 @@ class Permutation:
|
||||
self.reader = None
|
||||
self._pid = None
|
||||
|
||||
def __copy__(self) -> "Permutation":
|
||||
"""Return a shallow copy without going through the pickle path.
|
||||
|
||||
The ``with_*`` builders use ``copy.copy`` to derive a new permutation.
|
||||
The default copy protocol would use ``__getstate__``/``__setstate__``,
|
||||
which materializes the permutation table with ``to_arrow()`` (not
|
||||
supported for remote tables) and rebuilds the base table and reader.
|
||||
A shallow copy instead keeps the existing table handles and reader;
|
||||
the caller replaces only the attribute it is changing.
|
||||
"""
|
||||
new = self.__class__.__new__(self.__class__)
|
||||
new.__dict__ = self.__dict__.copy()
|
||||
return new
|
||||
|
||||
def _ensure_open(self) -> None:
|
||||
pid = os.getpid()
|
||||
if self.reader is not None and getattr(self, "_pid", None) == pid:
|
||||
@@ -1008,6 +1036,7 @@ class Permutation:
|
||||
"pandas",
|
||||
"arrow",
|
||||
"torch",
|
||||
"torch_dict",
|
||||
"torch_row",
|
||||
"torch_col",
|
||||
"polars",
|
||||
@@ -1019,28 +1048,54 @@ class Permutation:
|
||||
If this method is not called, the "python" format will be used.
|
||||
|
||||
The format can be one of:
|
||||
- "numpy" - the batch will be a dict of numpy arrays (one per column)
|
||||
- "numpy" - a single NumPy ndarray built with
|
||||
``batch.to_pandas().to_numpy()``. This conversion may copy data and
|
||||
may promote mixed numeric columns to a common numeric dtype, for
|
||||
example int64 and float32 to float64. Nested or incompatible columns
|
||||
produce an object array.
|
||||
- "python" - the batch will be a list of dicts (one per row)
|
||||
- "python_col" - the batch will be a dict of lists (one entry per column)
|
||||
- "pandas" - the batch will be a pandas DataFrame
|
||||
- "arrow" - the batch will be a pyarrow RecordBatch
|
||||
- "torch" - the batch will be a list of per-row dicts mapping column
|
||||
name to a 0-D torch tensor. Works with the default
|
||||
``torch.utils.data.DataLoader`` collate, which stacks the per-row
|
||||
dicts back into a dict of batched tensors.
|
||||
- "torch_row" - the batch will be a list of tensors, one per row
|
||||
- "torch_col" - the batch will be a 2D torch tensor (first dim indexes columns)
|
||||
- "torch" - a list of per-row dicts mapping column names to tensors with
|
||||
shape ``(*S)``. The default DataLoader collate stacks these into a
|
||||
dict of ``(B, *S)`` tensors.
|
||||
- "torch_dict" - a dict mapping each column name to one tensor with
|
||||
shape ``(B, *S)``. Columns may have different sample shapes ``S``.
|
||||
Use an identity collate to consume the batch directly. Tensors share
|
||||
Arrow storage where the layout allows.
|
||||
- "torch_row" - a list of per-row tensors with shape ``(C, *S)``. All
|
||||
columns must have the same sample shape ``S``. A single scalar column
|
||||
produces ``(1,)`` tensors. Numeric dtypes are combined with
|
||||
``torch.promote_types``.
|
||||
- "torch_col" - one tensor with shape ``(C, B, *S)``. All columns must
|
||||
have the same sample shape ``S``. For one column this is an
|
||||
``unsqueeze(0)`` view of the column tensor.
|
||||
- "polars" - the batch will be a polars DataFrame
|
||||
|
||||
Conversion may or may not involve a data copy. Lance uses Arrow internally
|
||||
and so it is able to zero-copy to the arrow and polars formats.
|
||||
For torch formats, ``S`` is the shape of one sample. Scalar columns have
|
||||
``S = ()``. A fixed-size-list column of width ``D`` contributes a
|
||||
dimension ``D``, and nested fixed-size lists contribute one dimension
|
||||
per level. Fixed-shape tensors use their logical shape, including any
|
||||
axis permutation. "torch_dict", "torch", and "torch_col" reject nulls;
|
||||
use the "python" or "arrow" format for nullable columns. "torch_row"
|
||||
preserves the previous NaN behavior for nullable scalar integer and
|
||||
floating columns, but rejects nulls in nested fixed-size-list and tensor
|
||||
columns.
|
||||
|
||||
Conversion to torch and torch_col will be zero-copy but will only support a
|
||||
subset of data types (numeric types).
|
||||
``lance.bfloat16`` values become ``torch.bfloat16`` tensors when the
|
||||
leaf field is ``fixed_size_binary[2]`` and carries the
|
||||
``ARROW:extension:name`` metadata value ``lance.bfloat16``. Unmarked
|
||||
binary columns are rejected.
|
||||
|
||||
Conversion to numpy and/or pandas will typically be zero-copy for numeric
|
||||
types. Conversion of strings, lists, and structs will require creating python
|
||||
objects and this is not zero-copy.
|
||||
Conversion may or may not involve a data copy. Lance uses Arrow
|
||||
internally and can zero-copy to the arrow and polars formats.
|
||||
"torch_dict", "torch", and a single-column "torch_col" produce
|
||||
numeric and fixed-size-list tensors without copying where the Arrow
|
||||
layout allows. Multi-column "torch_col" and "torch_row" stack columns
|
||||
and therefore copy. Conversion to numpy and/or pandas can copy even
|
||||
homogeneous numeric columns. Conversion of strings, lists, and structs
|
||||
will require creating Python objects and this is not zero-copy.
|
||||
|
||||
For custom formatting, use
|
||||
[with_transform][lancedb.permutation.Permutation.with_transform] which
|
||||
@@ -1059,6 +1114,8 @@ class Permutation:
|
||||
return self.with_transform(Transforms.arrow2arrow)
|
||||
elif format == "torch":
|
||||
return self.with_transform(batch_to_tensor_dict)
|
||||
elif format == "torch_dict":
|
||||
return self.with_transform(batch_to_tensor_columns)
|
||||
elif format == "torch_row":
|
||||
return self.with_transform(batch_to_tensor_rows)
|
||||
elif format == "torch_col":
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Typed metadata previews and results of data-cache prewarm jobs."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrewarmDataResult:
|
||||
"""Reported executor work for a pinned snapshot, not guaranteed cache residency.
|
||||
|
||||
Counts omitted by older workers remain None. I/O counts are unknown when
|
||||
executors do not report them. Partial completions are a subset of completed
|
||||
executors and may reflect cache pressure.
|
||||
"""
|
||||
|
||||
table_version: int
|
||||
executors_targeted: Optional[int] = None
|
||||
executors_completed: Optional[int] = None
|
||||
executors_partial: Optional[int] = None
|
||||
fragments_selected: Optional[int] = None
|
||||
ranges_completed: Optional[int] = None
|
||||
bytes_read: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "PrewarmDataResult":
|
||||
value = json.loads(raw)
|
||||
names = {field.name for field in fields(cls)}
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrewarmPruningSummary:
|
||||
"""Conservative metadata pruning; selected ranges are not exact row matches.
|
||||
|
||||
``mode`` is a server-reported string, including future pruning modes.
|
||||
Unknown interval counts and fallback reasons remain None.
|
||||
"""
|
||||
|
||||
mode: str
|
||||
input_fragments: int
|
||||
selected_fragments: int
|
||||
pruned_fragments: int
|
||||
selected_row_ranges: Optional[int] = None
|
||||
fallback_reason: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrewarmDataPlan:
|
||||
"""Metadata-only preview for a snapshot, without a warming job.
|
||||
|
||||
A later submission chooses its own snapshot and can produce a different
|
||||
plan. ``plan`` is readable display text; use ``pruning`` for structured facts.
|
||||
"""
|
||||
|
||||
table_version: int
|
||||
plan: str
|
||||
pruning: PrewarmPruningSummary
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "PrewarmDataPlan":
|
||||
# The native SDK validates the wire format before returning this value.
|
||||
value = json.loads(raw)
|
||||
summary = value["pruning"]
|
||||
names = {field.name for field in fields(PrewarmPruningSummary)}
|
||||
return cls(
|
||||
table_version=value["table_version"],
|
||||
plan=value["plan"],
|
||||
pruning=PrewarmPruningSummary(
|
||||
**{key: item for key, item in summary.items() if key in names}
|
||||
),
|
||||
)
|
||||
+1203
-191
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from lancedb.server_info import ServerInfo
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import timedelta
|
||||
import json
|
||||
@@ -37,8 +39,8 @@ import pyarrow as pa
|
||||
|
||||
from ..common import DATA
|
||||
from lancedb.listing import Listing, NamespaceListing, TableListing
|
||||
from ..db import DBConnection, LOOP
|
||||
from ..functions import FunctionVersion, UdfDefinition
|
||||
from ..db import DBConnection, LOOP, _normalize_function_version
|
||||
from ..functions import FunctionVersion, FunctionDefinition
|
||||
from ..graph import EdgeTable, NodeTable, PropertyGraph
|
||||
from ..job import AsyncJob, Job
|
||||
from ..sql import Query as SqlQuery
|
||||
@@ -214,6 +216,7 @@ class RemoteDBConnection(DBConnection):
|
||||
client_config,
|
||||
oauth_config,
|
||||
sql_host_override,
|
||||
storage_options,
|
||||
):
|
||||
config = (
|
||||
ClientConfig(**client_config)
|
||||
@@ -233,7 +236,7 @@ class RemoteDBConnection(DBConnection):
|
||||
result.region = "us-east-1"
|
||||
result.host_override = endpoint
|
||||
result.sql_host_override = sql_host_override
|
||||
result.storage_options = None
|
||||
result.storage_options = storage_options
|
||||
result.client_config = replace(config, extra_headers=headers)
|
||||
result._catalog_oauth = oauth_config is not None
|
||||
result._conn = inner
|
||||
@@ -430,7 +433,11 @@ class RemoteDBConnection(DBConnection):
|
||||
page_token: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> TableListing:
|
||||
"""List a page of tables in this database.
|
||||
"""Iterate over all tables in this database, fetching pages as needed.
|
||||
|
||||
The ``tables`` attribute contains only the current page (100 names by
|
||||
default). Iterate over the listing to visit all pages, or use
|
||||
``table_exists([name])`` to check for a particular table.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -468,7 +475,9 @@ class RemoteDBConnection(DBConnection):
|
||||
"""List the names of all tables in the database.
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`list_tables` instead, which provides proper pagination support.
|
||||
Iterate over :meth:`list_tables` to get all names, or use
|
||||
:meth:`table_exists` to check for a particular table. The listing's
|
||||
``tables`` attribute contains only one page.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -488,7 +497,8 @@ class RemoteDBConnection(DBConnection):
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"table_names() is deprecated, use list_tables() instead",
|
||||
"table_names() is deprecated, iterate list_tables() for all names "
|
||||
"or use table_exists([name]) to check existence",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -566,6 +576,7 @@ class RemoteDBConnection(DBConnection):
|
||||
source_version: Optional[int] = None,
|
||||
source_tag: Optional[str] = None,
|
||||
is_shallow: bool = True,
|
||||
exist_ok: bool = False,
|
||||
) -> Table:
|
||||
"""Clone a table from a source table.
|
||||
|
||||
@@ -585,6 +596,8 @@ class RemoteDBConnection(DBConnection):
|
||||
is_shallow: bool, default True
|
||||
Whether to perform a shallow clone (True) or deep clone (False).
|
||||
Currently only shallow clone is supported.
|
||||
exist_ok: bool, default False
|
||||
Return the existing target unchanged instead of cloning over it.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -602,6 +615,7 @@ class RemoteDBConnection(DBConnection):
|
||||
source_version=source_version,
|
||||
source_tag=source_tag,
|
||||
is_shallow=is_shallow,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
)
|
||||
return RemoteTable(
|
||||
@@ -627,6 +641,8 @@ class RemoteDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
"""Create a [Table][lancedb.table.Table] in the database.
|
||||
|
||||
@@ -672,6 +688,10 @@ class RemoteDBConnection(DBConnection):
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
enable_v2_manifest_paths: bool, optional
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
initial_bases: list, optional
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -747,6 +767,16 @@ class RemoteDBConnection(DBConnection):
|
||||
f"{option} is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if initial_bases:
|
||||
raise NotImplementedError(
|
||||
"initial_bases is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if allow_external_blob_outside_bases:
|
||||
raise NotImplementedError(
|
||||
"allow_external_blob_outside_bases is not supported for table "
|
||||
"creation in LanceDB Enterprise"
|
||||
)
|
||||
if exist_ok:
|
||||
if mode == "create":
|
||||
mode = "exist_ok"
|
||||
@@ -782,12 +812,14 @@ class RemoteDBConnection(DBConnection):
|
||||
def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: SelectArg = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
) -> MaterializedView:
|
||||
@@ -797,10 +829,12 @@ class RemoteDBConnection(DBConnection):
|
||||
self._conn.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
)
|
||||
@@ -818,12 +852,14 @@ class RemoteDBConnection(DBConnection):
|
||||
def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: SelectArg = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
) -> Job[None]:
|
||||
@@ -831,10 +867,12 @@ class RemoteDBConnection(DBConnection):
|
||||
self._conn.create_materialized_view_async(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
)
|
||||
@@ -958,6 +996,13 @@ class RemoteDBConnection(DBConnection):
|
||||
"""
|
||||
return Job(LOOP.run(self._conn.open_job(job_id)))
|
||||
|
||||
@override
|
||||
def server_info(self) -> ServerInfo:
|
||||
"""Read the responding server's build information. See
|
||||
[DBConnection.server_info][lancedb.db.DBConnection.server_info].
|
||||
"""
|
||||
return LOOP.run(self._conn.server_info())
|
||||
|
||||
@override
|
||||
def list_gpu_classes(self) -> List[GpuClass]:
|
||||
"""List configured Function GPU classes. See
|
||||
@@ -968,14 +1013,20 @@ class RemoteDBConnection(DBConnection):
|
||||
@override
|
||||
def create_function_async(
|
||||
self,
|
||||
definition: UdfDefinition,
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
) -> Job[FunctionVersion]:
|
||||
job = LOOP.run(
|
||||
self._conn.create_function_async(
|
||||
definition, secrets=secrets, namespace_path=namespace_path
|
||||
definition,
|
||||
secrets=secrets,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -985,9 +1036,10 @@ class RemoteDBConnection(DBConnection):
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
version: str,
|
||||
version: Optional[Union[int, str]] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> FunctionVersion:
|
||||
version = _normalize_function_version(version)
|
||||
return LOOP.run(
|
||||
self._conn.get_function(
|
||||
name, version=version, namespace_path=namespace_path
|
||||
@@ -1024,11 +1076,14 @@ class RemoteDBConnection(DBConnection):
|
||||
version: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> bool:
|
||||
return LOOP.run(
|
||||
self._conn.drop_function(
|
||||
dropped, drop_warnings = LOOP.run(
|
||||
self._conn._drop_function_with_warnings(
|
||||
name, version=version, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
for warning in drop_warnings:
|
||||
warnings.warn(warning, UserWarning, stacklevel=2)
|
||||
return dropped
|
||||
|
||||
@override
|
||||
def drop_function_async(
|
||||
@@ -1062,6 +1117,7 @@ class RemoteDBConnection(DBConnection):
|
||||
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> StorageIntegrationInfo:
|
||||
return LOOP.run(
|
||||
@@ -1079,6 +1135,7 @@ class RemoteDBConnection(DBConnection):
|
||||
azure_client_secret_secret=azure_client_secret_secret,
|
||||
gcp_credentials_json_secret=gcp_credentials_json_secret,
|
||||
huggingface_token_secret=huggingface_token_secret,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
)
|
||||
)
|
||||
@@ -1117,9 +1174,18 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def create_secret(
|
||||
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
value: str,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> None:
|
||||
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
|
||||
LOOP.run(
|
||||
self._conn.create_secret(
|
||||
name, value, exist_ok=exist_ok, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def alter_secret(
|
||||
@@ -1163,10 +1229,17 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def create_view(
|
||||
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
query: str,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> ViewDescription:
|
||||
return LOOP.run(
|
||||
self._conn.create_view(name, query, namespace_path=namespace_path)
|
||||
self._conn.create_view(
|
||||
name, query, exist_ok=exist_ok, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
@@ -1267,16 +1340,52 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> Listing[JobInfo]:
|
||||
"""List server-side jobs across the database's tables.
|
||||
"""List server-side jobs, optionally filtered before pagination.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
|
||||
``page_token`` resumes from a saved token. Requests and errors occur during
|
||||
iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
``table`` names a table in ``namespace_path`` (the root by default).
|
||||
Listings include all branches of the table. A namespace filter requires
|
||||
``table``.
|
||||
``state`` uses registry states such as ``in_progress``, ``succeeded``,
|
||||
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
|
||||
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
|
||||
Creation-time bounds are Unix milliseconds, inclusive at
|
||||
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
|
||||
Resume a ``page_token`` with the same filters. Requests and errors occur
|
||||
during iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
|
||||
For example, to inspect up to five jobs without fetching all history::
|
||||
|
||||
jobs = db.list_jobs(table="events", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
"""
|
||||
return Listing(
|
||||
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
|
||||
self._conn.list_jobs(
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
table=table,
|
||||
namespace_path=namespace_path,
|
||||
state=state,
|
||||
job_type=job_type,
|
||||
job_types=job_types,
|
||||
created_at_gte_millis=created_at_gte_millis,
|
||||
created_at_lt_millis=created_at_lt_millis,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
|
||||
@@ -149,6 +149,8 @@ def _http_error_class(
|
||||
return input_class
|
||||
if error_code == "already_exists":
|
||||
return AlreadyExistsError
|
||||
if status_code == 409:
|
||||
return ConflictError
|
||||
if error_code != "not_found" or resource_kind is None:
|
||||
return None
|
||||
return {
|
||||
@@ -268,6 +270,80 @@ class AlreadyExistsError(HttpError):
|
||||
"""A remote resource already exists."""
|
||||
|
||||
|
||||
class ConflictError(HttpError):
|
||||
"""A remote operation conflicts with the current state of a resource.
|
||||
|
||||
For example, deleting a branch whose files are still needed by another
|
||||
branch raises this error. The server's reason is included in the message.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> error = HttpError("main depends on the branch's files", "req-1", 409)
|
||||
>>> isinstance(error, ConflictError)
|
||||
True
|
||||
>>> error.status_code
|
||||
409
|
||||
"""
|
||||
|
||||
|
||||
class ResponseInterruptedError(HttpError):
|
||||
"""A streamed query response stopped before the server finished sending it.
|
||||
|
||||
The batches already returned are valid, but the result is incomplete. The
|
||||
query is not retried automatically, because a new attempt would return those
|
||||
rows a second time. To read the same data in a new attempt, check out
|
||||
``table_version`` first.
|
||||
|
||||
Attributes
|
||||
----------
|
||||
batches: int
|
||||
The number of batches returned before the interruption.
|
||||
rows: int
|
||||
The number of rows in those batches.
|
||||
table_version: int or None
|
||||
The table version the response reflected, if the server reported it.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7)
|
||||
>>> isinstance(error, HttpError)
|
||||
True
|
||||
>>> (error.rows, error.table_version)
|
||||
(2048, 7)
|
||||
"""
|
||||
|
||||
# HttpError.__new__ takes HttpError's arguments, to choose a subclass.
|
||||
def __new__(cls, *args, **kwargs):
|
||||
return RuntimeError.__new__(cls)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
request_id: str,
|
||||
batches: int,
|
||||
rows: int,
|
||||
table_version: Optional[int] = None,
|
||||
is_transport_error: bool = False,
|
||||
):
|
||||
super().__init__(message, request_id, is_transport_error=is_transport_error)
|
||||
self.batches = batches
|
||||
self.rows = rows
|
||||
self.table_version = table_version
|
||||
|
||||
def __reduce__(self) -> tuple[type, tuple]:
|
||||
return (
|
||||
self.__class__,
|
||||
(
|
||||
str(self),
|
||||
self.request_id,
|
||||
self.batches,
|
||||
self.rows,
|
||||
self.table_version,
|
||||
self.is_transport_error,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError):
|
||||
"""A remote table was not found.
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ from typing import (
|
||||
import warnings
|
||||
|
||||
from lancedb import __version__
|
||||
from lancedb.sql import QueryParameters
|
||||
from lancedb._blob import BlobFile
|
||||
|
||||
from lancedb._lancedb import (
|
||||
@@ -34,6 +35,7 @@ from lancedb._lancedb import (
|
||||
DeleteResult,
|
||||
DropColumnsResult,
|
||||
FtsToken,
|
||||
FunctionColumnStatus,
|
||||
IndexConfig,
|
||||
RTEWriteSpec,
|
||||
MergeResult,
|
||||
@@ -47,8 +49,14 @@ from lancedb.index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import FunctionApplication, RefreshColumnResult
|
||||
from lancedb.functions import (
|
||||
FunctionProvenance,
|
||||
FunctionApplication,
|
||||
FunctionRetryPolicy,
|
||||
RefreshColumnResult,
|
||||
)
|
||||
from lancedb.remote.db import LOOP
|
||||
from lancedb.table import IndexConfigType, _maybe_add_fts_error_note
|
||||
import pyarrow as pa
|
||||
@@ -60,6 +68,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry
|
||||
from lancedb.table import _normalize_progress
|
||||
|
||||
from ..query import (
|
||||
FullTextOperator,
|
||||
AnalyzePlanDistributedMetrics,
|
||||
DocumentGranularity,
|
||||
FullTextQuery,
|
||||
@@ -71,6 +80,7 @@ from ..table import (
|
||||
BlobMode,
|
||||
Branches,
|
||||
CompactionOptions,
|
||||
CompactionResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
Table,
|
||||
@@ -374,6 +384,7 @@ class RemoteTable(Table):
|
||||
index_type: ScalarIndexType = "BTREE",
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
):
|
||||
"""Create a scalar index on a column.
|
||||
|
||||
@@ -400,6 +411,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -438,6 +450,7 @@ class RemoteTable(Table):
|
||||
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
):
|
||||
"""Create a full-text search index on a column.
|
||||
|
||||
@@ -497,6 +510,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
field_names,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
name=name,
|
||||
wait_timeout=wait_timeout,
|
||||
@@ -521,6 +535,7 @@ class RemoteTable(Table):
|
||||
replace: bool = ...,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
) -> None: ...
|
||||
|
||||
@@ -546,6 +561,7 @@ class RemoteTable(Table):
|
||||
*,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
target_partition_size: Optional[int] = ...,
|
||||
) -> None: ...
|
||||
@@ -577,6 +593,7 @@ class RemoteTable(Table):
|
||||
config: Optional[IndexConfigType] = None,
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
train: bool = True,
|
||||
target_partition_size: Optional[int] = None,
|
||||
):
|
||||
@@ -597,7 +614,7 @@ class RemoteTable(Table):
|
||||
config : IndexConfigType, optional
|
||||
The index configuration object. If provided, uses the new unified API.
|
||||
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
|
||||
BTree, Bitmap, LabelList, Fm, FTS.
|
||||
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS.
|
||||
replace : bool, default True
|
||||
Whether to replace an existing index on this column.
|
||||
wait_timeout : timedelta, optional
|
||||
@@ -680,6 +697,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -695,6 +713,7 @@ class RemoteTable(Table):
|
||||
replace: Optional[bool] = None,
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
train: bool = True,
|
||||
) -> Job:
|
||||
"""Create an index, returning a handle to the indexing job.
|
||||
@@ -707,6 +726,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index_async(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -724,6 +744,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].
|
||||
|
||||
@@ -758,6 +779,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
|
||||
-------
|
||||
@@ -775,6 +799,7 @@ class RemoteTable(Table):
|
||||
progress=progress,
|
||||
write_parallelism=write_parallelism,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
retries=retries,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -789,6 +814,8 @@ class RemoteTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceQueryBuilder:
|
||||
"""Create a search query to find the nearest neighbors
|
||||
of the given query vector. We currently support
|
||||
@@ -847,6 +874,10 @@ class RemoteTable(Table):
|
||||
|
||||
- *default None*, which leaves fast search disabled.
|
||||
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string full-text query; the default is OR.
|
||||
Use ``query_type="fts"`` when the table also has embeddings.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceQueryBuilder
|
||||
@@ -883,6 +914,7 @@ class RemoteTable(Table):
|
||||
ordering_field_name=ordering_field_name,
|
||||
fts_columns=fts_columns or [],
|
||||
fast_search=fast_search,
|
||||
operator=operator,
|
||||
)
|
||||
|
||||
def _execute_query(
|
||||
@@ -905,6 +937,14 @@ class RemoteTable(Table):
|
||||
|
||||
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
|
||||
|
||||
def _execute_arrow(
|
||||
self,
|
||||
query: Query,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
return LOOP.run(self._table._execute_arrow(query, timeout=timeout))
|
||||
|
||||
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
|
||||
return LOOP.run(self._table._explain_plan(query, verbose))
|
||||
|
||||
@@ -935,9 +975,10 @@ class RemoteTable(Table):
|
||||
new_data: DATA,
|
||||
on_bad_vectors: str,
|
||||
fill_value: float,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult:
|
||||
return LOOP.run(
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
|
||||
)
|
||||
|
||||
@_deprecated_keyword("predicate", "where")
|
||||
@@ -1085,6 +1126,13 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_async(
|
||||
self, *, compaction_options: Optional[CompactionOptions] = None
|
||||
) -> Job[CompactionResult]:
|
||||
return Job(
|
||||
LOOP.run(self._table.compact_async(compaction_options=compaction_options))
|
||||
)
|
||||
|
||||
def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -1097,10 +1145,13 @@ class RemoteTable(Table):
|
||||
Enterprise job. Pruning old versions and index optimization are not
|
||||
yet supported remotely, so this call skips them and returns
|
||||
successfully with zeroed pruning statistics once the compaction job
|
||||
has been submitted; it does not wait for that job to finish. Passing
|
||||
a non-default ``compaction_options`` raises ``NotImplementedError``
|
||||
before anything is submitted, since there is no way yet to forward
|
||||
those settings to the server.
|
||||
has been submitted; it does not wait for that job to finish. The
|
||||
per-job options ``target_rows_per_fragment``, ``max_source_rows``,
|
||||
``io_buffer_size``, and ``batch_size`` are supported on compatible
|
||||
servers. Omitted fields inherit table tuning, then deployment/built-in
|
||||
defaults. Other non-default settings raise ``NotImplementedError``
|
||||
before submission. Errors from older servers are propagated without
|
||||
retrying with the settings removed.
|
||||
"""
|
||||
return LOOP.run(
|
||||
self._table.optimize(
|
||||
@@ -1130,6 +1181,7 @@ class RemoteTable(Table):
|
||||
computed: Dict[str, str] | None = None,
|
||||
auto_refresh_enabled: bool | None = None,
|
||||
auto_refresh_interval_seconds: int | None = None,
|
||||
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
|
||||
) -> AddColumnsResult:
|
||||
return LOOP.run(
|
||||
self._table.add_columns(
|
||||
@@ -1137,6 +1189,7 @@ class RemoteTable(Table):
|
||||
computed=computed,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
auto_refresh_resource_budget=auto_refresh_resource_budget,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1144,16 +1197,56 @@ class RemoteTable(Table):
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[Dict[str, int]] = None,
|
||||
supervisor_resources: Optional[Dict[str, int]] = None,
|
||||
planning_workers: Optional[Dict[str, Any]] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
error_policy: Optional[Literal["fail", "skip"]] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
retry_errors: bool = False,
|
||||
retry_job_id: Optional[str] = None,
|
||||
retry_error_type: Optional[str] = None,
|
||||
include_quarantined: bool = False,
|
||||
function_version: Optional[str] = None,
|
||||
recompute: Optional[Literal["failed", "all", "none"]] = None,
|
||||
):
|
||||
return LOOP.run(
|
||||
self._table.refresh_column(
|
||||
column,
|
||||
where=where,
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
publication_interval_rows=publication_interval_rows,
|
||||
resource_budget=resource_budget,
|
||||
supervisor_resources=supervisor_resources,
|
||||
planning_workers=planning_workers,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
retry_policy=retry_policy,
|
||||
error_policy=error_policy,
|
||||
max_failed_fraction=max_failed_fraction,
|
||||
max_failed_rows=max_failed_rows,
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
init_timeout_seconds=init_timeout_seconds,
|
||||
num_workers=num_workers,
|
||||
max_executor_processes_per_worker=max_executor_processes_per_worker,
|
||||
retry_errors=retry_errors,
|
||||
retry_job_id=retry_job_id,
|
||||
retry_error_type=retry_error_type,
|
||||
include_quarantined=include_quarantined,
|
||||
function_version=function_version,
|
||||
recompute=recompute,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1161,17 +1254,57 @@ class RemoteTable(Table):
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[Dict[str, int]] = None,
|
||||
supervisor_resources: Optional[Dict[str, int]] = None,
|
||||
planning_workers: Optional[Dict[str, Any]] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
error_policy: Optional[Literal["fail", "skip"]] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
retry_errors: bool = False,
|
||||
retry_job_id: Optional[str] = None,
|
||||
retry_error_type: Optional[str] = None,
|
||||
include_quarantined: bool = False,
|
||||
function_version: Optional[str] = None,
|
||||
recompute: Optional[Literal["failed", "all", "none"]] = None,
|
||||
) -> Job[RefreshColumnResult]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.refresh_column_async(
|
||||
column,
|
||||
where=where,
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
publication_interval_rows=publication_interval_rows,
|
||||
resource_budget=resource_budget,
|
||||
supervisor_resources=supervisor_resources,
|
||||
planning_workers=planning_workers,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
retry_policy=retry_policy,
|
||||
error_policy=error_policy,
|
||||
max_failed_fraction=max_failed_fraction,
|
||||
max_failed_rows=max_failed_rows,
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
init_timeout_seconds=init_timeout_seconds,
|
||||
num_workers=num_workers,
|
||||
max_executor_processes_per_worker=max_executor_processes_per_worker,
|
||||
retry_errors=retry_errors,
|
||||
retry_job_id=retry_job_id,
|
||||
retry_error_type=retry_error_type,
|
||||
include_quarantined=include_quarantined,
|
||||
function_version=function_version,
|
||||
recompute=recompute,
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -1181,11 +1314,57 @@ class RemoteTable(Table):
|
||||
job_id: Optional[str] = None,
|
||||
column: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
history: bool = False,
|
||||
):
|
||||
return LOOP.run(
|
||||
self._table.function_errors(job_id=job_id, column=column, limit=limit)
|
||||
self._table.function_errors(
|
||||
job_id=job_id, column=column, limit=limit, history=history
|
||||
)
|
||||
).as_sync(self)
|
||||
|
||||
def quarantine_failed(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
error_type: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
after_attempts: Optional[int] = None,
|
||||
quarantined: bool = True,
|
||||
) -> int:
|
||||
return LOOP.run(
|
||||
self._table.quarantine_failed(
|
||||
column,
|
||||
error_type=error_type,
|
||||
job_id=job_id,
|
||||
after_attempts=after_attempts,
|
||||
quarantined=quarantined,
|
||||
)
|
||||
)
|
||||
|
||||
def function_provenance(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
limit: Optional[int] = None,
|
||||
version: Optional[int] = None,
|
||||
) -> FunctionProvenance:
|
||||
return LOOP.run(
|
||||
self._table.function_provenance(column, limit=limit, version=version)
|
||||
)
|
||||
|
||||
def column_statuses(
|
||||
self, column: Optional[str] = None
|
||||
) -> list[FunctionColumnStatus]:
|
||||
return LOOP.run(self._table.column_statuses(column=column))
|
||||
|
||||
def column_status(self, column: str) -> FunctionColumnStatus:
|
||||
return LOOP.run(self._table.column_status(column))
|
||||
|
||||
def wait_fresh(
|
||||
self, column: str, timeout: Optional[timedelta] = None
|
||||
) -> FunctionColumnStatus:
|
||||
return LOOP.run(self._table.wait_fresh(column, timeout))
|
||||
|
||||
def alter_columns(
|
||||
self, *alterations: Iterable[Dict[str, str]]
|
||||
) -> AlterColumnsResult:
|
||||
@@ -1220,7 +1399,11 @@ class RemoteTable(Table):
|
||||
return LOOP.run(self._table.get_table_overrides())
|
||||
|
||||
def update_table_overrides(self, **overrides: Any) -> dict[str, Any]:
|
||||
"""Merge Enterprise table overrides into the current table overrides."""
|
||||
"""Merge Enterprise table overrides using a non-atomic read-modify-write.
|
||||
|
||||
See [the async method][lancedb.AsyncTable.update_table_overrides]
|
||||
for merge behavior and concurrency limitations.
|
||||
"""
|
||||
return LOOP.run(self._table.update_table_overrides(**overrides))
|
||||
|
||||
def reset_table_overrides(self) -> dict[str, Any]:
|
||||
@@ -1282,7 +1465,14 @@ class RemoteTable(Table):
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_index(name))
|
||||
|
||||
def prewarm_data(self, columns: Optional[List[str]] = None) -> None:
|
||||
def prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
) -> None:
|
||||
"""Prewarm data for the table.
|
||||
|
||||
This is a hint to the database that the given columns will be accessed
|
||||
@@ -1290,7 +1480,8 @@ class RemoteTable(Table):
|
||||
Currently only supported in LanceDB Enterprise.
|
||||
|
||||
This call initiates prewarming and returns once the request is accepted.
|
||||
It is idempotent and safe to call from multiple clients concurrently.
|
||||
Uses SQL PREWARM and requires Flight SQL connectivity. To track the
|
||||
durable warming job, use ``prewarm_data_async()``.
|
||||
|
||||
This operation has a large upfront cost but can speed up future queries
|
||||
that need to fetch the given columns. Large columns such as embeddings
|
||||
@@ -1301,8 +1492,62 @@ class RemoteTable(Table):
|
||||
----------
|
||||
columns: list of str, optional
|
||||
The columns to prewarm. If None, all columns are prewarmed.
|
||||
filter: str, optional
|
||||
A single SQL predicate for conservative metadata pruning.
|
||||
parameters: sequence, mapping, or one-row Arrow batch/table, optional
|
||||
Scalar values for ``$1``/``$name`` placeholders in ``filter``.
|
||||
Values are sent separately from SQL; requires server support.
|
||||
concurrency: int, optional
|
||||
Positive per-executor warming concurrency; omitted uses the server default.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> table.prewarm_data( # doctest: +SKIP
|
||||
... ["payload"], filter="quality > 0.7", concurrency=4)
|
||||
"""
|
||||
return LOOP.run(self._table.prewarm_data(columns))
|
||||
return LOOP.run(
|
||||
self._table.prewarm_data(
|
||||
columns, filter=filter, concurrency=concurrency, parameters=parameters
|
||||
)
|
||||
)
|
||||
|
||||
def explain_prewarm_data(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
) -> PrewarmDataPlan:
|
||||
"""Preview prewarm without submitting a warming job.
|
||||
|
||||
See [Table.explain_prewarm_data][lancedb.table.Table.explain_prewarm_data]
|
||||
for options, permissions, snapshot semantics, and limitations.
|
||||
"""
|
||||
return LOOP.run(
|
||||
self._table.explain_prewarm_data(
|
||||
columns, filter=filter, concurrency=concurrency, parameters=parameters
|
||||
)
|
||||
)
|
||||
|
||||
def prewarm_data_async(
|
||||
self,
|
||||
columns: Optional[List[str]] = None,
|
||||
*,
|
||||
filter: Optional[str] = None,
|
||||
concurrency: Optional[int] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
) -> Job[PrewarmDataResult]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.prewarm_data_async(
|
||||
columns,
|
||||
filter=filter,
|
||||
concurrency=concurrency,
|
||||
parameters=parameters,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def wait_for_index(
|
||||
self, index_names: Iterable[str], timeout: timedelta = timedelta(seconds=300)
|
||||
@@ -1321,9 +1566,15 @@ class RemoteTable(Table):
|
||||
return LOOP.run(self._table.uri())
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
|
||||
builder = LanceTakeQueryBuilder(
|
||||
self._table.take_offsets(offsets, preserve_order=preserve_order)
|
||||
)
|
||||
if with_row_id:
|
||||
builder.with_row_id()
|
||||
return builder
|
||||
@@ -1359,13 +1610,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:
|
||||
"""
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import ctypes
|
||||
import importlib
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Iterable, Optional
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -27,6 +28,78 @@ _BLOB_V2_STORAGE_TYPE = pa.struct(
|
||||
]
|
||||
)
|
||||
_resolved_blob_type = None
|
||||
_UINT32_MAX = 0xFFFF_FFFF
|
||||
_UINT64_MAX = 0xFFFF_FFFF_FFFF_FFFF
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BasePath:
|
||||
"""A storage base registered on a table at creation time.
|
||||
|
||||
Use with the ``initial_bases`` argument of
|
||||
[create_table][lancedb.db.DBConnection.create_table] to make
|
||||
external blob URIs resolve under a shared prefix: descriptors that fall
|
||||
under ``path`` are stored relative to it instead of as absolute URIs.
|
||||
|
||||
This is a lightweight stand-in for ``lance.DatasetBasePath`` that does
|
||||
not require pylance. Both classes, and equivalent dictionaries, are
|
||||
accepted by the create APIs.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
path:
|
||||
Full URI of the base (for example ``s3://bucket/prefix`` or a
|
||||
``file://`` URI). A blob URI under this prefix is stored relative to
|
||||
it.
|
||||
name:
|
||||
Optional human-readable name for the base.
|
||||
is_dataset_root:
|
||||
Whether the base uses the dataset-root layout. Defaults to ``False``.
|
||||
Bases registered here must leave this ``False``: Lance only resolves
|
||||
external blob URIs against non-root bases.
|
||||
id:
|
||||
Base ID used by scoped storage options such as ``base_<id>.region``.
|
||||
``None`` lets Lance assign a non-zero ID. ``0`` is reserved for
|
||||
absolute (unregistered) URIs and is rejected.
|
||||
|
||||
When supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
IDs. The pinned Lance release can collide when one base uses automatic
|
||||
allocation and another supplies an explicit ID; the create fails, the
|
||||
table name can remain listed but unopenable, and retrying with distinct
|
||||
explicit IDs succeeds. Automatic allocation for every base is
|
||||
supported.
|
||||
"""
|
||||
|
||||
path: str
|
||||
name: Optional[str] = None
|
||||
is_dataset_root: bool = False
|
||||
id: Optional[int] = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.path, str):
|
||||
raise TypeError(f"path must be a string, got {type(self.path).__name__}")
|
||||
if not self.path:
|
||||
raise ValueError("path must not be empty")
|
||||
if self.name is not None and not isinstance(self.name, str):
|
||||
raise TypeError(f"name must be a string, got {type(self.name).__name__}")
|
||||
if not isinstance(self.is_dataset_root, bool):
|
||||
raise TypeError(
|
||||
"is_dataset_root must be a bool, got "
|
||||
f"{type(self.is_dataset_root).__name__}"
|
||||
)
|
||||
if self.id is None:
|
||||
return
|
||||
if isinstance(self.id, bool) or not isinstance(self.id, int):
|
||||
raise TypeError(f"id must be an int or None, got {type(self.id).__name__}")
|
||||
if self.id == 0:
|
||||
raise ValueError(
|
||||
"id=0 is reserved for unregistered blob URIs; "
|
||||
"pass id=None to let Lance assign an ID"
|
||||
)
|
||||
if self.id < 0:
|
||||
raise ValueError("id must be a positive integer")
|
||||
if self.id > _UINT32_MAX:
|
||||
raise ValueError("id must fit in a 32-bit unsigned integer")
|
||||
|
||||
|
||||
class _FallbackBlobType(pa.ExtensionType):
|
||||
@@ -122,6 +195,15 @@ def blob_v2_column_paths(schema: pa.Schema) -> list[str]:
|
||||
return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)]
|
||||
|
||||
|
||||
def row_addressable_blob_paths(schema: pa.Schema) -> list[str]:
|
||||
"""Blob v1 and v2 paths with one blob addressable by table row id."""
|
||||
return [
|
||||
path
|
||||
for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_like_field)
|
||||
if not has_list_ancestor
|
||||
]
|
||||
|
||||
|
||||
def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]:
|
||||
"""Blob v2 paths with one blob addressable by table row id.
|
||||
|
||||
@@ -335,6 +417,132 @@ def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def _blob_uint64(value: object, what: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
|
||||
if value < 0:
|
||||
raise ValueError(f"{what} must be non-negative")
|
||||
if value > _UINT64_MAX:
|
||||
raise OverflowError(f"{what} must fit in a uint64")
|
||||
return value
|
||||
|
||||
|
||||
def blob_uri_array(
|
||||
uris: Iterable[Optional[str]],
|
||||
*,
|
||||
positions: Optional[Iterable[Optional[int]]] = None,
|
||||
sizes: Optional[Iterable[Optional[int]]] = None,
|
||||
) -> pa.ExtensionArray:
|
||||
"""Build a Lance blob v2 extension array from external URIs.
|
||||
|
||||
Produces the standard four-field blob v2 storage (``data=None``, ``uri``,
|
||||
nullable ``position`` and ``size``) without requiring pylance, so the
|
||||
result can be used directly in Arrow record batches and combined with
|
||||
field metadata such as ``lancedb:logical_type="mp4"``.
|
||||
|
||||
A row without ``position`` and ``size`` references the whole object; a
|
||||
row with both reads exactly that byte range. Register the object prefix
|
||||
with [BasePath][lancedb.schema.BasePath] at table creation to store a
|
||||
matched URI relative to a base, or enable
|
||||
``allow_external_blob_outside_bases`` on the write that inserts the row to
|
||||
keep the absolute URI when no base matches. The opt-in covers that one
|
||||
write; a later ``add()`` must enable it again.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
uris:
|
||||
An iterable of absolute URI strings or ``None`` for a null blob. A
|
||||
URI under a registered base is matched and stored in the descriptor
|
||||
relative to that base. An unmatched URI requires the write that
|
||||
inserts the row to opt in with
|
||||
``allow_external_blob_outside_bases``, and must always be a valid
|
||||
absolute URI.
|
||||
positions:
|
||||
Optional byte offsets, one per URI. Provide together with ``sizes``;
|
||||
each entry is an ``int`` or ``None``. A range requires both fields.
|
||||
sizes:
|
||||
Optional range lengths in bytes, one per URI. Must be positive when
|
||||
``position`` is set.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pa.ExtensionArray
|
||||
external blob values ready to use in Arrow tables or record batches.
|
||||
|
||||
Raises
|
||||
------
|
||||
TypeError
|
||||
If a URI, position, or size has the wrong type.
|
||||
ValueError
|
||||
If lengths differ, only one of ``positions``/``sizes`` is given, a
|
||||
range is incomplete, a size is not positive, or a range is given for
|
||||
a null URI.
|
||||
OverflowError
|
||||
If a position or size does not fit in a uint64.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import pyarrow as pa
|
||||
>>> from lancedb.schema import blob, blob_uri_array
|
||||
>>> schema = pa.schema([blob("video")])
|
||||
>>> videos = blob_uri_array(
|
||||
... ["s3://bucket/a.mp4", "hf://datasets/org/repo@abc/b.mp4"],
|
||||
... positions=[0, 8],
|
||||
... sizes=[4, 4],
|
||||
... )
|
||||
>>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
|
||||
>>> batch.num_rows
|
||||
2
|
||||
"""
|
||||
uri_list = list(uris)
|
||||
if positions is None and sizes is None:
|
||||
ranges = [(None, None)] * len(uri_list)
|
||||
elif positions is None or sizes is None:
|
||||
raise ValueError("positions and sizes must be provided together")
|
||||
else:
|
||||
position_list = list(positions)
|
||||
size_list = list(sizes)
|
||||
if len(position_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"positions must have the same length as uris, got "
|
||||
f"{len(position_list)} and {len(uri_list)}"
|
||||
)
|
||||
if len(size_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"sizes must have the same length as uris, got "
|
||||
f"{len(size_list)} and {len(uri_list)}"
|
||||
)
|
||||
ranges = list(zip(position_list, size_list, strict=True))
|
||||
|
||||
descriptors = []
|
||||
for index, (uri, (position, size)) in enumerate(zip(uri_list, ranges, strict=True)):
|
||||
if uri is None:
|
||||
if position is not None or size is not None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] is None but a position or size was provided"
|
||||
)
|
||||
descriptors.append(None)
|
||||
continue
|
||||
if not isinstance(uri, str):
|
||||
raise TypeError(f"uris[{index}] must be a string, got {type(uri).__name__}")
|
||||
if position is None and size is None:
|
||||
descriptors.append({"uri": uri})
|
||||
continue
|
||||
if position is None or size is None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] must set both position and size or neither"
|
||||
)
|
||||
position = _blob_uint64(position, f"positions[{index}]")
|
||||
size = _blob_uint64(size, f"sizes[{index}]")
|
||||
if size == 0:
|
||||
raise ValueError(f"sizes[{index}] must be positive to read a byte range")
|
||||
descriptors.append({"uri": uri, "position": position, "size": size})
|
||||
|
||||
blob_type = _resolve_blob_type()()
|
||||
storage = pa.array(descriptors, type=blob_type.storage_type)
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType:
|
||||
"""A help function to create a vector type.
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ class EnvVarSecret:
|
||||
|
||||
Pass these in the ``secrets`` sequence of
|
||||
[DBConnection.create_function][lancedb.db.DBConnection.create_function]. The
|
||||
Function's source is unchanged by binding: it reads ``OPENAI_API_KEY`` the
|
||||
Function's source is unchanged by binding: it reads ``MODEL_API_KEY`` the
|
||||
way it always did, and the binding is what puts a value there.
|
||||
|
||||
This is a local value. Constructing it contacts no server, so it always
|
||||
@@ -101,10 +101,10 @@ class EnvVarSecret:
|
||||
--------
|
||||
>>> from lancedb import EnvVarSecret
|
||||
>>> binding = EnvVarSecret(
|
||||
... secret_name="openai-prod", env_variable="OPENAI_API_KEY"
|
||||
... secret_name="model-api-key", env_variable="MODEL_API_KEY"
|
||||
... )
|
||||
>>> binding.secret_name, binding.env_variable
|
||||
('openai-prod', 'OPENAI_API_KEY')
|
||||
('model-api-key', 'MODEL_API_KEY')
|
||||
"""
|
||||
|
||||
__slots__ = ("_secret_name", "_env_variable", "_secret_namespace_path")
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Remote server build information returned as JSON-compatible dictionaries."""
|
||||
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
class ServerBuildInfo(TypedDict):
|
||||
"""Immutable identity compiled into a server executable."""
|
||||
|
||||
release: str
|
||||
git_sha: str
|
||||
build_date: Optional[str]
|
||||
|
||||
|
||||
class ServerInfo(TypedDict):
|
||||
"""The responding query node and its configured Function runtime.
|
||||
|
||||
``query_node`` can be ``None`` when the executable has no build metadata.
|
||||
``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling
|
||||
upgrade, separate requests can reach different query-node builds.
|
||||
Configured images do not establish the version of a running job.
|
||||
"""
|
||||
|
||||
query_node: Optional[ServerBuildInfo]
|
||||
lance_version: str
|
||||
lancedb_version: str
|
||||
function_worker_protocol_version: int
|
||||
configured_query_node_image: Optional[str]
|
||||
configured_job_worker_image: Optional[str]
|
||||
configured_sql_job_image: Optional[str]
|
||||
configured_gpu_worker_image: Optional[str]
|
||||
@@ -104,6 +104,15 @@ class AsyncQuery:
|
||||
"""The stable identifier scoped to the connection that submitted it."""
|
||||
return self._inner.id
|
||||
|
||||
@property
|
||||
def job_id(self) -> Optional[str]:
|
||||
"""The durable Job Registry id once the server reports this query as a job.
|
||||
|
||||
A running query reports it after :meth:`describe` observes the latest
|
||||
server status. This is separate from the connection-scoped ``id``.
|
||||
"""
|
||||
return self._inner.job_id
|
||||
|
||||
async def describe(self) -> QueryDescription:
|
||||
"""Get a point-in-time description of the query."""
|
||||
return await self._inner.describe()
|
||||
@@ -118,7 +127,12 @@ class AsyncQuery:
|
||||
return AsyncRecordBatchReader(await self._inner.reader())
|
||||
|
||||
async def cancel(self) -> None:
|
||||
"""Request cancellation of the query."""
|
||||
"""Request cancellation of this query's Flight execution.
|
||||
|
||||
A durable server-side job may reject this operation because its Flight
|
||||
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
|
||||
with ``job_id`` to cancel that job.
|
||||
"""
|
||||
await self._inner.cancel()
|
||||
|
||||
|
||||
@@ -133,6 +147,15 @@ class Query:
|
||||
"""The stable identifier scoped to the connection that submitted it."""
|
||||
return self._inner.id
|
||||
|
||||
@property
|
||||
def job_id(self) -> Optional[str]:
|
||||
"""The durable Job Registry id once the server reports this query as a job.
|
||||
|
||||
A running query reports it after :meth:`describe` observes the latest
|
||||
server status. This is separate from the connection-scoped ``id``.
|
||||
"""
|
||||
return self._inner.job_id
|
||||
|
||||
def describe(self) -> QueryDescription:
|
||||
"""Get a point-in-time description of the query."""
|
||||
return LOOP.run(self._inner.describe())
|
||||
@@ -159,7 +182,12 @@ class Query:
|
||||
return pa.RecordBatchReader.from_batches(reader.schema, batches())
|
||||
|
||||
def cancel(self) -> None:
|
||||
"""Request cancellation of the query."""
|
||||
"""Request cancellation of this query's Flight execution.
|
||||
|
||||
A durable server-side job may reject this operation because its Flight
|
||||
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
|
||||
with ``job_id`` to cancel that job.
|
||||
"""
|
||||
LOOP.run(self._inner.cancel())
|
||||
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ import warnings
|
||||
from collections import deque
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from copy import deepcopy
|
||||
from multiprocessing import RawArray, get_context
|
||||
from multiprocessing import RawArray, get_all_start_methods, get_context
|
||||
from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -60,6 +60,13 @@ DEFAULT_PREFETCH_BATCHES = 4
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
def _default_worker_start_method() -> str:
|
||||
"""Return the worker start method used when the caller omits a context."""
|
||||
if "forkserver" in get_all_start_methods():
|
||||
return "forkserver"
|
||||
return "spawn"
|
||||
|
||||
|
||||
class _WorkerSample(NamedTuple):
|
||||
data: Any
|
||||
dataset: "StreamingDataset"
|
||||
@@ -1999,6 +2006,14 @@ class StreamingDataLoader(DataLoader):
|
||||
because the custom iterator cannot provide the exact per-yield checkpoint
|
||||
snapshots required by this loader.
|
||||
|
||||
When ``num_workers > 0`` and ``multiprocessing_context`` is omitted or
|
||||
``None``, workers default to the ``forkserver`` start method when the
|
||||
platform provides it, and to ``spawn`` otherwise. Explicit start-method
|
||||
names and context objects are used unchanged. With ``num_workers == 0``,
|
||||
no context is selected, leaving PyTorch's single-process behavior intact.
|
||||
Callbacks and worker state must be picklable under the selected start
|
||||
method, following PyTorch's DataLoader rules.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> # dataset = StreamingDataset(table, num_splits=2)
|
||||
@@ -2028,6 +2043,10 @@ class StreamingDataLoader(DataLoader):
|
||||
)
|
||||
self._streaming_dataset = dataset
|
||||
super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs)
|
||||
# Fill the default only after DataLoader has handled an explicit context;
|
||||
# num_workers=0 keeps whatever PyTorch decided.
|
||||
if self.num_workers > 0 and self.multiprocessing_context is None:
|
||||
self.multiprocessing_context = _default_worker_start_method()
|
||||
if self.drop_last:
|
||||
raise ValueError(
|
||||
"StreamingDataLoader does not support drop_last=True because "
|
||||
|
||||
+1896
-127
File diff suppressed because it is too large
Load Diff
@@ -52,6 +52,7 @@ IndexType = Literal[
|
||||
"BITMAP",
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
"RTREE",
|
||||
"IVF_RQ",
|
||||
]
|
||||
|
||||
|
||||
+332
-32
@@ -8,9 +8,11 @@ import importlib
|
||||
import math
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import warnings
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from functools import singledispatch
|
||||
from typing import Tuple, Union, Optional, Any, List
|
||||
from urllib.parse import urlparse
|
||||
@@ -328,7 +330,7 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]:
|
||||
|
||||
|
||||
def infer_vector_column_name(
|
||||
schema: pa.Schema,
|
||||
schema: Optional[pa.Schema],
|
||||
query_type: str,
|
||||
query: Optional[Any], # inferred later in query builder
|
||||
vector_column_name: Optional[str],
|
||||
@@ -348,6 +350,8 @@ def infer_vector_column_name(
|
||||
# nothing to infer.
|
||||
return None
|
||||
|
||||
if schema is None:
|
||||
raise ValueError("schema is required to infer a vector column")
|
||||
vector_column_name = inf_vector_column_query(schema, dim=_query_vector_dim(query))
|
||||
|
||||
if vector_column_name is None:
|
||||
@@ -382,7 +386,8 @@ def _(value: bytes):
|
||||
|
||||
@value_to_sql.register(int)
|
||||
def _(value: int):
|
||||
return str(value)
|
||||
# int() first: str() of an int-valued Enum member is its name, e.g. "P.HIGH".
|
||||
return str(int(value))
|
||||
|
||||
|
||||
@value_to_sql.register(float)
|
||||
@@ -394,7 +399,7 @@ def _(value: float):
|
||||
return (
|
||||
"CAST('Infinity' AS DOUBLE)" if value > 0 else "CAST('-Infinity' AS DOUBLE)"
|
||||
)
|
||||
return str(value)
|
||||
return str(float(value))
|
||||
|
||||
|
||||
@value_to_sql.register(Decimal)
|
||||
@@ -415,6 +420,12 @@ def _(value: type(None)):
|
||||
return "NULL"
|
||||
|
||||
|
||||
@value_to_sql.register(Enum)
|
||||
def _(value: Enum):
|
||||
# Write the member's value, as model_to_dict does for a LanceModel field.
|
||||
return value_to_sql(value.value)
|
||||
|
||||
|
||||
@value_to_sql.register(datetime)
|
||||
def _(value: datetime):
|
||||
return f"'{value.isoformat()}'"
|
||||
@@ -601,15 +612,253 @@ def tbl_to_tensor(tbl: pa.Table):
|
||||
return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)])
|
||||
|
||||
|
||||
_BFLOAT16_EXTENSION_NAME = "lance.bfloat16"
|
||||
_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name"
|
||||
|
||||
|
||||
def _field_metadata_value(field: pa.Field, key: str):
|
||||
metadata = field.metadata or {}
|
||||
value = metadata.get(key.encode()) or metadata.get(key)
|
||||
if isinstance(value, bytes):
|
||||
return value.decode()
|
||||
return value
|
||||
|
||||
|
||||
def _field_extension_name(field: pa.Field) -> Optional[str]:
|
||||
extension_name = _field_metadata_value(field, _ARROW_EXTENSION_NAME_KEY)
|
||||
if extension_name is not None:
|
||||
return extension_name
|
||||
if isinstance(field.type, pa.ExtensionType):
|
||||
return field.type.extension_name
|
||||
return None
|
||||
|
||||
|
||||
def _field_storage_type(field: pa.Field) -> pa.DataType:
|
||||
if isinstance(field.type, pa.ExtensionType):
|
||||
return field.type.storage_type
|
||||
return field.type
|
||||
|
||||
|
||||
def _is_bfloat16_field(field: pa.Field) -> bool:
|
||||
if _field_extension_name(field) != _BFLOAT16_EXTENSION_NAME:
|
||||
return False
|
||||
storage_type = _field_storage_type(field)
|
||||
return pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
|
||||
|
||||
|
||||
def _check_torch_nulls(array: pa.Array, column_name: str) -> None:
|
||||
if array.null_count:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` to a torch tensor because it "
|
||||
f"contains {array.null_count} null value(s). Drop or fill nulls before "
|
||||
"using a torch format."
|
||||
)
|
||||
|
||||
|
||||
def _bfloat16_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
storage = array.storage if isinstance(array.type, pa.ExtensionType) else array
|
||||
storage_type = storage.type
|
||||
if not (
|
||||
pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
|
||||
):
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` is marked as {_BFLOAT16_EXTENSION_NAME!r} but "
|
||||
f"has storage type {storage_type}. The lance.bfloat16 extension requires "
|
||||
"fixed_size_binary[2] storage."
|
||||
)
|
||||
_check_torch_nulls(storage, column_name)
|
||||
if len(storage) == 0:
|
||||
return torch.empty((0,), dtype=torch.bfloat16)
|
||||
|
||||
buffer = storage.buffers()[1]
|
||||
if buffer is None:
|
||||
return torch.empty((0,), dtype=torch.bfloat16)
|
||||
offset = storage.offset * 2
|
||||
byte_length = len(storage) * 2
|
||||
if buffer.size < offset + byte_length:
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` has a truncated bfloat16 value buffer."
|
||||
)
|
||||
|
||||
# Arrow stores bfloat16 as two little-endian bytes. Copy only on big-endian
|
||||
# hosts before viewing the same bits as torch.bfloat16.
|
||||
values = np.frombuffer(
|
||||
buffer, dtype=np.dtype("<u2"), count=len(storage), offset=offset
|
||||
)
|
||||
if sys.byteorder != "little":
|
||||
values = values.astype(np.uint16)
|
||||
# Older torch releases cannot create a tensor from np.uint16, so view the
|
||||
# same bits as signed 16-bit values before interpreting them as bfloat16.
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message="The given NumPy array is not writable",
|
||||
category=UserWarning,
|
||||
)
|
||||
return torch.from_numpy(values.view(np.int16)).view(torch.bfloat16)
|
||||
|
||||
|
||||
def _leaf_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
if _is_bfloat16_field(field):
|
||||
return _bfloat16_to_tensor(array, torch, column_name)
|
||||
|
||||
data_type = array.type
|
||||
if isinstance(data_type, pa.ExtensionType):
|
||||
raise ValueError(
|
||||
f"Unsupported PyTorch column type {data_type} for column "
|
||||
f"`{column_name}`. Supported extension types are "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r} and arrow.fixed_shape_tensor."
|
||||
)
|
||||
if (
|
||||
pa.types.is_boolean(data_type)
|
||||
or pa.types.is_integer(data_type)
|
||||
or pa.types.is_floating(data_type)
|
||||
):
|
||||
# Arrow packs booleans as bits while torch uses one byte per value, so
|
||||
# boolean columns always need a copy. Other numeric columns share the
|
||||
# Arrow buffer.
|
||||
zero_copy_only = not pa.types.is_boolean(data_type)
|
||||
try:
|
||||
numpy_values = array.to_numpy(zero_copy_only=zero_copy_only)
|
||||
except pa.ArrowInvalid as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` of type {data_type} to a "
|
||||
f"torch tensor without copying: {err}"
|
||||
) from err
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message="The given NumPy array is not writable",
|
||||
category=UserWarning,
|
||||
)
|
||||
return torch.from_numpy(numpy_values)
|
||||
except (TypeError, RuntimeError) as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` of type {data_type} to a "
|
||||
f"torch tensor: {err}"
|
||||
) from err
|
||||
if pa.types.is_fixed_size_binary(data_type) and data_type.byte_width == 2:
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` has type fixed_size_binary[2] but is not "
|
||||
f"marked with {_ARROW_EXTENSION_NAME_KEY!r} = "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r}. An unmarked binary column is not "
|
||||
"treated as bfloat16."
|
||||
)
|
||||
raise ValueError(
|
||||
f"Unsupported PyTorch column type {data_type} for column `{column_name}`. "
|
||||
"Supported leaf types are boolean, integer, floating point, and "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r} fixed_size_binary[2] values."
|
||||
)
|
||||
|
||||
|
||||
def _fixed_size_list_to_tensor(array: pa.FixedSizeListArray, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
width = array.type.list_size
|
||||
values = array.values.slice(array.offset * width, len(array) * width)
|
||||
child_tensor = _arrow_column_to_tensor(
|
||||
values, array.type.value_field, torch, column_name
|
||||
)
|
||||
return child_tensor.reshape((len(array), width, *child_tensor.shape[1:]))
|
||||
|
||||
|
||||
def _fixed_shape_tensor_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
tensor_type = array.type
|
||||
storage = array.storage
|
||||
physical_shape = list(tensor_type.shape)
|
||||
permutation = list(getattr(tensor_type, "permutation", None) or [])
|
||||
storage_tensor = _arrow_column_to_tensor(
|
||||
storage, storage.type.value_field, torch, column_name
|
||||
)
|
||||
tensor = storage_tensor.reshape((len(array), *physical_shape))
|
||||
if permutation:
|
||||
# Arrow's ``shape`` is the physical row-major shape, and
|
||||
# ``permutation`` maps a logical axis to its physical axis. Transposing
|
||||
# by it restores the logical shape as a view.
|
||||
tensor = tensor.permute([0] + [axis + 1 for axis in permutation])
|
||||
return tensor
|
||||
|
||||
|
||||
def _arrow_column_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
|
||||
if isinstance(array.type, pa.FixedShapeTensorType):
|
||||
return _fixed_shape_tensor_to_tensor(array, torch, column_name)
|
||||
if pa.types.is_fixed_size_list(array.type):
|
||||
return _fixed_size_list_to_tensor(array, torch, column_name)
|
||||
return _leaf_to_tensor(array, field, torch, column_name).reshape((len(array),))
|
||||
|
||||
|
||||
def _is_nullable_numeric_scalar(array: pa.Array) -> bool:
|
||||
data_type = array.type
|
||||
if isinstance(data_type, pa.ExtensionType) or array.null_count == 0:
|
||||
return False
|
||||
return pa.types.is_integer(data_type) or pa.types.is_floating(data_type)
|
||||
|
||||
|
||||
def _nullable_numeric_scalar_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
try:
|
||||
numpy_values = array.to_numpy(zero_copy_only=False)
|
||||
except pa.ArrowInvalid as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert nullable column `{column_name}` of type {array.type} "
|
||||
f"to a torch tensor: {err}"
|
||||
) from err
|
||||
try:
|
||||
return torch.from_numpy(numpy_values)
|
||||
except (TypeError, RuntimeError) as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert nullable column `{column_name}` of type {array.type} "
|
||||
f"to a torch tensor: {err}"
|
||||
) from err
|
||||
|
||||
|
||||
def _batch_column_tensors(batch: pa.RecordBatch, allow_scalar_nulls: bool = False):
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
columns = []
|
||||
for field, column in zip(batch.schema, batch.columns):
|
||||
if allow_scalar_nulls and _is_nullable_numeric_scalar(column):
|
||||
tensor = _nullable_numeric_scalar_to_tensor(column, torch, field.name)
|
||||
else:
|
||||
tensor = _arrow_column_to_tensor(column, field, torch, field.name)
|
||||
columns.append((field.name, tensor))
|
||||
return torch, columns
|
||||
|
||||
|
||||
def _uniform_column_tensors(
|
||||
batch: pa.RecordBatch, format_name: str, allow_scalar_nulls: bool = False
|
||||
):
|
||||
torch, columns = _batch_column_tensors(batch, allow_scalar_nulls=allow_scalar_nulls)
|
||||
if len(columns) <= 1:
|
||||
return torch, columns
|
||||
|
||||
first_name, first = columns[0]
|
||||
first_shape = tuple(first.shape[1:])
|
||||
for name, tensor in columns[1:]:
|
||||
shape = tuple(tensor.shape[1:])
|
||||
if shape != first_shape:
|
||||
raise ValueError(
|
||||
f"Cannot use the {format_name!r} format because column `{name}` "
|
||||
f"has sample shape {shape} while column `{first_name}` has sample "
|
||||
f'shape {first_shape}. Use with_format("torch_dict") for columns '
|
||||
'with different shapes, or with_format("torch") for a list of '
|
||||
"per-row dicts."
|
||||
)
|
||||
return torch, columns
|
||||
|
||||
|
||||
def batch_to_tensor(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a PyTorch Tensor.
|
||||
|
||||
Each column is converted to a tensor (using zero-copy via DLPack)
|
||||
and the columns are then stacked into a single tensor.
|
||||
Each column is converted to a tensor with shape ``(rows, *sample_shape)``
|
||||
and the columns are stacked along a new leading dimension. Scalar columns
|
||||
have sample shape ``()`` and fixed-size-list columns contribute each list
|
||||
dimension. All columns must have the same sample shape.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -618,43 +867,99 @@ def batch_to_tensor(batch: pa.RecordBatch):
|
||||
|
||||
Returns
|
||||
-------
|
||||
torch.Tensor: The tensor containing the columns of the record batch.
|
||||
torch.Tensor: A tensor with shape ``(columns, rows, *sample_shape)``. A
|
||||
one-column batch returns an ``unsqueeze(0)`` view of that column.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
return torch.stack([torch.from_dlpack(col) for col in batch.columns])
|
||||
torch, columns = _uniform_column_tensors(batch, "torch_col")
|
||||
if not columns:
|
||||
return torch.empty((0, batch.num_rows))
|
||||
if len(columns) == 1:
|
||||
return columns[0][1].unsqueeze(0)
|
||||
return torch.stack([tensor for _, tensor in columns], dim=0)
|
||||
|
||||
|
||||
def batch_to_tensor_rows(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a list of PyTorch Tensor, one per row
|
||||
Convert a PyArrow RecordBatch to a list of PyTorch Tensors, one per row.
|
||||
|
||||
Each column is converted to a tensor (using zero-copy via DLPack)
|
||||
and the columns are then stacked into a single tensor. The 2D tensor
|
||||
is then converted to a list of tensors, one per row
|
||||
Each row tensor has shape ``(columns, *sample_shape)``. All columns must
|
||||
have the same sample shape, so a table mixing scalar and vector columns
|
||||
should use ``torch_dict`` or ``torch`` instead. Dtypes are combined with
|
||||
``torch.promote_types``, matching PyTorch's numeric promotion rules.
|
||||
|
||||
Fails if torch or numpy is not installed.
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Nulls in ordinary integer or floating scalar columns become ``NaN``.
|
||||
Nulls in nested fixed-size-list or tensor columns are rejected.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch : pa.RecordBatch
|
||||
The record batch to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[torch.Tensor]
|
||||
One tensor per row, each with shape ``(columns, *sample_shape)``. A
|
||||
one-column scalar batch produces ``(1,)`` tensors.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
numpy = attempt_import_or_raise("numpy", "numpy")
|
||||
columns = [col.to_numpy(zero_copy_only=False) for col in batch.columns]
|
||||
stacked = torch.tensor(numpy.column_stack(columns))
|
||||
rows = list(stacked.unbind(dim=0))
|
||||
return rows
|
||||
torch, columns = _uniform_column_tensors(
|
||||
batch, "torch_row", allow_scalar_nulls=True
|
||||
)
|
||||
if not columns:
|
||||
return [torch.empty((0,)) for _ in range(batch.num_rows)]
|
||||
|
||||
dtype = columns[0][1].dtype
|
||||
for _, tensor in columns[1:]:
|
||||
dtype = torch.promote_types(dtype, tensor.dtype)
|
||||
tensors = [
|
||||
tensor if tensor.dtype == dtype else tensor.to(dtype) for _, tensor in columns
|
||||
]
|
||||
stacked = torch.stack(tensors, dim=1)
|
||||
return list(stacked.unbind(dim=0))
|
||||
|
||||
|
||||
def batch_to_tensor_columns(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a dict of per-column PyTorch Tensors.
|
||||
|
||||
Each tensor has shape ``(rows, *sample_shape)`` and shares Arrow storage
|
||||
where the layout allows it. Unlike ``torch_col`` and ``torch_row``, columns
|
||||
may have different sample shapes. This is the transform behind
|
||||
``Permutation.with_format("torch_dict")`` and can be consumed directly by
|
||||
a ``DataLoader`` with an identity ``collate_fn``.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch : pa.RecordBatch
|
||||
The record batch to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, torch.Tensor]
|
||||
A tensor per column, each with shape ``(rows, *sample_shape)``.
|
||||
"""
|
||||
_, columns = _batch_column_tensors(batch)
|
||||
return dict(columns)
|
||||
|
||||
|
||||
def batch_to_tensor_dict(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a list of per-row dicts of PyTorch Tensors.
|
||||
|
||||
Each column is first converted to a 1-D tensor (zero-copy via DLPack), then
|
||||
sliced per row. The result is a list whose length is ``batch.num_rows`` and
|
||||
whose items are dicts keyed by column name. This shape composes directly
|
||||
with PyTorch's default ``DataLoader`` collate, which stacks the per-row
|
||||
dicts back into a dict of batched tensors.
|
||||
Each column is converted to a tensor with shape ``(rows, *sample_shape)``,
|
||||
then sliced per row. The result is a list whose length is
|
||||
``batch.num_rows`` and whose items are dicts keyed by column name. This
|
||||
shape composes directly with PyTorch's default ``DataLoader`` collate,
|
||||
which stacks the per-row dicts back into a dict of batched tensors.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -665,14 +970,9 @@ def batch_to_tensor_dict(batch: pa.RecordBatch):
|
||||
-------
|
||||
list[dict[str, torch.Tensor]]
|
||||
One per-row dict per row in the batch. Each dict maps column name to a
|
||||
0-D tensor view into the column.
|
||||
tensor view into the column.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
tensors = {
|
||||
name: torch.from_dlpack(col)
|
||||
for name, col in zip(batch.schema.names, batch.columns)
|
||||
}
|
||||
_, columns = _batch_column_tensors(batch)
|
||||
return [
|
||||
{name: tensor[i] for name, tensor in tensors.items()}
|
||||
for i in range(batch.num_rows)
|
||||
{name: tensor[i] for name, tensor in columns} for i in range(batch.num_rows)
|
||||
]
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop"
|
||||
|
||||
|
||||
def _run_in_subprocess(code: str, timeout: int = 30) -> subprocess.CompletedProcess:
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
|
||||
return subprocess.run(
|
||||
[sys.executable, "-c", textwrap.dedent(code)],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None:
|
||||
assert result.returncode == 0, result.stderr or result.stdout
|
||||
|
||||
|
||||
def test_import_and_inspection_do_not_start_background_loop():
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import threading
|
||||
|
||||
import lancedb
|
||||
from lancedb.background_loop import BackgroundEventLoop, LOOP
|
||||
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == {BACKGROUND_THREAD_NAME!r}
|
||||
]
|
||||
|
||||
assert LOOP.thread is None
|
||||
assert LOOP.loop is None
|
||||
assert background_threads() == []
|
||||
|
||||
# Inspecting a fresh instance is also side-effect free.
|
||||
loop = BackgroundEventLoop()
|
||||
assert loop.thread is None
|
||||
assert loop.loop is None
|
||||
assert background_threads() == []
|
||||
"""
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
def test_first_sync_call_starts_one_daemon_thread():
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import threading
|
||||
|
||||
import lancedb
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == {BACKGROUND_THREAD_NAME!r}
|
||||
]
|
||||
|
||||
assert LOOP.thread is None
|
||||
assert LOOP.loop is None
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
assert db.table_names() == []
|
||||
|
||||
worker = LOOP.thread
|
||||
assert worker is not None
|
||||
assert worker is background_threads()[0]
|
||||
assert len(background_threads()) == 1
|
||||
assert worker.daemon
|
||||
assert worker.is_alive()
|
||||
assert LOOP.loop is not None
|
||||
"""
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
def test_concurrent_first_use_initializes_one_background_thread():
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
worker_count = 8
|
||||
barrier = threading.Barrier(worker_count)
|
||||
results = []
|
||||
errors = []
|
||||
results_lock = threading.Lock()
|
||||
|
||||
def submit(index):
|
||||
try:
|
||||
barrier.wait(timeout=10)
|
||||
value = LOOP.run(asyncio.sleep(0.05, result=index))
|
||||
with results_lock:
|
||||
results.append(value)
|
||||
except BaseException as exc:
|
||||
with results_lock:
|
||||
errors.append(repr(exc))
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=submit, args=(index,))
|
||||
for index in range(worker_count)
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=20)
|
||||
|
||||
assert all(not thread.is_alive() for thread in threads)
|
||||
assert errors == []
|
||||
assert sorted(results) == list(range(worker_count))
|
||||
|
||||
background_threads = [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == {BACKGROUND_THREAD_NAME!r}
|
||||
]
|
||||
assert len(background_threads) == 1
|
||||
assert background_threads[0].daemon
|
||||
"""
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform != "linux",
|
||||
reason=(
|
||||
"fork() is unavailable on Windows and unsafe on macOS "
|
||||
"(Apple frameworks/TLS are not fork-safe)"
|
||||
),
|
||||
)
|
||||
def test_forked_child_starts_background_loop_lazily():
|
||||
# Fork from a fresh interpreter: earlier tests in a shared pytest process
|
||||
# may have left native runtime state that is not part of this scenario.
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
BACKGROUND_THREAD_NAME = {BACKGROUND_THREAD_NAME!r}
|
||||
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == BACKGROUND_THREAD_NAME
|
||||
]
|
||||
|
||||
def fork_child(queue):
|
||||
try:
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
inherited_thread_is_none = LOOP.thread is None
|
||||
inherited_loop_is_none = LOOP.loop is None
|
||||
background_threads_before = [
|
||||
thread.name for thread in background_threads()
|
||||
]
|
||||
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
tables = db.table_names()
|
||||
|
||||
worker = LOOP.thread
|
||||
queue.put(
|
||||
dict(
|
||||
error=None,
|
||||
inherited_thread_is_none=inherited_thread_is_none,
|
||||
inherited_loop_is_none=inherited_loop_is_none,
|
||||
background_threads_before=background_threads_before,
|
||||
tables=tables,
|
||||
thread_alive=False if worker is None else worker.is_alive(),
|
||||
thread_daemon=False if worker is None else worker.daemon,
|
||||
background_thread_count=len(background_threads()),
|
||||
)
|
||||
)
|
||||
except BaseException:
|
||||
queue.put(dict(error=traceback.format_exc()))
|
||||
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
|
||||
parent_thread = LOOP.thread
|
||||
assert parent_thread is not None
|
||||
|
||||
ctx = mp.get_context("fork")
|
||||
queue = ctx.Queue()
|
||||
|
||||
# Simulate forking while another thread held the initialization lock. The
|
||||
# child must replace the inherited lock instead of trying to acquire it.
|
||||
LOOP._start_lock.acquire()
|
||||
try:
|
||||
proc = ctx.Process(target=fork_child, args=(queue,))
|
||||
proc.start()
|
||||
finally:
|
||||
LOOP._start_lock.release()
|
||||
|
||||
proc.join(timeout=20)
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
proc.join(timeout=5)
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
proc.join()
|
||||
raise AssertionError("Forked child hung starting the background loop")
|
||||
|
||||
assert proc.exitcode == 0, "child exited with code %s" % proc.exitcode
|
||||
payload = queue.get(timeout=5)
|
||||
queue.close()
|
||||
assert payload["error"] is None, payload["error"]
|
||||
assert payload["inherited_thread_is_none"] is True
|
||||
assert payload["inherited_loop_is_none"] is True
|
||||
assert payload["background_threads_before"] == []
|
||||
assert payload["tables"] == []
|
||||
assert payload["thread_alive"] is True
|
||||
assert payload["thread_daemon"] is True
|
||||
assert payload["background_thread_count"] == 1
|
||||
|
||||
# The child's reset must not disturb the parent's loop.
|
||||
assert LOOP.thread is parent_thread
|
||||
assert parent_thread.is_alive()
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
|
||||
""",
|
||||
# join(20) + terminate join(5) + queue get(5), plus startup and traceback.
|
||||
timeout=40,
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
@@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode():
|
||||
1: b"one",
|
||||
2: b"two",
|
||||
}
|
||||
ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["id"].to_pylist() == [2, 1]
|
||||
assert ordered["image"].to_pylist() == [b"two", b"one"]
|
||||
assert [
|
||||
row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes")
|
||||
] == [b"one"]
|
||||
@@ -1070,8 +1075,10 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path):
|
||||
)
|
||||
table.add([{"id": 1, "image": b"one"}])
|
||||
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot") as exc:
|
||||
table.to_arrow(blob_mode="bytes")
|
||||
assert "fetch_blobs(column, row_ids)" in str(exc.value)
|
||||
assert "with_row_id(True)" in str(exc.value)
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
table.search().to_list(blob_mode="bytes")
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
@@ -1103,6 +1110,54 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path)
|
||||
await table.query().to_batches(blob_mode="bytes")
|
||||
|
||||
|
||||
def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
rows = [
|
||||
{"id": 1, "image": b"one"},
|
||||
{"id": 2, "image": b""},
|
||||
{"id": 3, "image": None},
|
||||
{"id": 4, "image": b"excluded"},
|
||||
]
|
||||
source = db.create_table("source", data=rows, schema=schema)
|
||||
hits = (
|
||||
source.search()
|
||||
.where("id < 4")
|
||||
.select(["id"])
|
||||
.with_row_id(True)
|
||||
.limit(100)
|
||||
.to_arrow()
|
||||
)
|
||||
payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist()
|
||||
subset = db.create_table("subset", schema=schema)
|
||||
subset.add(
|
||||
[
|
||||
{"id": image_id, "image": payload}
|
||||
for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True)
|
||||
]
|
||||
)
|
||||
copied = subset.search().to_list(blob_mode="bytes")
|
||||
assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
|
||||
|
||||
|
||||
def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema)
|
||||
hits = source.search().where("id = 1").to_arrow()
|
||||
|
||||
with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc:
|
||||
db.create_table("copy", data=hits, schema=schema)
|
||||
|
||||
message = str(exc.value)
|
||||
assert "blob_mode='bytes'" in message
|
||||
assert "blob_mode='descriptions'" in message
|
||||
assert "with_row_id(True)" in message
|
||||
assert "fetch_blobs(column, row_ids)" in message
|
||||
assert "fetch_blob_files(column, row_ids)" in message
|
||||
assert not db.table_exists(["copy"])
|
||||
|
||||
|
||||
def test_fetch_blobs_round_trip():
|
||||
table = _blob_table(
|
||||
"round_trip",
|
||||
@@ -1619,16 +1674,41 @@ def test_bytes_mode_rejects_blobs_inside_lists():
|
||||
|
||||
|
||||
def test_row_addressable_paths_exclude_list_children():
|
||||
from lancedb.schema import row_addressable_blob_v2_paths
|
||||
from lancedb.schema import (
|
||||
row_addressable_blob_paths,
|
||||
row_addressable_blob_v2_paths,
|
||||
)
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("info", pa.struct([lancedb.blob("blob")])),
|
||||
pa.field(
|
||||
"info",
|
||||
pa.struct(
|
||||
[
|
||||
lancedb.blob("blob"),
|
||||
pa.field(
|
||||
"legacy",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
]
|
||||
),
|
||||
),
|
||||
pa.field(
|
||||
"legacy",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
pa.field("images", pa.list_(lancedb.blob("image"))),
|
||||
]
|
||||
)
|
||||
assert blob_v2_column_paths(schema) == ["info.blob", "images.image"]
|
||||
assert row_addressable_blob_paths(schema) == [
|
||||
"info.blob",
|
||||
"info.legacy",
|
||||
"legacy",
|
||||
]
|
||||
assert row_addressable_blob_v2_paths(schema) == ["info.blob"]
|
||||
|
||||
|
||||
@@ -1883,6 +1963,18 @@ def test_fetch_blob_apis_reject_missing_fragment_row_addr():
|
||||
_assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live])
|
||||
|
||||
|
||||
def test_fetch_blobs_missing_row_ids_suggest_take_offsets():
|
||||
table = _blob_table(
|
||||
"position_hint",
|
||||
[{"id": i, "image": b"x"} for i in range(3)],
|
||||
)
|
||||
with pytest.raises(ValueError, match="take_offsets") as exc:
|
||||
table.fetch_blobs("image", [10])
|
||||
message = str(exc.value)
|
||||
assert "first missing row ids: [10]" in message
|
||||
assert "with_row_id=True" in message
|
||||
|
||||
|
||||
def test_fetch_blob_apis_reject_deleted_row_ids():
|
||||
table = _blob_table(
|
||||
"deleted_rows",
|
||||
@@ -2141,8 +2233,11 @@ def test_fetch_blobs_from_query_result_without_row_id_raises():
|
||||
table = _blob_table("no_rowid", [{"id": 1, "image": b"x"}])
|
||||
hits = table.search().select(["id"]).to_arrow()
|
||||
assert "_rowid" not in hits.column_names
|
||||
with pytest.raises(ValueError, match="_rowid"):
|
||||
with pytest.raises(ValueError, match="take_offsets") as exc:
|
||||
table.fetch_blobs("image", hits)
|
||||
message = str(exc.value)
|
||||
assert "with_row_id=True" in message
|
||||
assert "list of row ids" in message
|
||||
|
||||
|
||||
_HYBRID_BLOB_SCHEMA = pa.schema(
|
||||
@@ -2293,6 +2388,8 @@ async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch):
|
||||
if blob_mode != "lazy":
|
||||
assert "_rowid" not in reader.schema.names
|
||||
assert "_lance_row_id" not in str(reader.schema)
|
||||
else:
|
||||
assert "_rowid" in reader.schema.names
|
||||
|
||||
|
||||
class _KeepAllScoresReranker(Reranker):
|
||||
@@ -2307,6 +2404,77 @@ class _KeepAllScoresReranker(Reranker):
|
||||
return combined.append_column("_relevance_score", scores)
|
||||
|
||||
|
||||
class _RecordingVectorReranker(Reranker):
|
||||
def __init__(self):
|
||||
super().__init__(return_score="all")
|
||||
self.calls = []
|
||||
|
||||
def rerank_hybrid(self, query, vector_results, fts_results):
|
||||
raise AssertionError("vector queries must not call rerank_hybrid")
|
||||
|
||||
def rerank_vector(self, query, vector_results):
|
||||
self.calls.append((query, vector_results))
|
||||
return vector_results.append_column(
|
||||
"_relevance_score",
|
||||
pa.array([1.0] * len(vector_results), type=pa.float32()),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
|
||||
def test_vector_to_arrow_reranks_before_blob_conversion(blob_mode, monkeypatch):
|
||||
db = lancedb.connect("memory:///")
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
||||
lancedb.blob("image"),
|
||||
]
|
||||
)
|
||||
table = db.create_table(f"vector_rerank_{blob_mode}", schema=schema)
|
||||
rows = 1100
|
||||
table.add(
|
||||
[
|
||||
{
|
||||
"id": row_id,
|
||||
"vector": [1.0, float(row_id % 2)],
|
||||
"image": f"image-{row_id}".encode(),
|
||||
}
|
||||
for row_id in range(rows)
|
||||
]
|
||||
)
|
||||
fetched = []
|
||||
fetch_blobs = table.fetch_blobs
|
||||
|
||||
def fetch(column, row_ids):
|
||||
fetched.append((column, len(row_ids)))
|
||||
return fetch_blobs(column, row_ids)
|
||||
|
||||
monkeypatch.setattr(table, "fetch_blobs", fetch)
|
||||
reranker = _RecordingVectorReranker()
|
||||
hits = (
|
||||
table.search([1.0, 0.0])
|
||||
.limit(rows)
|
||||
.select(["id", "image"])
|
||||
.rerank(reranker, "hello")
|
||||
.to_arrow(blob_mode=blob_mode)
|
||||
)
|
||||
|
||||
assert len(reranker.calls) == 1
|
||||
query, source = reranker.calls[0]
|
||||
assert query == "hello"
|
||||
# The reranker sees descriptors, not already-converted payload bytes.
|
||||
assert not pa.types.is_large_binary(source.schema.field("image").type)
|
||||
assert "_relevance_score" in hits.column_names
|
||||
assert len(hits) == rows
|
||||
if blob_mode == "bytes":
|
||||
# The whole lazy result is materialized before one aggregate conversion.
|
||||
assert fetched == [("image", rows)]
|
||||
assert pa.types.is_large_binary(hits.schema.field("image").type)
|
||||
else:
|
||||
assert fetched == []
|
||||
assert not pa.types.is_large_binary(hits.schema.field("image").type)
|
||||
|
||||
|
||||
def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
@@ -2336,7 +2504,7 @@ def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
|
||||
.rerank(_KeepAllScoresReranker())
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*legacy blob columns"):
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
||||
query.to_arrow(blob_mode="bytes")
|
||||
|
||||
|
||||
@@ -3099,3 +3267,393 @@ async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
|
||||
with file:
|
||||
actual.append(await file.aread())
|
||||
assert actual == [None, b"alpha", b"alpha"]
|
||||
|
||||
|
||||
def _initial_base_payloads(tmp_path):
|
||||
base_dir = tmp_path / "videos"
|
||||
base_dir.mkdir(exist_ok=True)
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
return base_dir, clip, payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_spec", ["lightweight", "dict", "dataset_base_path"])
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_store_relative_blob_ranges(
|
||||
tmp_path, base_spec, use_async
|
||||
):
|
||||
lance = None
|
||||
if base_spec == "dataset_base_path":
|
||||
lance = pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
field = lancedb.blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
base_kwargs = {"path": base_dir.as_uri(), "name": "source", "id": 1}
|
||||
if base_spec == "lightweight":
|
||||
bases = [lancedb.BasePath(**base_kwargs)]
|
||||
elif base_spec == "dict":
|
||||
bases = [base_kwargs]
|
||||
else:
|
||||
bases = [lance.DatasetBasePath(**base_kwargs)]
|
||||
|
||||
if use_async:
|
||||
db = await lancedb.connect_async(tmp_path / "db")
|
||||
table = await db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert await table.version() == 1
|
||||
created_schema = await table.schema()
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload[:6]]
|
||||
assert (
|
||||
await reopened.fetch_blob_ranges("video", [(row_id, 1, 3)])
|
||||
).to_pylist() == [payload[1:4]]
|
||||
else:
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
created_schema = table.schema
|
||||
# Manifest introspection needs pylance; the lightweight and dict
|
||||
# variants must still prove registration through the reopen and bytes.
|
||||
if lance is not None:
|
||||
registered = table.to_lance().base_paths()[1]
|
||||
assert registered.path == base_dir.as_uri()
|
||||
assert registered.is_dataset_root is False
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
assert created_schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
|
||||
|
||||
def test_create_table_initial_bases_bootstrap_empty_table_with_auto_id(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source")],
|
||||
)
|
||||
assert table.version == 1
|
||||
registered = list(table.to_lance().base_paths().values())
|
||||
assert len(registered) == 1
|
||||
assert registered[0].id > 0
|
||||
assert registered[0].path == base_dir.as_uri()
|
||||
assert registered[0].is_dataset_root is False
|
||||
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
table.add(rows)
|
||||
reopened = db.open_table("videos")
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1]]).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_reject_bad_input(tmp_path):
|
||||
base_dir, _, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect("memory:///")
|
||||
path = base_dir.as_uri()
|
||||
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
lancedb.BasePath(path=path, id=0)
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
db.create_table("zero", schema=schema, initial_bases=[{"path": path, "id": 0}])
|
||||
with pytest.raises(ValueError, match="unique"):
|
||||
db.create_table(
|
||||
"duplicates",
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=path, id=1),
|
||||
lancedb.BasePath(path=f"{path}/other", id=1),
|
||||
],
|
||||
)
|
||||
with pytest.raises(ValueError, match="missing 'path'"):
|
||||
db.create_table("missing_path", schema=schema, initial_bases=[{"id": 1}])
|
||||
with pytest.raises(TypeError, match="must be a BasePath, dict, or DatasetBasePath"):
|
||||
db.create_table("not_a_base", schema=schema, initial_bases=[object()])
|
||||
|
||||
|
||||
def test_create_table_allow_external_blob_outside_bases_is_atomic(tmp_path):
|
||||
payload = b"0123456789abcdef"
|
||||
clip = tmp_path / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
with pytest.raises(ValueError, match="allow_external_blob_outside_bases"):
|
||||
db.create_table("rejected", data=rows, schema=schema)
|
||||
with pytest.raises(ValueError, match="requires initial data"):
|
||||
db.create_table(
|
||||
"empty_opt_in", schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos", data=rows, schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 0, 6)]).to_pylist() == [
|
||||
payload[:6]
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_keep_scoped_options_on_reopen(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload = b"scoped-payload"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload)
|
||||
clip_b.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
storage_options = {
|
||||
"timeout": "7s",
|
||||
"base_1.region": "base-one",
|
||||
"base_2.region": "base-two",
|
||||
}
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
storage_options=storage_options,
|
||||
)
|
||||
assert table.version == 1
|
||||
assert {base.id for base in table.to_lance().base_paths().values()} == {1, 2}
|
||||
|
||||
reopened = db.open_table("videos", storage_options=storage_options)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1], by_id[2]]).to_pylist() == [
|
||||
payload,
|
||||
payload,
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_through_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
|
||||
|
||||
def test_namespace_create_keeps_scoped_options_over_connection_defaults(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
# The invalid scoped option belongs to base 1. It must survive the merge
|
||||
# with connection defaults instead of being replaced by them.
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)
|
||||
],
|
||||
storage_options={"base_1.scheduler_error_mode": "invalid"},
|
||||
)
|
||||
|
||||
|
||||
def test_namespace_reopen_applies_scoped_options_per_base(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload_a = b"namespace-base-a"
|
||||
payload_b = b"namespace-base-b"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload_a)
|
||||
clip_b.write_bytes(payload_b)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
)
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.scheduler_error_mode": "invalid"}
|
||||
)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
reopened.fetch_blobs("video", [by_id[1]])
|
||||
assert reopened.fetch_blobs("video", [by_id[2]]).to_pylist() == [payload_b]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_through_async_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = await db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert await table.version() == 1
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_namespace_refresh_layers_caller_scoped_options(tmp_path):
|
||||
from lance_namespace import (
|
||||
DeclareTableResponse,
|
||||
DescribeTableResponse,
|
||||
LanceNamespace,
|
||||
)
|
||||
from lancedb.namespace import LanceNamespaceDBConnection
|
||||
|
||||
class RefreshingNamespace(LanceNamespace):
|
||||
def __init__(self, location):
|
||||
self.location = location
|
||||
self.refreshes = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return self.location
|
||||
|
||||
def declare_table(self, request):
|
||||
return DeclareTableResponse(
|
||||
location=self.location,
|
||||
storage_options={
|
||||
"timeout": "7s",
|
||||
# Expired immediately so the next read must refresh.
|
||||
"expires_at_millis": "1",
|
||||
},
|
||||
)
|
||||
|
||||
def describe_table(self, request):
|
||||
self.refreshes += 1
|
||||
return DescribeTableResponse(
|
||||
location=self.location,
|
||||
storage_options={"timeout": "8s", "namespace_vended": "fresh"},
|
||||
)
|
||||
|
||||
payload = b"0123456789abcdef"
|
||||
base_dir = tmp_path / "base"
|
||||
base_dir.mkdir()
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
namespace = RefreshingNamespace((tmp_path / "table.lance").as_uri())
|
||||
db = LanceNamespaceDBConnection(namespace)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(base_dir.as_uri(), name="base", id=1)],
|
||||
storage_options={"base_1.caller_scoped": "keep-me"},
|
||||
)
|
||||
initial = table.initial_storage_options()
|
||||
assert initial["base_1.caller_scoped"] == "keep-me"
|
||||
assert initial["timeout"] == "7s"
|
||||
|
||||
latest = table.latest_storage_options()
|
||||
assert namespace.refreshes > 0, "expired seed did not trigger a refresh"
|
||||
assert latest["base_1.caller_scoped"] == "keep-me"
|
||||
assert latest["timeout"] == "8s"
|
||||
assert latest["namespace_vended"] == "fresh"
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.caller_scoped": "keep-me"}
|
||||
)
|
||||
assert reopened.latest_storage_options()["base_1.caller_scoped"] == "keep-me"
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", [row_id]).to_pylist() == [payload]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 4, 6)]).to_pylist() == [
|
||||
payload[4:10]
|
||||
]
|
||||
|
||||
@@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_pylance", [False, True])
|
||||
def test_blob_uri_array(with_pylance):
|
||||
if with_pylance:
|
||||
pytest.importorskip("lance")
|
||||
# Use fresh processes so each extension class can own Arrow's registry.
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
import importlib.abc
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if sys.argv[1] == "False":
|
||||
class MissingLance(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if fullname == "lance" or fullname.startswith("lance."):
|
||||
raise ModuleNotFoundError(fullname, name="lance")
|
||||
sys.meta_path.insert(0, MissingLance())
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb import BasePath, blob_uri_array
|
||||
from lancedb.schema import blob
|
||||
|
||||
if sys.argv[1] == "True":
|
||||
from lance import DatasetBasePath
|
||||
from lance.blob import BlobType
|
||||
else:
|
||||
from lancedb.schema import _FallbackBlobType as BlobType
|
||||
DatasetBasePath = None
|
||||
|
||||
schema = pa.schema([blob("video")])
|
||||
array = blob_uri_array(
|
||||
["s3://bucket/a.mp4", None, "b.mp4"],
|
||||
positions=[0, None, None],
|
||||
sizes=[4, None, None],
|
||||
)
|
||||
assert isinstance(array, pa.ExtensionArray)
|
||||
assert type(array.type) is BlobType
|
||||
assert array.type == schema.field("video").type
|
||||
assert array.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
|
||||
None,
|
||||
{"data": None, "uri": "b.mp4", "position": None, "size": None},
|
||||
]
|
||||
whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
|
||||
assert whole.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
|
||||
]
|
||||
|
||||
checks = [
|
||||
(lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
|
||||
"both position and size",
|
||||
),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
|
||||
(lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
|
||||
(lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
|
||||
(lambda: blob_uri_array([b"u"]), "must be a string"),
|
||||
]
|
||||
for call, fragment in checks:
|
||||
try:
|
||||
call()
|
||||
except (TypeError, ValueError, OverflowError) as error:
|
||||
assert fragment in str(error), (fragment, error)
|
||||
else:
|
||||
raise AssertionError(f"accepted invalid input: {fragment}")
|
||||
|
||||
try:
|
||||
BasePath("s3://bucket", id=0)
|
||||
except ValueError as error:
|
||||
assert "id=None" in str(error)
|
||||
else:
|
||||
raise AssertionError("accepted explicit id=0")
|
||||
|
||||
# The public create route must accept the helper and register the base
|
||||
# in the same commit as the data, with or without pylance.
|
||||
root = pathlib.Path(tempfile.mkdtemp())
|
||||
base_dir = root / "videos"
|
||||
base_dir.mkdir()
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
db = lancedb.connect(root / "db")
|
||||
field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
table_schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=table_schema
|
||||
)
|
||||
if DatasetBasePath is not None:
|
||||
bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
|
||||
else:
|
||||
bases = [BasePath(path=base_dir.as_uri(), name="source")]
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
assert (
|
||||
table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
)
|
||||
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
|
||||
assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
|
||||
assert table.fetch_blob_ranges(
|
||||
"video", [(row_ids[0].as_py(), 1, 3)]
|
||||
).to_pylist() == [payload[1:4]]
|
||||
if DatasetBasePath is not None:
|
||||
base_paths = table.to_lance().base_paths()
|
||||
assert base_paths[1].path == base_dir.as_uri()
|
||||
assert base_paths[1].is_dataset_root is False
|
||||
if sys.argv[1] == "False":
|
||||
assert "lance" not in sys.modules
|
||||
"""
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script, str(with_pylance)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
@@ -0,0 +1,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 == []
|
||||
@@ -8,12 +8,7 @@ import textwrap
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["sync", "async"])
|
||||
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
|
||||
def test_blob_query_without_pylance(tmp_path, api, result):
|
||||
if result == "pandas":
|
||||
pytest.importorskip("pandas")
|
||||
script = """\
|
||||
_WITHOUT_LANCE = """\
|
||||
import importlib.abc
|
||||
import sys
|
||||
|
||||
@@ -23,7 +18,15 @@ class MissingLance(importlib.abc.MetaPathFinder):
|
||||
raise ModuleNotFoundError(fullname, name="lance")
|
||||
|
||||
sys.meta_path.insert(0, MissingLance())
|
||||
""" + textwrap.dedent(
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["sync", "async"])
|
||||
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
|
||||
def test_blob_query_without_pylance(tmp_path, api, result):
|
||||
if result == "pandas":
|
||||
pytest.importorskip("pandas")
|
||||
script = _WITHOUT_LANCE + textwrap.dedent(
|
||||
"""\
|
||||
import asyncio
|
||||
import lancedb
|
||||
@@ -94,3 +97,187 @@ sys.meta_path.insert(0, MissingLance())
|
||||
text=True,
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["sync", "async"])
|
||||
@pytest.mark.parametrize("result", ["pandas", "batches", "arrow"])
|
||||
def test_plain_legacy_blob_query_without_pylance(tmp_path, api, result):
|
||||
if result == "pandas":
|
||||
pytest.importorskip("pandas")
|
||||
script = _WITHOUT_LANCE + textwrap.dedent(
|
||||
"""\
|
||||
import asyncio
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb.query import ColumnOrdering
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("filename", pa.string()),
|
||||
pa.field(
|
||||
"video_blob",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
]
|
||||
)
|
||||
rows = [
|
||||
{"id": 1, "filename": "file-1.mp4", "video_blob": b"outside"},
|
||||
{"id": 2, "filename": "file-2.mp4", "video_blob": b""},
|
||||
{"id": 3, "filename": "file-3.mp4", "video_blob": None},
|
||||
{"id": 4, "filename": "file-4.mp4", "video_blob": b"four"},
|
||||
]
|
||||
expected = [
|
||||
{"filename": "file-2.mp4", "payload": b""},
|
||||
{"filename": "file-3.mp4", "payload": None},
|
||||
{"filename": "file-4.mp4", "payload": b"four"},
|
||||
]
|
||||
|
||||
def configure(query):
|
||||
return (
|
||||
query.select({"filename": "filename", "payload": "video_blob"})
|
||||
.where("id >= 2")
|
||||
.order_by(
|
||||
[ColumnOrdering(column_name="id", ascending=True)]
|
||||
)
|
||||
.limit(3)
|
||||
)
|
||||
|
||||
async def main():
|
||||
storage_options = {"new_table_data_storage_version": "2.1"}
|
||||
if sys.argv[2] == "async":
|
||||
db = await lancedb.connect_async(
|
||||
sys.argv[1], storage_options=storage_options
|
||||
)
|
||||
table = await db.create_table("legacy", schema=schema)
|
||||
await table.add(rows)
|
||||
table = await db.open_table("legacy")
|
||||
def query():
|
||||
return configure(table.query())
|
||||
def original_query():
|
||||
return table.query().select(
|
||||
{"filename": "filename", "payload": "video_blob"}
|
||||
).limit(1)
|
||||
def empty_query():
|
||||
return query().where("id < 0")
|
||||
def batches():
|
||||
return query().to_batches(
|
||||
max_batch_length=1, blob_mode="bytes"
|
||||
)
|
||||
else:
|
||||
db = lancedb.connect(
|
||||
sys.argv[1], storage_options=storage_options
|
||||
)
|
||||
table = db.create_table("legacy", schema=schema)
|
||||
table.add(rows)
|
||||
table = db.open_table("legacy")
|
||||
def query():
|
||||
return configure(table.search())
|
||||
def original_query():
|
||||
return table.search().select(
|
||||
{"filename": "filename", "payload": "video_blob"}
|
||||
).limit(1)
|
||||
def empty_query():
|
||||
return query().where("id < 0")
|
||||
def batches():
|
||||
return query().to_batches(
|
||||
batch_size=1, blob_mode="bytes"
|
||||
)
|
||||
|
||||
if sys.argv[2] == "async":
|
||||
reused = table.query().select(
|
||||
{"filename": "filename", "payload": "video_blob"}
|
||||
).limit(3)
|
||||
byte_reader = await reused.to_batches(blob_mode="bytes")
|
||||
await byte_reader.read_all()
|
||||
lazy_reader = await reused.to_batches(blob_mode="lazy")
|
||||
assert "_rowid" not in lazy_reader.schema.names
|
||||
await lazy_reader.read_all()
|
||||
reused.select(["filename"])
|
||||
nonblob_reader = await reused.to_batches(blob_mode="lazy")
|
||||
assert nonblob_reader.schema.names == ["filename"]
|
||||
await nonblob_reader.read_all()
|
||||
|
||||
if sys.argv[3] == "pandas":
|
||||
frame = query().to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
frame = await frame
|
||||
assert frame.to_dict("records") == expected
|
||||
original = original_query().to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
original = await original
|
||||
assert original.to_dict("records") == [
|
||||
{"filename": "file-1.mp4", "payload": b"outside"}
|
||||
]
|
||||
direct = table.to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
direct = await direct
|
||||
assert direct.to_dict("records") == rows
|
||||
empty = empty_query().to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
empty = await empty
|
||||
assert empty.to_dict("records") == []
|
||||
elif sys.argv[3] == "batches":
|
||||
reader = batches()
|
||||
if sys.argv[2] == "async":
|
||||
reader = await reader
|
||||
rows_out = [batch async for batch in reader]
|
||||
else:
|
||||
rows_out = list(reader)
|
||||
assert reader.schema.field("payload").type == pa.large_binary()
|
||||
assert "_rowid" not in reader.schema.names
|
||||
assert all(batch.num_rows == 1 for batch in rows_out)
|
||||
assert all(batch.schema == reader.schema for batch in rows_out)
|
||||
actual = [row for batch in rows_out for row in batch.to_pylist()]
|
||||
assert actual == expected
|
||||
original_reader = original_query().to_batches(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
original_reader = await original_reader
|
||||
original_rows = [batch async for batch in original_reader]
|
||||
else:
|
||||
original_rows = list(original_reader)
|
||||
assert [
|
||||
row for batch in original_rows for row in batch.to_pylist()
|
||||
] == [{"filename": "file-1.mp4", "payload": b"outside"}]
|
||||
empty_reader = empty_query().to_batches(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
empty_reader = await empty_reader
|
||||
empty_batches = [batch async for batch in empty_reader]
|
||||
else:
|
||||
empty_batches = list(empty_reader)
|
||||
assert empty_batches == []
|
||||
assert empty_reader.schema.field("payload").type == pa.large_binary()
|
||||
else:
|
||||
table_out = query().to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
table_out = await table_out
|
||||
assert table_out.schema.field("payload").type == pa.large_binary()
|
||||
assert "_rowid" not in table_out.column_names
|
||||
assert table_out.to_pylist() == expected
|
||||
original = original_query().to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
original = await original
|
||||
assert original.to_pylist() == [
|
||||
{"filename": "file-1.mp4", "payload": b"outside"}
|
||||
]
|
||||
direct = table.to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
direct = await direct
|
||||
assert direct.to_pylist() == rows
|
||||
empty_table = empty_query().to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
empty_table = await empty_table
|
||||
assert empty_table.num_rows == 0
|
||||
assert empty_table.schema.field("payload").type == pa.large_binary()
|
||||
assert "lance" not in sys.modules
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
)
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-c", script, str(tmp_path), api, result],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Exercise the public sync/async range APIs over bounded loopback HTTP."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import threading
|
||||
|
||||
import lancedb._lancedb as native
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
from lancedb.remote.errors import HttpError, TableNotFoundError
|
||||
from test_remote_db import mock_lancedb_connection
|
||||
|
||||
MIB = 1024 * 1024
|
||||
IDENTITY = "v1:" + "a" * 64
|
||||
ROUTE = "/v1/table/test/fetch_blob_ranges/"
|
||||
|
||||
|
||||
def payload(row, offset, length, version):
|
||||
pattern = bytes((row * 17 + i + version) % 251 for i in range(251))
|
||||
start = offset % 251
|
||||
return (pattern * ((start + length + 250) // 251))[start : start + length]
|
||||
|
||||
|
||||
class RangeServer:
|
||||
def __init__(self, fault=None):
|
||||
self.fault = fault
|
||||
self.calls = []
|
||||
self.fetches = []
|
||||
self.identities = []
|
||||
self.stalled = threading.Event()
|
||||
self.release = threading.Event()
|
||||
|
||||
def __call__(self, request):
|
||||
request.connection.settimeout(15)
|
||||
size = int(request.headers.get("Content-Length", 0))
|
||||
assert size <= 256 * 1024
|
||||
body = json.loads(request.rfile.read(size) or b"{}")
|
||||
self.calls.append((request.command, request.path, body))
|
||||
if request.path in (
|
||||
"/v1/table/test/describe/",
|
||||
"/v1/table/test/branches/list/",
|
||||
):
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.send_header("phalanx-version", "1.13.0-beta.0")
|
||||
if request.path.endswith("/describe/"):
|
||||
request.send_header("x-lancedb-blob-ranges", "1")
|
||||
request.end_headers()
|
||||
response = (
|
||||
{
|
||||
"branches": {
|
||||
"experiment": {
|
||||
"parentBranch": None,
|
||||
"parentVersion": 1,
|
||||
"createAt": 1,
|
||||
"manifestSize": 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
if request.path.endswith("branches/list/")
|
||||
else {"version": 8, "schema": {"fields": []}}
|
||||
)
|
||||
request.wfile.write(json.dumps(response).encode())
|
||||
return
|
||||
assert (request.command, request.path) == ("POST", ROUTE)
|
||||
self.fetches.append(body)
|
||||
self.identities.append(request.headers.get("x-lancedb-query-snapshot"))
|
||||
assert body["column"] == "image"
|
||||
assert body["branch"] == "experiment"
|
||||
ranges = body["ranges"]
|
||||
assert len(ranges) <= 1024
|
||||
assert sum(r["length"] for r in ranges) <= 64 * MIB
|
||||
version = body["version"] or (7 if len(self.fetches) == 1 else 8)
|
||||
values = [
|
||||
None
|
||||
if r["row_id"] == 20
|
||||
else payload(r["row_id"], r["offset"], r["length"], version)
|
||||
for r in ranges
|
||||
]
|
||||
fault = (
|
||||
self.fault
|
||||
if len(self.fetches) > 1 or str(self.fault).startswith("first-")
|
||||
else None
|
||||
)
|
||||
if fault in ("recreated", "gone"):
|
||||
request.send_response(400 if fault == "recreated" else 404)
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
b"query snapshot identity mismatch: source gone or replaced"
|
||||
)
|
||||
return
|
||||
if fault == "stall" and len(self.fetches) == 2:
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
|
||||
request.send_header("x-lancedb-version", str(version))
|
||||
request.send_header("x-lancedb-query-snapshot", IDENTITY)
|
||||
request.end_headers()
|
||||
request.wfile.flush()
|
||||
self.stalled.set()
|
||||
assert self.release.wait(15), "test did not release stalled response"
|
||||
return
|
||||
if fault == "structured400":
|
||||
request.send_response(400)
|
||||
request.send_header("x-lancedb-error-code", "invalid_input")
|
||||
request.end_headers()
|
||||
request.wfile.write(b'{"error":"range exceeds blob size"}')
|
||||
return
|
||||
if isinstance(fault, int):
|
||||
request.send_response(fault)
|
||||
request.end_headers()
|
||||
request.wfile.write(b"ordinary server failure")
|
||||
return
|
||||
if fault == "disconnect":
|
||||
request.connection.shutdown(socket.SHUT_RDWR)
|
||||
return
|
||||
column = "wrong" if fault == "column" else "value"
|
||||
data_type = pa.binary() if fault == "type" else pa.large_binary()
|
||||
if fault == "count":
|
||||
values = []
|
||||
elif fault == "length":
|
||||
values = [b""]
|
||||
batch = pa.table({column: pa.array(values, type=data_type)})
|
||||
sink = pa.BufferOutputStream()
|
||||
with pa.ipc.new_stream(sink, batch.schema) as writer:
|
||||
writer.write_table(batch, max_chunksize=257)
|
||||
ipc = sink.getvalue().to_pybytes()
|
||||
if fault == "eos":
|
||||
ipc = ipc[:-8]
|
||||
elif fault == "body":
|
||||
ipc = ipc[: len(ipc) // 2]
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
|
||||
if fault != "version":
|
||||
request.send_header("x-lancedb-version", str(version))
|
||||
if fault not in ("missing-identity", "first-missing-identity"):
|
||||
identity = (
|
||||
"broken"
|
||||
if fault == "first-invalid-identity"
|
||||
else "v1:" + "b" * 64
|
||||
if fault == "wrong-identity"
|
||||
else IDENTITY
|
||||
)
|
||||
request.send_header("x-lancedb-query-snapshot", identity)
|
||||
request.send_header(
|
||||
"Content-Length", str(len(ipc) + (10 if fault == "transport" else 0))
|
||||
)
|
||||
request.end_headers()
|
||||
for i in range(0, len(ipc), 8192):
|
||||
request.wfile.write(ipc[i : i + 8192])
|
||||
|
||||
|
||||
async def fetch(table, requests, use_async):
|
||||
result = table.fetch_blob_ranges("image", requests)
|
||||
return await result if use_async else result
|
||||
|
||||
|
||||
def api(db, use_async, version=None):
|
||||
table = db.open_table("test", branch="experiment", version=version)
|
||||
return table._table if use_async else table
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("version", [None, 3])
|
||||
async def test_range_sdk_order_snapshot_and_overwrite(use_async, version):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async, version)
|
||||
requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)]
|
||||
requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)]
|
||||
result = await fetch(table, requests, use_async)
|
||||
assert isinstance(result, pa.LargeBinaryArray)
|
||||
assert result.to_pylist() == [
|
||||
None if row == 20 else payload(row, offset, length, version or 7)
|
||||
for row, offset, length in requests
|
||||
]
|
||||
assert [b["version"] for b in handler.fetches] == [version, version or 7]
|
||||
result = await fetch(table, [(10, 0, 1)], use_async)
|
||||
assert result.to_pylist() == [payload(10, 0, 1, version or 8)]
|
||||
assert handler.fetches[-1]["version"] == version
|
||||
assert len(handler.fetches) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_cached_reopen_negotiates_capability(use_async):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
for version in (7, 8):
|
||||
table = api(db, use_async)
|
||||
result = await fetch(table, [(10, 0, 1)], use_async)
|
||||
assert result.to_pylist() == [payload(10, 0, 1, version)]
|
||||
assert len(handler.fetches) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_large_single_and_aggregate_budget(use_async):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
requests = [
|
||||
(10, 3, 33 * MIB),
|
||||
(30, 7, 33 * MIB),
|
||||
(40, 11, 70 * MIB),
|
||||
(20, 0, 2**64 - 1),
|
||||
]
|
||||
# The loopback server advances latest after the first partition.
|
||||
result = await fetch(table, requests, use_async)
|
||||
assert len(result) == 4
|
||||
for i, (row, offset, length) in enumerate(requests[:3]):
|
||||
expected = payload(row, offset, length, 7)
|
||||
assert (
|
||||
hashlib.sha256(result[i].as_buffer()).digest()
|
||||
== hashlib.sha256(expected).digest()
|
||||
)
|
||||
assert len(result[i].as_buffer()) == length
|
||||
assert result[3].as_py() is None
|
||||
assert len(handler.fetches) == 3
|
||||
assert [b["version"] for b in handler.fetches] == [None, 7, 7]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"fault",
|
||||
[
|
||||
"type",
|
||||
"column",
|
||||
"count",
|
||||
"length",
|
||||
"eos",
|
||||
"body",
|
||||
"transport",
|
||||
"version",
|
||||
"disconnect",
|
||||
401,
|
||||
403,
|
||||
404,
|
||||
429,
|
||||
500,
|
||||
],
|
||||
)
|
||||
async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault):
|
||||
handler = RangeServer(fault=fault)
|
||||
with mock_lancedb_connection(
|
||||
handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2}
|
||||
) as db:
|
||||
table = api(db, use_async)
|
||||
with pytest.raises(Exception) as exc:
|
||||
await fetch(table, [(10, 0, 1)] * 1025, use_async)
|
||||
if fault == 404:
|
||||
assert isinstance(exc.value, TableNotFoundError)
|
||||
assert isinstance(exc.value.__cause__, HttpError)
|
||||
assert exc.value.__cause__.status_code == 404
|
||||
else:
|
||||
assert not isinstance(exc.value, ValueError)
|
||||
if isinstance(fault, int):
|
||||
assert exc.value.status_code == fault
|
||||
assert len(handler.fetches) == 2
|
||||
assert all(
|
||||
path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE)
|
||||
for _, path, _ in handler.calls
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_structured_400_preserves_value_error(use_async):
|
||||
handler = RangeServer(fault="structured400")
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
with pytest.raises(ValueError, match="range exceeds blob size"):
|
||||
await fetch(table, [(10, 0, 1)] * 1025, use_async)
|
||||
assert len(handler.fetches) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_range_sdk_async_cancel_releases_only_request_permit():
|
||||
handler = RangeServer(fault="stall")
|
||||
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
|
||||
table = api(db, True)
|
||||
pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True))
|
||||
try:
|
||||
assert await asyncio.to_thread(handler.stalled.wait, 10)
|
||||
pending.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await pending
|
||||
assert len(handler.fetches) == 2
|
||||
result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5)
|
||||
assert result.to_pylist() == [payload(10, 0, 1, 8)]
|
||||
assert len(handler.fetches) == 3
|
||||
finally:
|
||||
pending.cancel()
|
||||
handler.release.set()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_integer_validation_and_empty_zero_io(use_async):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
before = len(handler.calls)
|
||||
assert (await fetch(table, [], use_async)).to_pylist() == []
|
||||
for request in [
|
||||
(-1, 0, 1),
|
||||
(2**64, 0, 1),
|
||||
(10, -1, 1),
|
||||
(10, 0, -1),
|
||||
(10, 0, 2**64),
|
||||
(10, 0.5, 1),
|
||||
(20, 2**64 - 1, 1),
|
||||
(10, 0),
|
||||
]:
|
||||
with pytest.raises((ValueError, OverflowError, TypeError)):
|
||||
await fetch(table, [request], use_async)
|
||||
assert len(handler.calls) == before
|
||||
|
||||
|
||||
def test_range_sdk_loaded_artifact_identity():
|
||||
artifact = Path(native.__file__).resolve()
|
||||
digest = hashlib.sha256()
|
||||
with artifact.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}")
|
||||
assert artifact.is_file()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"fault", ["missing-identity", "wrong-identity", "recreated", "gone"]
|
||||
)
|
||||
@pytest.mark.parametrize("huge", [False, True])
|
||||
async def test_range_sdk_original_identity_survives_every_partition(
|
||||
use_async, fault, huge
|
||||
):
|
||||
handler = RangeServer(fault=fault)
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025
|
||||
error = (
|
||||
ValueError
|
||||
if fault == "recreated"
|
||||
else TableNotFoundError
|
||||
if fault == "gone"
|
||||
else NotImplementedError
|
||||
)
|
||||
with pytest.raises(
|
||||
error, match="snapshot identity" if fault != "gone" else None
|
||||
):
|
||||
await fetch(table, requests, use_async)
|
||||
assert handler.identities == [None, IDENTITY]
|
||||
assert len(handler.fetches) == 2
|
||||
assert [body["version"] for body in handler.fetches] == [None, 7]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"])
|
||||
async def test_range_sdk_bulk_requires_identity_before_payload_acceptance(
|
||||
use_async, fault
|
||||
):
|
||||
handler = RangeServer(fault=fault)
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
before = len(handler.calls)
|
||||
with pytest.raises(NotImplementedError, match="snapshot identity"):
|
||||
await fetch(table, [(10, 0, 1)] * 1025, use_async)
|
||||
assert len(handler.fetches) == 1
|
||||
assert len(handler.calls) == before + 1
|
||||
@@ -2,7 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import warnings
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
|
||||
endpoint,
|
||||
api_key="secret",
|
||||
sql_host_override="invalid://localhost",
|
||||
storage_options={"azure_storage_account_name": "catalog-account"},
|
||||
client_config={
|
||||
"extra_headers": {
|
||||
"X-LanceDB-Database": "wrong",
|
||||
@@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
|
||||
assert db.table_names() == []
|
||||
restored = lancedb.deserialize_conn(db.serialize())
|
||||
assert restored.sql_host_override == "invalid://localhost"
|
||||
assert restored.storage_options == {"azure_storage_account_name": "catalog-account"}
|
||||
for connection in (db, restored):
|
||||
with pytest.raises(ValueError, match="sql_host_override must use"):
|
||||
connection.execute_query_async("SELECT 1")
|
||||
@@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
|
||||
)
|
||||
assert "x-lancedb-database-prefix" not in headers
|
||||
assert headers["x-api-key"] == "secret"
|
||||
assert headers["x-azure-storage-account-name"] == "catalog-account"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server):
|
||||
]
|
||||
)
|
||||
catalog = await lancedb.connect_catalog_async(
|
||||
endpoint, sql_host_override="invalid://localhost"
|
||||
endpoint,
|
||||
sql_host_override="invalid://localhost",
|
||||
storage_options={"account_name": "async-account"},
|
||||
)
|
||||
assert isinstance(catalog, lancedb.AsyncCatalog)
|
||||
db = await catalog.connect_database("analytics")
|
||||
@@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server):
|
||||
await catalog.drop_database("full")
|
||||
await catalog.drop_database("missing", ignore_missing=True)
|
||||
assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"}
|
||||
for _, headers, _ in requests:
|
||||
headers = {key.lower(): value for key, value in headers.items()}
|
||||
assert headers["x-azure-storage-account-name"] == "async-account"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"])
|
||||
@@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint):
|
||||
lancedb.connect_catalog(endpoint)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"])
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_accepts_database_connection_settings(
|
||||
catalog_server, asynchronous, region
|
||||
):
|
||||
endpoint, requests, responses = catalog_server
|
||||
responses.extend([(200, {"namespaces": []}), (200, {"tables": []})])
|
||||
settings = {
|
||||
"uri": "db://analytics",
|
||||
"api_key": "shared-secret",
|
||||
"region": region,
|
||||
"host_override": endpoint,
|
||||
"sql_host_override": "invalid://localhost",
|
||||
"read_consistency_interval": timedelta(seconds=5),
|
||||
"client_config": {"extra_headers": {"x-shared-setting": "shared"}},
|
||||
"storage_options": {"azure_storage_account_name": "shared-account"},
|
||||
"session": None,
|
||||
"manifest_enabled": False,
|
||||
"namespace_client_properties": None,
|
||||
}
|
||||
if not asynchronous:
|
||||
settings.update(
|
||||
request_thread_pool=None,
|
||||
namespace_client_impl=None,
|
||||
namespace_client_pushdown_operations=None,
|
||||
)
|
||||
with pytest.warns(
|
||||
UserWarning, match="region is ignored by connect_catalog"
|
||||
) as caught:
|
||||
catalog = (
|
||||
await lancedb.connect_catalog_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect_catalog(**settings)
|
||||
)
|
||||
assert len(caught) == 1
|
||||
assert catalog.uri == endpoint
|
||||
assert (
|
||||
[name async for name in catalog.list_databases()]
|
||||
if asynchronous
|
||||
else list(catalog.list_databases())
|
||||
) == []
|
||||
db = (
|
||||
await lancedb.connect_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect(**settings)
|
||||
)
|
||||
assert (await db.table_names() if asynchronous else db.table_names()) == []
|
||||
root_headers = {key.lower(): value for key, value in requests[0][1].items()}
|
||||
db_headers = {key.lower(): value for key, value in requests[1][1].items()}
|
||||
for headers in (root_headers, db_headers):
|
||||
assert headers["x-api-key"] == "shared-secret"
|
||||
assert headers["x-shared-setting"] == "shared"
|
||||
assert headers["x-azure-storage-account-name"] == "shared-account"
|
||||
assert "x-lancedb-database" not in root_headers
|
||||
assert db_headers["x-lancedb-database"] == "analytics"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("host_only", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_default_region_is_silent_and_api_key_uses_environment(
|
||||
catalog_server, monkeypatch, asynchronous, host_only
|
||||
):
|
||||
endpoint, requests, responses = catalog_server
|
||||
monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret")
|
||||
responses.extend([(200, {}), (200, {"tables": []})])
|
||||
settings = {"host_override": endpoint} if host_only else {"uri": endpoint}
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
catalog = (
|
||||
await lancedb.connect_catalog_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect_catalog(**settings)
|
||||
)
|
||||
assert caught == []
|
||||
assert catalog.uri == endpoint
|
||||
db = (
|
||||
await catalog.connect_database("analytics")
|
||||
if asynchronous
|
||||
else catalog.connect_database("analytics")
|
||||
)
|
||||
if not asynchronous:
|
||||
db = lancedb.deserialize_conn(db.serialize())
|
||||
assert (await db.table_names() if asynchronous else db.table_names()) == []
|
||||
for _, headers, _ in requests:
|
||||
headers = {key.lower(): value for key, value in headers.items()}
|
||||
assert headers["x-api-key"] == "environment-secret"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous):
|
||||
endpoint, _, _ = catalog_server
|
||||
settings = {"uri": "https://unused.example", "host_override": endpoint}
|
||||
catalog = (
|
||||
await lancedb.connect_catalog_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect_catalog(**settings)
|
||||
)
|
||||
assert catalog.uri == endpoint
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options, message",
|
||||
[
|
||||
({}, "uri or host_override is required"),
|
||||
({"session": object()}, "session"),
|
||||
({"manifest_enabled": True}, "manifest_enabled"),
|
||||
({"namespace_client_properties": {}}, "namespace_client_properties"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_rejects_unsupported_connection_settings(
|
||||
catalog_server, asynchronous, options, message
|
||||
):
|
||||
_, requests, _ = catalog_server
|
||||
error = NotImplementedError if options else ValueError
|
||||
with pytest.raises(error, match=message):
|
||||
if asynchronous:
|
||||
await lancedb.connect_catalog_async(**options)
|
||||
else:
|
||||
lancedb.connect_catalog(**options)
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options, error, message",
|
||||
[
|
||||
(
|
||||
{"namespace_client_impl": "dir"},
|
||||
NotImplementedError,
|
||||
"namespace_client_impl",
|
||||
),
|
||||
(
|
||||
{"namespace_client_pushdown_operations": []},
|
||||
NotImplementedError,
|
||||
"namespace_client_pushdown_operations",
|
||||
),
|
||||
({"unknown_option": True}, ValueError, "Unknown keyword arguments"),
|
||||
],
|
||||
)
|
||||
def test_catalog_rejects_unsupported_sync_settings(options, error, message):
|
||||
with pytest.raises(error, match=message):
|
||||
lancedb.connect_catalog(**options)
|
||||
|
||||
|
||||
def test_catalog_accepts_deprecated_sync_settings(catalog_server):
|
||||
endpoint, _, responses = catalog_server
|
||||
responses.append((200, {}))
|
||||
with pytest.warns(DeprecationWarning) as caught:
|
||||
catalog = lancedb.connect_catalog(
|
||||
endpoint,
|
||||
request_thread_pool=2,
|
||||
connection_timeout=5,
|
||||
read_timeout=10,
|
||||
)
|
||||
assert len(caught) == 3
|
||||
db = catalog.connect_database("analytics")
|
||||
assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5)
|
||||
assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)])
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous):
|
||||
source_uri = str(tmp_path / "source.lance")
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
await db.create_table("source", [{"id": 1}])
|
||||
table = await db.clone_table("target", source_uri, exist_ok=True)
|
||||
assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
|
||||
await table.add([{"id": 2}])
|
||||
version = await table.version()
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
await db.clone_table("target", source_uri)
|
||||
kept = await db.clone_table("target", "missing.lance", exist_ok=True)
|
||||
assert await kept.version() == version
|
||||
assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}]
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
db.create_table("source", [{"id": 1}])
|
||||
table = db.clone_table("target", source_uri, exist_ok=True)
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1}]
|
||||
table.add([{"id": 2}])
|
||||
version = table.version
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
db.clone_table("target", source_uri)
|
||||
kept = db.clone_table("target", "missing.lance", exist_ok=True)
|
||||
assert kept.version == version
|
||||
assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}]
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import contextlib
|
||||
import inspect
|
||||
import pickle
|
||||
import re
|
||||
import sys
|
||||
from datetime import timedelta
|
||||
@@ -69,6 +70,29 @@ def test_basic(tmp_path):
|
||||
assert db.open_table("test").name == db["test"].name
|
||||
|
||||
|
||||
def test_lance_db_connection_pickle_roundtrip(tmp_path):
|
||||
interval = timedelta(seconds=2)
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=interval)
|
||||
db.create_table("pickle_conn", pa.table({"id": [1, 2]}))
|
||||
|
||||
restored = pickle.loads(pickle.dumps(db))
|
||||
|
||||
assert restored.uri == str(tmp_path)
|
||||
assert restored.read_consistency_interval == interval
|
||||
assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2]
|
||||
|
||||
|
||||
def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table("pickle_zero", pa.table({"id": [1]}))
|
||||
|
||||
restored_db, restored_table = pickle.loads(pickle.dumps((db, table)))
|
||||
lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]}))
|
||||
|
||||
assert restored_db.read_consistency_interval == timedelta(0)
|
||||
assert restored_table.to_arrow()["id"].to_pylist() == [1, 2]
|
||||
|
||||
|
||||
def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch):
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
@@ -282,9 +306,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path):
|
||||
assert empty.page_token is None
|
||||
|
||||
|
||||
def test_db_contains_stops_after_matching_table_page(
|
||||
tmp_db: lancedb.DBConnection, monkeypatch
|
||||
):
|
||||
def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch):
|
||||
calls = []
|
||||
pages = {
|
||||
None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"),
|
||||
@@ -297,18 +319,44 @@ def test_db_contains_stops_after_matching_table_page(
|
||||
|
||||
monkeypatch.setattr(tmp_db, "list_tables", list_tables)
|
||||
|
||||
assert "table_1" in tmp_db
|
||||
assert calls == [None]
|
||||
|
||||
calls.clear()
|
||||
assert "table_2" in tmp_db
|
||||
assert calls == [None, "next"]
|
||||
|
||||
calls.clear()
|
||||
assert len(tmp_db) == 3
|
||||
assert calls == [None, "next"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]])
|
||||
async def test_local_table_exists_without_listing(
|
||||
tmp_path, monkeypatch, namespace_path
|
||||
):
|
||||
db = lancedb.connect(tmp_path)
|
||||
for depth in range(1, len(namespace_path) + 1):
|
||||
db.create_namespace(namespace_path[:depth])
|
||||
db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path)
|
||||
if not namespace_path:
|
||||
for idx in range(100):
|
||||
(tmp_path / f"a{idx:03}.lance").mkdir()
|
||||
assert "events" not in db.list_tables().tables
|
||||
adb = await lancedb.connect_async(tmp_path)
|
||||
|
||||
def fail_listing(*args, **kwargs):
|
||||
raise AssertionError("Existence checks must not list tables")
|
||||
|
||||
monkeypatch.setattr(db, "list_tables", fail_listing)
|
||||
monkeypatch.setattr(adb, "list_tables", fail_listing)
|
||||
table_id = namespace_path + ["events"]
|
||||
assert db.table_exists(table_id) is True
|
||||
assert await adb.table_exists(table_id) is True
|
||||
assert db.table_exists(namespace_path + ["missing"]) is False
|
||||
assert await adb.table_exists(namespace_path + ["missing"]) is False
|
||||
assert ("events" in db) is (not namespace_path)
|
||||
assert "missing" not in db
|
||||
assert table_id == namespace_path + ["events"]
|
||||
|
||||
db.drop_table("events", namespace_path=namespace_path)
|
||||
assert db.table_exists(table_id) is False
|
||||
assert await adb.table_exists(table_id) is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_table_names_async(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
@@ -821,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection):
|
||||
tmp_db.open_table("does_not_exist")
|
||||
|
||||
|
||||
def test_open_table_sync_with_location(tmp_path):
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
db.create_table("test", data=[{"id": 0}])
|
||||
dataset_path = tmp_path / "db" / "test.lance"
|
||||
|
||||
other_db = lancedb.connect(tmp_path / "other")
|
||||
opened = other_db.open_table("test", location=str(dataset_path))
|
||||
assert opened.name == "test"
|
||||
assert opened.count_rows() == 1
|
||||
|
||||
|
||||
def test_open_table_sync_lance_dataset_path_hint(tmp_path):
|
||||
data_dir = tmp_path / "data"
|
||||
lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}])
|
||||
dataset_db = lancedb.connect(data_dir / "embeddings.lance")
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
dataset_db.open_table("embeddings")
|
||||
message = str(exc_info.value)
|
||||
assert "Table 'embeddings' was not found" in message
|
||||
assert "points to a Lance dataset rather than a database directory" in message
|
||||
assert f"parent directory '{data_dir}'" in message
|
||||
assert "open table 'embeddings' instead" in message
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
dataset_db.open_table("missing", location=str(tmp_path / "missing.lance"))
|
||||
assert "points to a Lance dataset" not in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_table(tmp_path):
|
||||
from conftest import pandas_string_type
|
||||
|
||||
@@ -10,12 +10,140 @@ import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb import LanceDBConnection, udf
|
||||
from lancedb import LanceDBConnection, function
|
||||
from lancedb.compaction import CompactionResult
|
||||
from lancedb.index import FTS
|
||||
from lancedb.prewarm import PrewarmDataResult
|
||||
|
||||
# TODO: setup integ test mark and script
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def maintenance_connection_options():
|
||||
uri = os.environ.get("LANCEDB_URI")
|
||||
if not uri:
|
||||
pytest.skip(
|
||||
"Set LANCEDB_URI to a server supporting SQL maintenance job results"
|
||||
)
|
||||
assert uri.startswith("db://")
|
||||
return {
|
||||
"uri": uri,
|
||||
"api_key": os.environ.get("LANCEDB_API_KEY"),
|
||||
"region": os.environ.get("LANCEDB_REGION", "us-east-1"),
|
||||
"host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"),
|
||||
"sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"])
|
||||
async def test_maintenance_job_result_and_reopen_against_server(
|
||||
maintenance_connection_options, asynchronous, operation
|
||||
):
|
||||
"""Exercise real SQL receipts, workers and HTTP job results with matching versions.
|
||||
|
||||
Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint
|
||||
overrides for a writable database. Workers must publish maintenance results;
|
||||
an unsupported server fails the contract rather than silently skipping it.
|
||||
"""
|
||||
if asynchronous:
|
||||
connection = await lancedb.connect_async(**maintenance_connection_options)
|
||||
else:
|
||||
connection = lancedb.connect(**maintenance_connection_options)
|
||||
|
||||
async def call(method, *args, **kwargs):
|
||||
result = method(*args, **kwargs)
|
||||
return await result if asynchronous else result
|
||||
|
||||
name = f"maintenance_{uuid4().hex}"
|
||||
created = False
|
||||
expected = [{"id": i, "payload": i * 10} for i in range(16)]
|
||||
timeout = timedelta(minutes=5)
|
||||
try:
|
||||
table = await call(
|
||||
connection.create_table, name, pa.Table.from_pylist(expected[:4])
|
||||
)
|
||||
created = True
|
||||
for start in (4, 8, 12):
|
||||
await call(table.add, pa.Table.from_pylist(expected[start : start + 4]))
|
||||
version = await table.version() if asynchronous else table.version
|
||||
if operation == "compact":
|
||||
job = await call(
|
||||
table.compact_async,
|
||||
compaction_options={
|
||||
"target_rows_per_fragment": 100,
|
||||
"batch_size": 128,
|
||||
"io_buffer_size": 0,
|
||||
},
|
||||
)
|
||||
elif operation == "prewarm_legacy":
|
||||
assert (
|
||||
await call(
|
||||
table.prewarm_data,
|
||||
["payload"],
|
||||
filter="id >= 8",
|
||||
concurrency=2,
|
||||
)
|
||||
is None
|
||||
)
|
||||
reader = await call(
|
||||
connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"'
|
||||
)
|
||||
batches = await call(reader.read_all)
|
||||
jobs = pa.Table.from_batches(batches) if asynchronous else batches
|
||||
ids = [
|
||||
row["job_id"]
|
||||
for row in jobs.to_pylist()
|
||||
if row["job_type"] == "prewarm_page_cache"
|
||||
]
|
||||
assert len(ids) == 1, jobs.to_pylist()
|
||||
job = await call(connection.open_job, ids[0])
|
||||
else:
|
||||
job = await call(
|
||||
table.prewarm_data_async,
|
||||
["payload"],
|
||||
filter="id >= 8",
|
||||
concurrency=2,
|
||||
)
|
||||
assert job.id
|
||||
progress = []
|
||||
result = await call(job.wait, timeout=timeout, progress=progress.append)
|
||||
assert any(snapshot["state"] == "finished" for snapshot in progress)
|
||||
await call(job.refresh)
|
||||
assert await call(job.status) == "finished"
|
||||
if operation == "compact":
|
||||
assert isinstance(result, CompactionResult)
|
||||
assert job.job_type == "compact"
|
||||
assert not result.partial_commit and result.rows_failed == 0
|
||||
assert result.completion_percentage == 100
|
||||
assert 0 <= result.rows_succeeded <= len(expected)
|
||||
assert result.files_added is not None and result.files_removed is not None
|
||||
else:
|
||||
assert isinstance(result, PrewarmDataResult)
|
||||
assert job.job_type == "prewarm_page_cache"
|
||||
assert result.table_version == version == job.spec["table_version"]
|
||||
assert job.spec["columns"] == ["payload"]
|
||||
assert job.spec["concurrency"] == 2
|
||||
assert result.fragments_selected > 0
|
||||
assert result.executors_completed == result.executors_targeted
|
||||
assert result.executors_partial == 0
|
||||
assert result.bytes_read is None and result.ranges_completed is None
|
||||
reopened = await call(connection.open_job, job.id)
|
||||
assert await call(reopened.wait, timeout=timeout) == result
|
||||
query = table.query() if asynchronous else table.search()
|
||||
actual = await call(
|
||||
query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow
|
||||
)
|
||||
assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected
|
||||
finally:
|
||||
try:
|
||||
if created:
|
||||
await call(connection.drop_table, name)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server"
|
||||
)
|
||||
@@ -98,7 +226,7 @@ def test_function_execution_controls_through_sql_and_materialized_view():
|
||||
view_name = f"batch_probe_view_{suffix}"
|
||||
registered_version = None
|
||||
|
||||
@udf(
|
||||
@function(
|
||||
name=function_name,
|
||||
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
output_schema=pa.int64(),
|
||||
@@ -180,3 +308,65 @@ def test_against_local_server():
|
||||
table = conn.open_table("sift1m_ivf1024_pq16")
|
||||
df = table.search(np.random.rand(128)).to_pandas()
|
||||
assert len(df) == 10
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_prewarm_preview_against_server(
|
||||
maintenance_connection_options, asynchronous
|
||||
):
|
||||
"""Preview is typed, source-versioned, and creates no maintenance jobs."""
|
||||
from lancedb.prewarm import PrewarmDataPlan
|
||||
|
||||
connection = (
|
||||
await lancedb.connect_async(**maintenance_connection_options)
|
||||
if asynchronous
|
||||
else lancedb.connect(**maintenance_connection_options)
|
||||
)
|
||||
|
||||
async def call(method, *args, **kwargs):
|
||||
result = method(*args, **kwargs)
|
||||
return await result if asynchronous else result
|
||||
|
||||
async def jobs():
|
||||
reader = await call(connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"')
|
||||
result = await call(reader.read_all)
|
||||
if asynchronous:
|
||||
return [row for batch in result for row in batch.to_pylist()]
|
||||
return result.to_pylist()
|
||||
|
||||
name = f"preview_{uuid4().hex}"
|
||||
created = False
|
||||
try:
|
||||
table = await call(connection.create_table, name, [{"id": 1, "payload": "one"}])
|
||||
created = True
|
||||
version = await table.version() if asynchronous else table.version
|
||||
before = await jobs()
|
||||
for predicate, mode, selected in [
|
||||
(None, "unfiltered", 1),
|
||||
("TRUE", "full_warm_fallback", 1),
|
||||
("FALSE", "constant", 0),
|
||||
("id > 10", "full_warm_fallback", 1),
|
||||
]:
|
||||
preview = await call(
|
||||
table.explain_prewarm_data, ["payload"], filter=predicate, concurrency=2
|
||||
)
|
||||
assert isinstance(preview, PrewarmDataPlan)
|
||||
assert preview.table_version == version
|
||||
assert preview.pruning.mode == mode
|
||||
assert preview.pruning.input_fragments == 1
|
||||
assert preview.pruning.selected_fragments == selected
|
||||
if mode == "full_warm_fallback":
|
||||
assert preview.pruning.fallback_reason
|
||||
assert await jobs() == before
|
||||
assert (await table.version() if asynchronous else table.version) == version
|
||||
# A preview does not reserve the source snapshot for a later request.
|
||||
await call(table.add, [{"id": 2, "payload": "two"}])
|
||||
newer = await call(table.explain_prewarm_data)
|
||||
assert newer.table_version > version
|
||||
assert newer.pruning.input_fragments == 2
|
||||
assert await jobs() == before
|
||||
finally:
|
||||
if created:
|
||||
await call(connection.drop_table, name)
|
||||
connection.close()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_to_reader_collects_without_default_slicing(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
rows = 5000
|
||||
data = pa.table(
|
||||
{
|
||||
"id": pa.array(range(rows), type=pa.int64()),
|
||||
"text": pa.array([f"row-{i}" for i in range(rows)]),
|
||||
}
|
||||
)
|
||||
table = await db.create_table("test", data)
|
||||
|
||||
reader = await table._inner.query().execute_to_reader(None, None)
|
||||
batches = list(reader)
|
||||
|
||||
assert sum(batch.num_rows for batch in batches) == rows
|
||||
assert max(batch.num_rows for batch in batches) > 1024
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_to_reader_preserves_empty_schema(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
data = pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2], type=pa.int64()),
|
||||
"text": pa.array(["a", "b"]),
|
||||
}
|
||||
)
|
||||
table = await db.create_table("test", data)
|
||||
|
||||
query = table._inner.query()
|
||||
query.where("id < 0")
|
||||
reader = await query.execute_to_reader(None, None)
|
||||
result = pa.Table.from_batches(reader, schema=reader.schema)
|
||||
|
||||
assert result.num_rows == 0
|
||||
assert result.schema == await table.query().where("id < 0").output_schema()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_to_reader_propagates_timeout(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", data=[{"id": 1}, {"id": 2}])
|
||||
|
||||
with pytest.raises(Exception, match="Query timeout"):
|
||||
await table._inner.query().execute_to_reader(None, timedelta(0))
|
||||
@@ -32,6 +32,7 @@ Parameters used throughout:
|
||||
|
||||
import dataclasses
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import threading
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -1028,6 +1029,105 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table):
|
||||
)
|
||||
|
||||
|
||||
# ── Worker start method defaults ─────────────────────────────────────────────
|
||||
|
||||
|
||||
def _loader_start_method(loader: StreamingDataLoader) -> str:
|
||||
context = loader.multiprocessing_context
|
||||
if isinstance(context, str):
|
||||
return context
|
||||
assert context is not None
|
||||
return context.get_start_method()
|
||||
|
||||
|
||||
def _platform_worker_start_method() -> str:
|
||||
return "forkserver" if "forkserver" in mp.get_all_start_methods() else "spawn"
|
||||
|
||||
|
||||
def test_default_worker_start_method_prefers_forkserver():
|
||||
with patch.object(
|
||||
streaming,
|
||||
"get_all_start_methods",
|
||||
return_value=["fork", "spawn", "forkserver"],
|
||||
):
|
||||
assert streaming._default_worker_start_method() == "forkserver"
|
||||
|
||||
|
||||
def test_streaming_dataloader_falls_back_to_spawn_without_forkserver(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
with patch.object(streaming, "get_all_start_methods", return_value=["spawn"]):
|
||||
loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1)
|
||||
|
||||
assert _loader_start_method(loader) == "spawn"
|
||||
|
||||
|
||||
def test_streaming_dataloader_omitted_context_uses_platform_method(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1)
|
||||
|
||||
assert _loader_start_method(loader) == _platform_worker_start_method()
|
||||
|
||||
|
||||
def test_streaming_dataloader_treats_none_context_as_omitted(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
loader = StreamingDataLoader(
|
||||
dataset,
|
||||
batch_size=2,
|
||||
num_workers=1,
|
||||
multiprocessing_context=None,
|
||||
)
|
||||
|
||||
assert _loader_start_method(loader) == _platform_worker_start_method()
|
||||
|
||||
|
||||
def test_streaming_dataloader_preserves_explicit_start_method(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
loader = StreamingDataLoader(
|
||||
dataset,
|
||||
batch_size=2,
|
||||
num_workers=1,
|
||||
multiprocessing_context="spawn",
|
||||
)
|
||||
|
||||
assert _loader_start_method(loader) == "spawn"
|
||||
|
||||
|
||||
def test_streaming_dataloader_preserves_explicit_context_object(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
context = mp.get_context("spawn")
|
||||
loader = StreamingDataLoader(
|
||||
dataset,
|
||||
batch_size=2,
|
||||
num_workers=1,
|
||||
multiprocessing_context=context,
|
||||
)
|
||||
|
||||
assert loader.multiprocessing_context is context
|
||||
|
||||
|
||||
def test_streaming_dataloader_zero_workers_leave_context_unset(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
loader = StreamingDataLoader(dataset, batch_size=12, num_workers=0)
|
||||
|
||||
assert loader.multiprocessing_context is None
|
||||
ids = [row_id for batch in loader for row_id in batch["id"].tolist()]
|
||||
assert sorted(ids) == list(range(NUM_ROWS))
|
||||
|
||||
|
||||
def test_streaming_dataloader_default_context_runs_real_worker(lance_table):
|
||||
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
loader = StreamingDataLoader(dataset, batch_size=12, num_workers=1)
|
||||
assert _loader_start_method(loader) == _platform_worker_start_method()
|
||||
|
||||
iterator = iter(loader)
|
||||
try:
|
||||
ids = [row_id for batch in iterator for row_id in batch["id"].tolist()]
|
||||
finally:
|
||||
iterator._shutdown_workers()
|
||||
|
||||
assert sorted(ids) == list(range(NUM_ROWS))
|
||||
|
||||
|
||||
# ── Resumability with num_workers ─────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -10,10 +10,12 @@ from lance_namespace.errors import TableNotFoundError as NamespaceTableNotFoundE
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.remote.errors import (
|
||||
AlreadyExistsError,
|
||||
ConflictError,
|
||||
FunctionNotFoundError,
|
||||
HttpError,
|
||||
LanceDBClientError,
|
||||
NamespaceNotFoundError,
|
||||
ResponseInterruptedError,
|
||||
RetryError,
|
||||
SecretNotFoundError,
|
||||
TableNotFoundError,
|
||||
@@ -72,6 +74,31 @@ def test_pickle_http_transport_error():
|
||||
assert restored.request_id == "req-789"
|
||||
|
||||
|
||||
def test_pickle_response_interrupted_error():
|
||||
err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True)
|
||||
restored = pickle.loads(pickle.dumps(err))
|
||||
assert type(restored) is ResponseInterruptedError
|
||||
assert str(restored) == "interrupted"
|
||||
assert restored.request_id == "req-1"
|
||||
assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7)
|
||||
assert restored.is_transport_error is True
|
||||
assert restored.status_code is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"])
|
||||
def test_http_conflict_error_preserves_reason_and_metadata(error_code):
|
||||
reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"
|
||||
original = HttpError(reason, "req-conflict", 409, error_code)
|
||||
for error in [original, pickle.loads(pickle.dumps(original))]:
|
||||
assert type(error) is ConflictError
|
||||
assert isinstance(error, HttpError)
|
||||
assert str(error) == reason
|
||||
assert error.request_id == "req-conflict"
|
||||
assert error.status_code == 409
|
||||
assert error.error_code == error_code
|
||||
assert error.is_transport_error is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error_code,resource_kind,status_code,expected_type",
|
||||
[
|
||||
@@ -251,6 +278,9 @@ def test_sql_errors_use_only_server_codes(code, category, type_name):
|
||||
(400, "schema_mismatch", "SchemaMismatchError"),
|
||||
(404, "table_not_found", "TableNotFoundError"),
|
||||
(404, "reference_not_found", "ReferenceNotFoundError"),
|
||||
(409, None, "ConflictError"),
|
||||
(409, "conflict", "ConflictError"),
|
||||
(500, "conflict", "HttpError"),
|
||||
(500, "column_not_found", "HttpError"),
|
||||
(503, "table_not_found", "HttpError"),
|
||||
],
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from collections import UserDict
|
||||
from pathlib import Path
|
||||
from types import MappingProxyType
|
||||
|
||||
import pytest
|
||||
|
||||
from lancedb import col
|
||||
from lancedb import col, lit
|
||||
import lancedb.functions as functions
|
||||
from lancedb.functions import (
|
||||
FunctionApplication,
|
||||
FunctionBinding,
|
||||
FunctionImage,
|
||||
FunctionVersion,
|
||||
PythonRuntimeSpec,
|
||||
SecretBinding,
|
||||
@@ -34,7 +36,7 @@ FIXTURES = (
|
||||
|
||||
|
||||
def fixture(name: str) -> str:
|
||||
return (FIXTURES / name).read_text()
|
||||
return (FIXTURES / name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def job_result(name: str) -> dict:
|
||||
@@ -58,6 +60,7 @@ def assert_no_secret_values(value):
|
||||
|
||||
|
||||
def test_public_function_values_are_in_api_reference():
|
||||
assert "LiteralInputBinding" in functions.__all__
|
||||
docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md"
|
||||
rendered = docs.read_text()
|
||||
for name in functions.__all__:
|
||||
@@ -148,6 +151,91 @@ def test_function_version_identity_is_immutable_and_exact():
|
||||
FunctionVersion(**{**value, "version": invalid})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gpu", [False, True])
|
||||
def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
|
||||
value = job_result("remote_function_job.json")["image"]
|
||||
value["descriptor"]["future_metadata"] = "x" * 100_000
|
||||
if gpu:
|
||||
value["descriptor"]["requires"]["capabilities"] = [
|
||||
{
|
||||
"type": "lance.cuda",
|
||||
"version": 1,
|
||||
"device_count": 1,
|
||||
"cuda_toolkit": "12.4",
|
||||
}
|
||||
]
|
||||
image = FunctionImage(**value)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", DeprecationWarning)
|
||||
details = image.describe()
|
||||
rendered = repr(image)
|
||||
assert "manifest_digest=" in str(image)
|
||||
encoded = json.loads(image.to_canonical_json())
|
||||
assert details == {
|
||||
"manifest_digest": value["manifest_digest"],
|
||||
"python_version": "3.12.14",
|
||||
"requires_gpu": gpu,
|
||||
"cuda_toolkit": "12.4" if gpu else None,
|
||||
"platforms": None,
|
||||
"base_image": None,
|
||||
"size_bytes": None,
|
||||
}
|
||||
assert len(rendered) < 350
|
||||
assert f"requires_gpu={gpu}" in rendered
|
||||
assert "future_metadata" not in rendered
|
||||
assert encoded == value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"descriptor",
|
||||
[
|
||||
{},
|
||||
{"format_version": 2, "requires": {"capabilities": []}},
|
||||
{"format_version": 1, "requires": {"capabilities": [None]}},
|
||||
{"python": {"version": {"future": "x" * 100_000}}},
|
||||
],
|
||||
)
|
||||
def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
|
||||
image = FunctionImage(
|
||||
manifest_digest="sha256:example", descriptor=descriptor, source=True
|
||||
)
|
||||
assert image.describe()["requires_gpu"] is None
|
||||
assert image.describe()["python_version"] is None
|
||||
assert len(repr(image)) < 350
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
|
||||
)
|
||||
def test_runtime_digests_match_server_golden_values(case):
|
||||
runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"]))
|
||||
assert runtime.digest == case["digest"]
|
||||
assert (
|
||||
PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest
|
||||
== runtime.digest
|
||||
)
|
||||
|
||||
|
||||
def test_unknown_runtime_digest_fails_closed():
|
||||
runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}')
|
||||
with pytest.raises(ValueError, match="cannot digest unknown runtime kind"):
|
||||
runtime.digest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"])
|
||||
def test_function_version_preserves_runtime_digest(runtime_digest):
|
||||
value = job_result("remote_function_job.json")
|
||||
legacy = FunctionVersion.from_json(json.dumps(value))
|
||||
assert legacy.runtime_digest is None
|
||||
assert "runtime_digest" not in json.loads(legacy.to_canonical_json())
|
||||
value["runtime_digest"] = runtime_digest
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
assert version.runtime_digest == runtime_digest
|
||||
assert FunctionVersion.from_json(version.to_canonical_json()) == version
|
||||
with pytest.raises((TypeError, ValueError)):
|
||||
version.runtime_digest = "sha256:changed"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"])
|
||||
def test_function_version_preserves_source_digest(source_digest):
|
||||
value = job_result("remote_function_job.json")
|
||||
@@ -180,6 +268,28 @@ def test_function_version_exposes_registered_gpu_class():
|
||||
assert json.loads(version.to_canonical_json())["gpu_class"] == "a10g"
|
||||
|
||||
|
||||
def test_function_version_preserves_execution_controls():
|
||||
value = job_result("remote_function_job.json")
|
||||
value.update(
|
||||
batch_size=12,
|
||||
max_concurrency=4,
|
||||
row_timeout_seconds=8.0,
|
||||
result_stability="input_and_context",
|
||||
)
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
encoded = json.loads(version.to_canonical_json())
|
||||
|
||||
assert encoded == value
|
||||
assert type(encoded["batch_size"]) is int
|
||||
assert type(encoded["max_concurrency"]) is int
|
||||
assert type(encoded["row_timeout_seconds"]) is float
|
||||
assert type(encoded["result_stability"]) is str
|
||||
|
||||
for invalid in [True, 1.5, 0, -1, 2**32]:
|
||||
with pytest.raises(ValueError, match="max_concurrency"):
|
||||
FunctionVersion(**{**value, "max_concurrency": invalid})
|
||||
|
||||
|
||||
def test_function_version_binds_named_columns_as_one_immutable_application():
|
||||
version = FunctionVersion.from_json(
|
||||
json.dumps(job_result("remote_function_job.json"))
|
||||
@@ -232,6 +342,67 @@ def test_function_version_binding_validates_names_and_direct_columns():
|
||||
version(text=col("text").lower())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1])
|
||||
def test_function_version_binds_direct_literals_without_changing_identity(constant):
|
||||
value = job_result("remote_function_job.json")
|
||||
value["signature"]["inputs"].append(
|
||||
{
|
||||
"name": "option",
|
||||
"arrow_type": "bool"
|
||||
if type(constant) is bool
|
||||
else "utf8"
|
||||
if isinstance(constant, str)
|
||||
else "uint64"
|
||||
if constant == 2**64 - 1
|
||||
else "int64",
|
||||
"nullable": True,
|
||||
}
|
||||
)
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
expression = lit(constant)
|
||||
application = version(text=col("body"), option=expression)
|
||||
encoded = json.loads(application.to_canonical_json())
|
||||
assert encoded["inputs"] == [
|
||||
{"parameter": "text", "kind": "column", "value": {"path": "body"}},
|
||||
{"parameter": "option", "kind": "literal", "value": constant},
|
||||
]
|
||||
assert application.function.version == version.version
|
||||
assert application.function.object_id == version.object_id
|
||||
assert application.function.manifest_digest == version.image.manifest_digest
|
||||
assert FunctionApplication.from_json(application.to_canonical_json()) == application
|
||||
if constant is None:
|
||||
assert expression.to_sql() == "NULL"
|
||||
if type(constant) is int:
|
||||
assert expression.to_sql() == str(constant)
|
||||
|
||||
|
||||
def test_function_literals_reject_expressions_and_unsupported_values():
|
||||
version = FunctionVersion.from_json(
|
||||
json.dumps(job_result("remote_function_job.json"))
|
||||
)
|
||||
with pytest.raises(TypeError, match="direct col"):
|
||||
version(text=lit(16) + lit(8))
|
||||
with pytest.raises(ValueError, match="floating-point Function literals"):
|
||||
version(text=lit(1.5))
|
||||
with pytest.raises(TypeError, match="unsupported Function literal type"):
|
||||
version(text=lit(b"data"))
|
||||
|
||||
|
||||
def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters():
|
||||
value = json.loads((FIXTURES / "remote_function_binding.json").read_text())
|
||||
value["inputs"] = value["inputs"][:1]
|
||||
value["literal_inputs"] = [{"parameter": "body", "value": None}]
|
||||
binding = FunctionBinding.from_json(json.dumps(value))
|
||||
assert binding.literal_inputs[0].value is None
|
||||
assert json.loads(binding.to_canonical_json())["literal_inputs"] == [
|
||||
{"parameter": "body", "value": None}
|
||||
]
|
||||
assert FunctionBinding.from_json(binding.to_canonical_json()) == binding
|
||||
value["literal_inputs"][0]["parameter"] = "title"
|
||||
with pytest.raises(ValueError, match="input parameters must be unique"):
|
||||
FunctionBinding.from_json(json.dumps(value))
|
||||
|
||||
|
||||
def test_function_version_keeps_named_struct_outputs_in_one_application():
|
||||
value = job_result("remote_function_job.json")
|
||||
value["name"] = "text_features"
|
||||
@@ -285,10 +456,15 @@ def test_unknown_fields_and_discriminators_are_forward_decodable():
|
||||
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
assert version.image.descriptor["future_interface"] == {"kind": "wasm"}
|
||||
assert json.loads(version.to_canonical_json())["image"]["descriptor"][
|
||||
"future_interface"
|
||||
] == {"kind": "wasm"}
|
||||
assert version.signature.output.kind == "future_output_shape"
|
||||
assert not hasattr(version, "future_version_metadata")
|
||||
|
||||
canonical = json.loads(version.to_canonical_json())
|
||||
expected = json.loads(fixture("remote_function_version.canonical.json"))
|
||||
expected["image"]["descriptor"]["future_interface"] = {"kind": "wasm"}
|
||||
expected["signature"]["output"]["kind"] = "future_output_shape"
|
||||
assert canonical == expected
|
||||
assert "future_version_metadata" not in canonical
|
||||
|
||||
|
||||
def test_function_application_uses_rename_columns_only():
|
||||
@@ -438,6 +614,7 @@ class _FunctionDeclarationInner:
|
||||
output_name,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
auto_refresh_resource_budget,
|
||||
):
|
||||
self.calls.append(
|
||||
(
|
||||
@@ -445,6 +622,7 @@ class _FunctionDeclarationInner:
|
||||
output_name,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
auto_refresh_resource_budget,
|
||||
)
|
||||
)
|
||||
return "declared"
|
||||
@@ -470,7 +648,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
)
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] == "features"
|
||||
assert inner.calls[-1][2:] == (None, None)
|
||||
assert inner.calls[-1][2:] == (None, None, None)
|
||||
|
||||
bare = application._copy(update={"columns": {}}).rename(
|
||||
columns={"normalized_text": "search_text"}
|
||||
@@ -481,7 +659,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] is None
|
||||
assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"}
|
||||
assert inner.calls[-1][2:] == (False, 300)
|
||||
assert inner.calls[-1][2:] == (False, 300, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+176
-14
@@ -29,6 +29,7 @@ from lancedb.query import (
|
||||
CombinedFieldsQuery,
|
||||
DocumentGranularity,
|
||||
FullTextOperator,
|
||||
FullTextSearchQuery,
|
||||
MatchQuery,
|
||||
MultiMatchQuery,
|
||||
PhraseQuery,
|
||||
@@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
|
||||
|
||||
def test_search_fts_phrase_query(table):
|
||||
table.create_fts_index("text", with_position=False)
|
||||
try:
|
||||
phrase_results = table.search('"puppy runs"').limit(100).to_list()
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
table.search('"puppy runs"').limit(100).to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
table.create_fts_index("text", with_position=True, replace=True)
|
||||
results = table.search("puppy").limit(100).to_list()
|
||||
|
||||
@@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_fts_phrase_query_async(async_table):
|
||||
await async_table.create_index("text", config=FTS(with_position=False))
|
||||
try:
|
||||
phrase_results = (
|
||||
await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
|
||||
)
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
await async_table.query().nearest_to_text('"puppy runs"').to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
await async_table.create_index("text", config=FTS(with_position=True))
|
||||
results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
|
||||
phrase_results = (
|
||||
@@ -1660,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object():
|
||||
def test_fts_phrase_query_execution_preserves_user_text():
|
||||
table = mock.Mock()
|
||||
table.schema = pa.schema([])
|
||||
table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader()
|
||||
# to_arrow() collects through the eager path; keep a real Table so the
|
||||
# reranker still receives and returns the real result contract.
|
||||
table._execute_arrow.return_value = pa.table({"text": ["result"]})
|
||||
|
||||
class CapturingReranker:
|
||||
score = "relevance"
|
||||
@@ -1682,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text():
|
||||
|
||||
query.to_arrow()
|
||||
|
||||
backend_query = table._execute_query.call_args.args[0]
|
||||
backend_query = table._execute_arrow.call_args.args[0]
|
||||
assert (
|
||||
backend_query.full_text_query.query,
|
||||
reranker.queries,
|
||||
@@ -1948,3 +1945,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
|
||||
|
||||
rows = await table.query().nearest_to_text("http").to_list()
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
|
||||
db = ldb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
table.create_index("text", config=FTS())
|
||||
kwargs = {"fts_columns": "text"}
|
||||
if operator is not None:
|
||||
kwargs["operator"] = operator
|
||||
query = table.search("gripper closed", query_type="fts", **kwargs)
|
||||
assert query.count_rows() == expected
|
||||
assert len(query.limit(100).to_list()) == expected
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", fts_columns="text")
|
||||
.operator("AND")
|
||||
.count_rows()
|
||||
== 15
|
||||
)
|
||||
if operator is not None:
|
||||
assert query.to_query_object().full_text_query.operator == operator
|
||||
query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
assert len(query.to_list()) <= 2
|
||||
assert (
|
||||
table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
|
||||
)
|
||||
assert (
|
||||
table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
|
||||
== 15
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
async def test_simple_fts_operator_and_count_async(
|
||||
tmp_path, indexed, operator, expected
|
||||
):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
await table.create_index("text", config=FTS())
|
||||
query = await table.search(
|
||||
"gripper closed", query_type="fts", fts_columns="text", operator=operator
|
||||
)
|
||||
assert await query.count_rows() == expected
|
||||
assert len(await query.limit(100).to_list()) == expected
|
||||
query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert await query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
direct = table.query().nearest_to_text(
|
||||
"gripper closed", columns="text", operator="AND"
|
||||
)
|
||||
assert await direct.count_rows() == 15
|
||||
assert direct.to_query_object().full_text_query.query.operator == "AND"
|
||||
assert (
|
||||
await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
def test_fts_phrase_count_positions(tmp_path, with_position, query):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.search(query, query_type="fts")
|
||||
if with_position:
|
||||
assert search.count_rows() == 1
|
||||
assert len(search.to_list()) == 1
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", operator="AND")
|
||||
.phrase_query()
|
||||
.count_rows()
|
||||
== 1
|
||||
)
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
await table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.query().nearest_to_text(query)
|
||||
if with_position:
|
||||
assert await search.count_rows() == 1
|
||||
assert len(await search.to_list()) == 1
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
await search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
def test_fts_operator_rejects_invalid_queries(table):
|
||||
with pytest.raises(ValueError):
|
||||
table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError, match="operator requires a string full-text query"):
|
||||
FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_operator_rejects_invalid_queries_async(async_table):
|
||||
with pytest.raises(ValueError):
|
||||
await async_table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
await async_table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError):
|
||||
async_table.query().nearest_to_text(query, operator="AND")
|
||||
|
||||
|
||||
def test_fts_count_fast_search(tmp_path):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"matches", pa.table({"text": ["gripper closed"] * 15})
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper closed"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").count_rows() == 20
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb.functions import function
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"])
|
||||
@pytest.mark.parametrize("exist_ok", [None, False, True])
|
||||
async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
fixture = (
|
||||
Path(__file__).parents[3]
|
||||
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
|
||||
/ "remote_function_version.canonical.json"
|
||||
)
|
||||
stored = json.loads(fixture.read_text())
|
||||
result = pa.table({"definition": [json.dumps(stored)]})
|
||||
|
||||
@function(name=stored["name"])
|
||||
def replacement(value: float) -> float:
|
||||
return value * 2
|
||||
|
||||
class FunctionServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with FunctionServer() as server:
|
||||
options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
|
||||
kwargs["namespace_path"] = ["team"]
|
||||
if entry == "async_job":
|
||||
db = await lancedb.connect_async("db://analytics", **options)
|
||||
job = await db.create_function_async(replacement, **kwargs)
|
||||
version = await job.wait()
|
||||
else:
|
||||
db = lancedb.connect("db://analytics", **options)
|
||||
if entry == "sync_job":
|
||||
version = db.create_function_async(replacement, **kwargs).wait()
|
||||
else:
|
||||
version = db.create_function(replacement, **kwargs)
|
||||
(request,) = server.requests
|
||||
|
||||
prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION"
|
||||
assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
|
||||
assert b'"exist_ok"' not in request
|
||||
assert json.loads(version.to_canonical_json()) == stored
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import pytest
|
||||
|
||||
from lancedb import function, udf
|
||||
from lancedb.functions import FunctionDefinition
|
||||
|
||||
|
||||
def identity(value: int) -> int:
|
||||
return value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"torch>=2.0,,<3",
|
||||
"torch>=",
|
||||
"torch=>2.0",
|
||||
"torch[",
|
||||
"torch; python_version >=",
|
||||
"",
|
||||
" torch",
|
||||
"torch ",
|
||||
],
|
||||
)
|
||||
def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch):
|
||||
def unexpected_packaging(*args, **kwargs):
|
||||
pytest.fail("invalid requirements must fail before packaging the function")
|
||||
|
||||
monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging)
|
||||
with pytest.raises(ValueError) as error:
|
||||
function(pip=["numpy", package])(identity)
|
||||
assert "pip[1]" in str(error.value)
|
||||
assert repr(package) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"numpy>=1,,<3",
|
||||
"numpy>=",
|
||||
"numpy[version=]",
|
||||
"numpy[unknown_field=value]",
|
||||
"",
|
||||
" numpy",
|
||||
"numpy ",
|
||||
],
|
||||
)
|
||||
def test_invalid_conda_requirement_names_entry(package):
|
||||
with pytest.raises(ValueError) as error:
|
||||
function(conda=["scipy", package])(identity)
|
||||
assert "conda[1]" in str(error.value)
|
||||
assert repr(package) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["pip", "conda"])
|
||||
@pytest.mark.parametrize("package", [None, 42, ["numpy"]])
|
||||
def test_requirement_must_be_a_string(kind, package):
|
||||
with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"):
|
||||
function(**{kind: ["numpy", package]})(identity)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"numpy",
|
||||
"torch>=2.0,<3",
|
||||
'requests[security,socks]>=2; python_version >= "3.10"',
|
||||
"numpy (>=1.26, <3)",
|
||||
"six @ https://example.com/six-1.16.0.tar.gz",
|
||||
"six @ git+https://github.com/benjaminp/six.git@main",
|
||||
"https://example.com/six-1.16.0.tar.gz",
|
||||
"git+https://github.com/benjaminp/six.git@main",
|
||||
"git+ssh://git@github.com/benjaminp/six.git@main",
|
||||
],
|
||||
)
|
||||
def test_supported_pip_requirements_are_preserved(package):
|
||||
definition = function(pip=[package])(identity)
|
||||
assert definition.registration_request.runtime.environment.packages == (package,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"numpy",
|
||||
"numpy=1.26",
|
||||
"numpy>=1.26,<3",
|
||||
"numpy=1.26=py310_0",
|
||||
"numpy 1.26 py310_0",
|
||||
"conda-forge::numpy>=1.26",
|
||||
"conda-forge/linux-64::numpy>=1.26",
|
||||
"numpy[version='>=1.26,<3',build='py310*']",
|
||||
],
|
||||
)
|
||||
def test_supported_conda_requirements_are_preserved(package):
|
||||
definition = function(conda=[package])(identity)
|
||||
assert definition.registration_request.runtime.environment.packages == (package,)
|
||||
|
||||
|
||||
def test_requirements_still_sort_and_deduplicate():
|
||||
definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity)
|
||||
assert definition.registration_request.runtime.environment.packages == (
|
||||
"numpy",
|
||||
"torch>=2",
|
||||
)
|
||||
|
||||
|
||||
def test_deprecated_udf_alias_validates_requirements():
|
||||
with pytest.warns(DeprecationWarning, match="use lancedb.function"):
|
||||
with pytest.raises(ValueError, match=r"pip\[0\]"):
|
||||
udf(pip=["torch>=2.0,,<3"])(identity)
|
||||
|
||||
|
||||
def test_direct_function_definition_validates_requirements():
|
||||
with pytest.raises(ValueError, match=r"pip\[0\]"):
|
||||
FunctionDefinition(
|
||||
identity,
|
||||
name=None,
|
||||
input_schema=None,
|
||||
output_schema=None,
|
||||
pip=("torch>=2.0,,<3",),
|
||||
env={},
|
||||
python_version=None,
|
||||
)
|
||||
@@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable):
|
||||
assert result["_rowid"].to_pylist() == [0, 3]
|
||||
|
||||
|
||||
def test_hybrid_fragment_constraints_fail_loud(sync_table: Table):
|
||||
query = (
|
||||
sync_table.search("dog", query_type="hybrid")
|
||||
.vector([0.5, -0.5])
|
||||
.fragment_ids([0])
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.to_arrow()
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.explain_plan()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable):
|
||||
query = (
|
||||
table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0])
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.to_arrow()
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.analyze_plan()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_query_filters(table: AsyncTable):
|
||||
# test that query params are passed down from the regular builder to
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
from datetime import timedelta
|
||||
import random
|
||||
import struct
|
||||
from typing import get_args, get_type_hints
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
import lancedb
|
||||
from lancedb import AsyncConnection, AsyncTable, connect_async
|
||||
from lancedb.index import (
|
||||
BTree,
|
||||
@@ -22,6 +24,8 @@ from lancedb.index import (
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -249,6 +253,388 @@ async def test_create_fm_index(some_table: AsyncTable):
|
||||
assert indices[0].columns == ["data"]
|
||||
|
||||
|
||||
POINT_TYPE = pa.struct([("x", pa.float64()), ("y", pa.float64())])
|
||||
POLYGON_TYPE = pa.list_(pa.field("rings", pa.list_(pa.field("vertices", POINT_TYPE))))
|
||||
|
||||
|
||||
def geoarrow_field(name: str, extension: str, data_type: pa.DataType) -> pa.Field:
|
||||
return pa.field(
|
||||
name,
|
||||
data_type,
|
||||
metadata={
|
||||
"ARROW:extension:name": extension,
|
||||
"ARROW:extension:metadata": "{}",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# The triangle's bounding box covers the 25 grid points with x <= 4 and y <= 4,
|
||||
# but only the 15 with x + y <= 4 intersect the triangle itself.
|
||||
TRIANGLE = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
|
||||
INTERSECTS_TRIANGLE = f"ST_Intersects(geom, {TRIANGLE})"
|
||||
TRIANGLE_IDS = [10 * y + x for y in range(10) for x in range(10) if x + y <= 4]
|
||||
|
||||
|
||||
def grid_points(nrows: int) -> pa.Table:
|
||||
"""A grid of GeoArrow points in which row ``10 * y + x`` sits at ``(x, y)``."""
|
||||
ids = list(range(nrows))
|
||||
geom = pa.StructArray.from_arrays(
|
||||
[
|
||||
pa.array([float(i % 10) for i in ids]),
|
||||
pa.array([float(i // 10) for i in ids]),
|
||||
],
|
||||
names=["x", "y"],
|
||||
)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
|
||||
pa.field("vector", pa.list_(pa.float32(), DIM)),
|
||||
]
|
||||
)
|
||||
return pa.Table.from_arrays(
|
||||
[pa.array(ids, pa.int64()), geom, sample_fixed_size_list_array(nrows, DIM)],
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def point_table(db_async):
|
||||
return await db_async.create_table("point_table", grid_points(100))
|
||||
|
||||
|
||||
async def query_ids(query) -> list:
|
||||
return (await query.to_arrow())["id"].to_pylist()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_rtree_index(point_table: AsyncTable):
|
||||
assert sorted(await query_ids(point_table.query().where(INTERSECTS_TRIANGLE))) == (
|
||||
TRIANGLE_IDS
|
||||
)
|
||||
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
indices = await point_table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].name == "geom_idx"
|
||||
assert indices[0].index_type == "RTree"
|
||||
assert indices[0].columns == ["geom"]
|
||||
stats = await point_table.index_stats("geom_idx")
|
||||
assert stats.index_type == "RTREE"
|
||||
assert stats.num_indexed_rows == 100
|
||||
assert stats.num_unindexed_rows == 0
|
||||
|
||||
# The index narrows the scan to the bounding box; the exact predicate then
|
||||
# drops the candidates that fall outside the triangle.
|
||||
query = point_table.query().where(INTERSECTS_TRIANGLE)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == TRIANGLE_IDS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"predicate, expected_ids",
|
||||
[
|
||||
(INTERSECTS_TRIANGLE, TRIANGLE_IDS),
|
||||
(f"ST_Within(geom, {TRIANGLE})", [11, 12, 21]),
|
||||
(f"ST_CoveredBy(geom, {TRIANGLE})", TRIANGLE_IDS),
|
||||
(
|
||||
f"ST_Touches(geom, {TRIANGLE})",
|
||||
[0, 1, 2, 3, 4, 10, 13, 20, 22, 30, 31, 40],
|
||||
),
|
||||
(f"ST_Intersects(geom, {TRIANGLE}) AND id > 20", [21, 22, 30, 31, 40]),
|
||||
("ST_Intersects(geom, ST_Point(3.0, 3.0))", [33]),
|
||||
("ST_Contains(geom, ST_Point(3.0, 3.0))", [33]),
|
||||
("ST_Covers(geom, ST_Point(3.0, 3.0))", [33]),
|
||||
],
|
||||
)
|
||||
async def test_rtree_index_accelerates_spatial_filters(
|
||||
point_table: AsyncTable, predicate: str, expected_ids: list
|
||||
):
|
||||
unindexed = sorted(await query_ids(point_table.query().where(predicate)))
|
||||
assert unindexed == expected_ids
|
||||
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
query = point_table.query().where(predicate)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rtree_index_prefilters_vector_search(point_table: AsyncTable):
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Row 99 sits outside the triangle, and its nearest vectors are rows 98, 97, ...
|
||||
far_corner = list(range(99 * DIM, 100 * DIM))
|
||||
|
||||
prefiltered = point_table.query().nearest_to(far_corner).where(INTERSECTS_TRIANGLE)
|
||||
assert "ScalarIndexQuery" in await prefiltered.explain_plan(True)
|
||||
assert await query_ids(prefiltered.limit(5)) == [40, 31, 30, 22, 21]
|
||||
|
||||
postfiltered = (
|
||||
point_table.query()
|
||||
.nearest_to(far_corner)
|
||||
.where(INTERSECTS_TRIANGLE)
|
||||
.postfilter()
|
||||
.limit(5)
|
||||
)
|
||||
assert await query_ids(postfiltered) == []
|
||||
|
||||
|
||||
def square(corner: float) -> list:
|
||||
"""A 2 x 2 square polygon with its lower left corner at ``(corner, corner)``."""
|
||||
ring = [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]
|
||||
return [[{"x": corner + x, "y": corner + y} for x, y in ring]]
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def polygon_table(db_async):
|
||||
"""Ten overlapping squares; row ``i`` covers ``(i, i)`` to ``(i + 2, i + 2)``."""
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("area", "geoarrow.polygon", POLYGON_TYPE),
|
||||
]
|
||||
)
|
||||
data = pa.Table.from_arrays(
|
||||
[
|
||||
pa.array(range(10), pa.int64()),
|
||||
pa.array([square(float(i)) for i in range(10)], POLYGON_TYPE),
|
||||
],
|
||||
schema=schema,
|
||||
)
|
||||
return await db_async.create_table("polygons", data)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"predicate, expected_ids",
|
||||
[
|
||||
("ST_Intersects(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
|
||||
("ST_Contains(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
|
||||
("ST_Covers(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
|
||||
("ST_Crosses(area, ST_GeomFromText('LINESTRING (2.5 2.5, 2.5 10)'))", [1, 2]),
|
||||
(
|
||||
"ST_Overlaps(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
|
||||
[2, 4],
|
||||
),
|
||||
(
|
||||
"ST_Touches(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
|
||||
[1, 5],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_create_rtree_index_on_polygons(
|
||||
polygon_table: AsyncTable, predicate: str, expected_ids: list
|
||||
):
|
||||
assert sorted(await query_ids(polygon_table.query().where(predicate))) == (
|
||||
expected_ids
|
||||
)
|
||||
|
||||
await polygon_table.create_index("area", config=RTree(page_size=2))
|
||||
assert (await polygon_table.list_indices())[0].index_type == "RTree"
|
||||
|
||||
query = polygon_table.query().where(predicate)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rtree_index_with_null_geometries(db_async):
|
||||
# Every third row has no geometry; the others sit on the diagonal at (i, i).
|
||||
geom = pa.array(
|
||||
[None if i % 3 == 0 else {"x": float(i), "y": float(i)} for i in range(10)],
|
||||
POINT_TYPE,
|
||||
)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
|
||||
]
|
||||
)
|
||||
table = await db_async.create_table(
|
||||
"nulls",
|
||||
pa.Table.from_arrays([pa.array(range(10), pa.int64()), geom], schema=schema),
|
||||
)
|
||||
box = "ST_GeomFromText('POLYGON ((-1 -1, 1.5 -1, 1.5 1.5, -1 1.5, -1 -1))')"
|
||||
expected = {
|
||||
"geom IS NULL": [0, 3, 6, 9],
|
||||
"geom IS NOT NULL": [1, 2, 4, 5, 7, 8],
|
||||
# Row 0 is inside the box but has no geometry, so it matches neither.
|
||||
f"ST_Intersects(geom, {box})": [1],
|
||||
f"NOT ST_Intersects(geom, {box})": [2, 4, 5, 7, 8],
|
||||
}
|
||||
for predicate, ids in expected.items():
|
||||
assert sorted(await query_ids(table.query().where(predicate))) == ids
|
||||
|
||||
await table.create_index("geom", config=RTree())
|
||||
for predicate, ids in expected.items():
|
||||
assert sorted(await query_ids(table.query().where(predicate))) == ids
|
||||
for predicate in ["geom IS NULL", f"ST_Intersects(geom, {box})"]:
|
||||
assert "ScalarIndexQuery" in await table.query().where(predicate).explain_plan(
|
||||
True
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_rtree_index_on_wkb(db_async):
|
||||
"""GeoParquet and GeoPandas data usually arrives as well-known binary."""
|
||||
|
||||
def wkb_point(x: float, y: float) -> bytes:
|
||||
# Byte order (1 = little endian), geometry type (1 = point), x, y.
|
||||
return struct.pack("<BIdd", 1, 1, x, y)
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("geom", "geoarrow.wkb", pa.binary()),
|
||||
]
|
||||
)
|
||||
data = pa.Table.from_arrays(
|
||||
[
|
||||
pa.array(range(100), pa.int64()),
|
||||
pa.array([wkb_point(i % 10, i // 10) for i in range(100)], pa.binary()),
|
||||
],
|
||||
schema=schema,
|
||||
)
|
||||
table = await db_async.create_table("wkb", data)
|
||||
assert sorted(await query_ids(table.query().where(INTERSECTS_TRIANGLE))) == (
|
||||
TRIANGLE_IDS
|
||||
)
|
||||
|
||||
await table.create_index("geom", config=RTree())
|
||||
query = table.query().where(INTERSECTS_TRIANGLE)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == TRIANGLE_IDS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rtree_index_after_append_and_optimize(point_table: AsyncTable):
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Rows 100..199 continue the grid above the first one, at y = 10..19.
|
||||
await point_table.add(grid_points(200).slice(100))
|
||||
across_both = (
|
||||
"ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 9, 2 9, 2 11, 0 11, 0 9))'))"
|
||||
)
|
||||
expected = [90, 91, 92, 100, 101, 102, 110, 111, 112]
|
||||
|
||||
stats = await point_table.index_stats("geom_idx")
|
||||
assert stats is not None
|
||||
assert (stats.num_indexed_rows, stats.num_unindexed_rows) == (100, 100)
|
||||
assert sorted(await query_ids(point_table.query().where(across_both))) == expected
|
||||
|
||||
await point_table.optimize()
|
||||
stats = await point_table.index_stats("geom_idx")
|
||||
assert stats is not None
|
||||
assert (stats.num_indexed_rows, stats.num_unindexed_rows) == (200, 0)
|
||||
query = point_table.query().where(across_both)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_geoarrow_column_round_trips(point_table: AsyncTable):
|
||||
"""Enabling geo support must not change how GeoArrow columns are stored or read."""
|
||||
expected = grid_points(100)
|
||||
schema = await point_table.schema()
|
||||
assert schema.field("geom").metadata == expected.schema.field("geom").metadata
|
||||
assert schema.field("geom").type == POINT_TYPE
|
||||
|
||||
data = (await point_table.query().to_arrow()).sort_by("id")
|
||||
assert data["geom"].to_pylist() == expected["geom"].to_pylist()
|
||||
assert sorted(await query_ids(point_table.query().where("id < 3"))) == [0, 1, 2]
|
||||
|
||||
|
||||
# Asymmetric predicates with the constant geometry first. GeoDataFusion once
|
||||
# evaluated these with the arguments swapped, so a write filter silently matched
|
||||
# the wrong rows. Only the three interior points are contained, the boundary
|
||||
# points are also covered, and no point contains or covers the triangle.
|
||||
CONSTANT_FIRST_CASES = [
|
||||
(f"ST_Contains({TRIANGLE}, geom)", [11, 12, 21]),
|
||||
(f"ST_Covers({TRIANGLE}, geom)", TRIANGLE_IDS),
|
||||
(f"ST_Within({TRIANGLE}, geom)", []),
|
||||
(f"ST_CoveredBy({TRIANGLE}, geom)", []),
|
||||
(f"ST_Intersects({TRIANGLE}, geom)", TRIANGLE_IDS),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
|
||||
async def test_spatial_filter_constant_first(
|
||||
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
|
||||
):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
query = point_table.query().where(predicate)
|
||||
assert sorted(await query_ids(query)) == expected_ids
|
||||
if indexed:
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
|
||||
async def test_delete_with_constant_first_spatial_filter(
|
||||
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
|
||||
):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Delete every row the predicate rejects; exactly the matching rows survive.
|
||||
await point_table.delete(f"NOT {predicate}")
|
||||
assert sorted(await query_ids(point_table.query())) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
|
||||
async def test_update_with_constant_first_spatial_filter(
|
||||
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
|
||||
):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Map each matching id to a negative one (-id - 1 keeps row 0 distinct).
|
||||
await point_table.update(updates_sql={"id": "-id - 1"}, where=predicate)
|
||||
updated = await query_ids(point_table.query().where("id < 0"))
|
||||
assert sorted(-new_id - 1 for new_id in updated) == expected_ids
|
||||
assert await point_table.count_rows() == 100
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
async def test_spatial_filter_with_null_constant(point_table: AsyncTable, indexed):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
null_geometry = "ST_GeomFromText(CAST(NULL AS VARCHAR))"
|
||||
for predicate in [
|
||||
f"ST_Intersects(geom, {null_geometry})",
|
||||
f"ST_Within(geom, {null_geometry})",
|
||||
]:
|
||||
assert await query_ids(point_table.query().where(predicate)) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_rtree_index_rejects_invalid_input(point_table: AsyncTable):
|
||||
with pytest.raises(ValueError, match="page_size must be at least 2"):
|
||||
await point_table.create_index("geom", config=RTree(page_size=1))
|
||||
# Only the message is part of the contract, not the exception type.
|
||||
with pytest.raises(Exception, match="GeoArrow"):
|
||||
await point_table.create_index("id", config=RTree())
|
||||
assert await point_table.list_indices() == []
|
||||
|
||||
|
||||
def test_create_rtree_index_sync(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("points", grid_points(100))
|
||||
table.create_index("geom", config=RTree())
|
||||
assert [index.index_type for index in table.list_indices()] == ["RTree"]
|
||||
table.create_index("geom", config=RTree(page_size=16), name="geom_rtree")
|
||||
assert table.index_stats("geom_rtree").index_type == "RTREE"
|
||||
|
||||
query = table.search().where(INTERSECTS_TRIANGLE).limit(100)
|
||||
assert "ScalarIndexQuery" in query.explain_plan(True)
|
||||
assert sorted(query.to_arrow()["id"].to_pylist()) == TRIANGLE_IDS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_ngram_index(db_async):
|
||||
# NGram indexes accelerate substring filters on UTF-8 string columns.
|
||||
@@ -279,6 +665,28 @@ async def test_create_ngram_index(db_async):
|
||||
assert "ScalarIndexQuery" in plan
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_zonemap_index(db_async):
|
||||
# ZoneMap indexes accelerate range and equality filters on ordered columns.
|
||||
data = pa.table(
|
||||
{
|
||||
"id": list(range(100)),
|
||||
"value": list(range(100)),
|
||||
}
|
||||
)
|
||||
table = await db_async.create_table("zonemap_table", data)
|
||||
await table.create_index("value", config=ZoneMap())
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].index_type == "ZoneMap"
|
||||
assert indices[0].columns == ["value"]
|
||||
|
||||
# The index narrows a range scan without changing its results.
|
||||
result = await table.query().where("value >= 90").to_arrow()
|
||||
assert sorted(result["id"].to_pylist()) == list(range(90, 100))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bitmap_index(some_table: AsyncTable):
|
||||
await some_table.create_index("id", config=Bitmap())
|
||||
@@ -591,9 +999,53 @@ def test_index_statistics_index_type_lists_all_supported_values():
|
||||
"BITMAP",
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
"ZONEMAP",
|
||||
"RTREE",
|
||||
}
|
||||
|
||||
assert (
|
||||
set(get_args(get_type_hints(IndexStatistics)["index_type"]))
|
||||
== expected_index_types
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))]
|
||||
)
|
||||
async def test_index_exist_ok_preserves_existing_index(
|
||||
some_table, background, column, config
|
||||
):
|
||||
await some_table.create_index(column, config=config, exist_ok=True)
|
||||
version = await some_table.version()
|
||||
original = await some_table.list_indices()
|
||||
if background:
|
||||
job = await some_table.create_index_async(
|
||||
column, config=config, replace=True, exist_ok=True
|
||||
)
|
||||
await job.wait()
|
||||
else:
|
||||
await some_table.create_index(
|
||||
column, config=config, replace=True, exist_ok=True
|
||||
)
|
||||
assert await some_table.version() == version
|
||||
assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [
|
||||
(i.name, i.index_type) for i in original
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
async def test_named_index_exist_ok_checks_before_column_validation(
|
||||
some_table, background
|
||||
):
|
||||
await some_table.create_index("id", config=BTree(), name="kept")
|
||||
version = await some_table.version()
|
||||
method = some_table.create_index_async if background else some_table.create_index
|
||||
result = await method("missing", config=BTree(), name="kept", exist_ok=True)
|
||||
if background:
|
||||
assert result.id is None
|
||||
await result.wait()
|
||||
assert await some_table.version() == version
|
||||
assert [index.name for index in await some_table.list_indices()] == ["kept"]
|
||||
|
||||
@@ -2,17 +2,64 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from lancedb.exceptions import JobCancelledError, JobFailedError
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.job import AsyncJob, Job, _progress_eta
|
||||
from lancedb.remote.errors import HttpError, RetryError
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
def test_job_repr_bounds_large_payloads_without_fetching(sync):
|
||||
spec = {"initialization": list(range(100000)), "source": "x" * 100000}
|
||||
result = {"rows_computed": 7, "details": [{"data": b"x" * 10000}] * 1000}
|
||||
inner = SimpleNamespace(
|
||||
id="job-repr",
|
||||
_state="failed",
|
||||
job_type="function_refresh",
|
||||
_description=SimpleNamespace(
|
||||
creation_ms=2000,
|
||||
spec=spec,
|
||||
result=result,
|
||||
failure="worker failed " + "x" * 10000,
|
||||
),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
if sync:
|
||||
job = Job(job)
|
||||
rendered = repr(job)
|
||||
assert len(rendered) < 1600
|
||||
assert len(rendered.splitlines()) <= 10
|
||||
assert "id='job-repr'" in rendered
|
||||
assert "state='failed'" in rendered
|
||||
assert "job_type='function_refresh'" in rendered
|
||||
assert "rows_computed" in rendered
|
||||
assert "worker failed" in rendered
|
||||
assert "..." in rendered
|
||||
assert len(repr(job.status)) < 1700
|
||||
assert job.spec is spec
|
||||
assert job.result is result
|
||||
assert len(job.spec["initialization"]) == 100000
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
def test_job_repr_handles_unobserved_and_local_jobs(sync):
|
||||
unobserved = AsyncJob(SimpleNamespace(id="job-pending", _state=None))
|
||||
local = AsyncJob(None)
|
||||
if sync:
|
||||
unobserved, local = Job(unobserved), Job(local)
|
||||
assert "id='job-pending', not refreshed" in repr(unobserved)
|
||||
assert "state='finished'" in repr(local)
|
||||
assert "failure=" not in repr(local)
|
||||
|
||||
|
||||
@pytest.fixture(params=["async", "sync"])
|
||||
def wait_job(request):
|
||||
async def wait(inner, timeout=None, result_decoder=None):
|
||||
@@ -683,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
|
||||
@pytest.mark.parametrize("progress", [False, None])
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
|
||||
class NoProgressArgument:
|
||||
id = "job-legacy"
|
||||
job_type = None
|
||||
|
||||
@property
|
||||
def job_type(self):
|
||||
raise AssertionError("quiet waits must not inspect progress metadata")
|
||||
|
||||
async def wait(self):
|
||||
return None
|
||||
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
|
||||
|
||||
|
||||
class _RegistrationQuery:
|
||||
id = "registration-query"
|
||||
job_type = "query"
|
||||
_description = None
|
||||
|
||||
def __init__(self, error=None):
|
||||
self.ready = asyncio.Event()
|
||||
self.error = error
|
||||
self.state = "running"
|
||||
self.wait_calls = 0
|
||||
self.cancel_calls = 0
|
||||
|
||||
async def status(self):
|
||||
return self.state
|
||||
|
||||
async def wait(self, progress=None):
|
||||
self.wait_calls += 1
|
||||
await self.ready.wait()
|
||||
if self.error is not None:
|
||||
self.state = (
|
||||
"cancelled" if isinstance(self.error, JobCancelledError) else "failed"
|
||||
)
|
||||
raise self.error
|
||||
self.state = "finished"
|
||||
return '{"version": "1"}'
|
||||
|
||||
async def cancel(self):
|
||||
self.cancel_calls += 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
|
||||
monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
|
||||
inner = _RegistrationQuery()
|
||||
job = AsyncJob(inner, json.loads)
|
||||
updates = []
|
||||
|
||||
def observe(snapshot):
|
||||
updates.append(snapshot)
|
||||
if len(updates) == 2:
|
||||
inner.ready.set()
|
||||
|
||||
if sync:
|
||||
result = await asyncio.to_thread(Job(job).wait, progress=observe)
|
||||
else:
|
||||
result = await job.wait(progress=observe)
|
||||
assert result == {"version": "1"}
|
||||
assert inner.wait_calls == 1
|
||||
assert inner.cancel_calls == 0
|
||||
assert updates[0]["state"] == "running"
|
||||
assert updates[-1]["state"] == "finished"
|
||||
assert all(snapshot["job_id"] == inner.id for snapshot in updates)
|
||||
elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
|
||||
assert elapsed == sorted(elapsed)
|
||||
assert elapsed[0] >= 0
|
||||
assert all("phase" not in snapshot for snapshot in updates)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
JobFailedError("bake failed", job_id="registration-query"),
|
||||
JobCancelledError("cancelled"),
|
||||
],
|
||||
)
|
||||
async def test_query_progress_preserves_terminal_exceptions(error):
|
||||
inner = _RegistrationQuery(error)
|
||||
inner.ready.set()
|
||||
updates = []
|
||||
with pytest.raises(type(error)) as raised:
|
||||
await AsyncJob(inner).wait(progress=updates.append)
|
||||
assert raised.value is error
|
||||
assert updates[-1]["state"] == inner.state
|
||||
assert inner.wait_calls == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
|
||||
monkeypatch,
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
bar = SimpleNamespace(
|
||||
n=0,
|
||||
total=None,
|
||||
update=MagicMock(),
|
||||
set_postfix_str=MagicMock(),
|
||||
close=MagicMock(),
|
||||
)
|
||||
constructor = MagicMock(return_value=bar)
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", constructor)
|
||||
inner = _RegistrationQuery(JobFailedError("bake failed"))
|
||||
inner.ready.set()
|
||||
|
||||
with pytest.raises(JobFailedError, match="bake failed"):
|
||||
await AsyncJob(inner).wait(progress=True)
|
||||
assert "elapsed" in constructor.call_args.kwargs["bar_format"]
|
||||
assert "rows" not in str(constructor.call_args)
|
||||
assert bar.set_postfix_str.call_args.args == ("failed",)
|
||||
bar.close.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failed", [False, True])
|
||||
@pytest.mark.parametrize("observer_error", ["status", "callback"])
|
||||
async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
|
||||
failed, observer_error, caplog
|
||||
):
|
||||
error = (
|
||||
JobFailedError("bake failed", job_id="registration-query") if failed else None
|
||||
)
|
||||
inner = _RegistrationQuery(error)
|
||||
inner.ready.set()
|
||||
if observer_error == "status":
|
||||
inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
|
||||
|
||||
def observe(snapshot):
|
||||
if observer_error == "callback":
|
||||
raise RuntimeError("observer failed")
|
||||
|
||||
job = AsyncJob(inner, json.loads)
|
||||
if failed:
|
||||
with pytest.raises(JobFailedError) as raised:
|
||||
await job.wait(progress=observe)
|
||||
assert raised.value is error
|
||||
else:
|
||||
assert await job.wait(progress=observe) == {"version": "1"}
|
||||
assert inner.wait_calls == 1
|
||||
assert inner.cancel_calls == 0
|
||||
assert "job progress observer failed" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
|
||||
inner = _RegistrationQuery()
|
||||
job = AsyncJob(inner, json.loads)
|
||||
updates = []
|
||||
with pytest.raises(TimeoutError, match="keep this handle"):
|
||||
await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
|
||||
assert inner.state == "running"
|
||||
assert inner.cancel_calls == 0
|
||||
inner.ready.set()
|
||||
assert await job.wait(progress=updates.append) == {"version": "1"}
|
||||
assert inner.wait_calls == 2
|
||||
assert updates[-1]["state"] == "finished"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("refresh_lock", [False, True])
|
||||
def test_blocking_create_function_forwards_progress_to_registration_handle(
|
||||
refresh_lock,
|
||||
):
|
||||
connection = MagicMock()
|
||||
definition = object()
|
||||
progress = object()
|
||||
result = DBConnection.create_function(
|
||||
connection, definition, refresh_lock=refresh_lock, progress=progress
|
||||
)
|
||||
connection.create_function_async.assert_called_once_with(
|
||||
definition,
|
||||
secrets=None,
|
||||
exist_ok=False,
|
||||
namespace_path=None,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
connection.create_function_async.return_value.wait.assert_called_once_with(
|
||||
progress=progress
|
||||
)
|
||||
assert result is connection.create_function_async.return_value.wait.return_value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("progress", [False, None])
|
||||
def test_blocking_create_function_preserves_quiet_wait_call(progress):
|
||||
connection = MagicMock()
|
||||
result = DBConnection.create_function(connection, object(), progress=progress)
|
||||
connection.create_function_async.return_value.wait.assert_called_once_with()
|
||||
assert result is connection.create_function_async.return_value.wait.return_value
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -706,3 +936,231 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
|
||||
assert "continues on the server" in message
|
||||
assert "keep this handle to continue waiting" in message
|
||||
assert "db.open_job" not in message
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys):
|
||||
reports = [
|
||||
None,
|
||||
"Function job: finished\nWorker utilization: unavailable\n",
|
||||
"Function job: finished\nWorker utilization: 25.0%\n",
|
||||
]
|
||||
inner = SimpleNamespace(
|
||||
stats=AsyncMock(side_effect=reports),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
for expected in reports:
|
||||
actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats()
|
||||
assert actual == expected
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
assert capsys.readouterr().out == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync):
|
||||
error = RuntimeError("run reports are unavailable on this server")
|
||||
job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error)))
|
||||
with pytest.raises(RuntimeError) as exc:
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).stats)
|
||||
else:
|
||||
await job.stats()
|
||||
assert exc.value is error
|
||||
with pytest.raises(NotImplementedError, match="server-side Function job"):
|
||||
if sync:
|
||||
Job(None).stats()
|
||||
else:
|
||||
await AsyncJob(None).stats()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path):
|
||||
trace = {
|
||||
"traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}],
|
||||
"metadata": {"partial": True},
|
||||
}
|
||||
inner = SimpleNamespace(
|
||||
timeline=AsyncMock(return_value=json.dumps(trace)),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
path = tmp_path / "job.trace.json"
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).export_timeline, str(path))
|
||||
else:
|
||||
await job.export_timeline(path)
|
||||
assert json.loads(path.read_text()) == trace
|
||||
inner.timeline.assert_awaited_once_with()
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_timeline_failure_preserves_existing_file(tmp_path):
|
||||
path = tmp_path / "job.trace.json"
|
||||
path.write_text("previous recording")
|
||||
job = AsyncJob(
|
||||
SimpleNamespace(
|
||||
timeline=AsyncMock(side_effect=RuntimeError("unsupported server"))
|
||||
)
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="unsupported server"):
|
||||
await job.export_timeline(path)
|
||||
assert path.read_text() == "previous recording"
|
||||
with pytest.raises(NotImplementedError, match="server-side Function job"):
|
||||
await AsyncJob(None).export_timeline(path)
|
||||
with pytest.raises(NotImplementedError, match="server-side Function job"):
|
||||
Job(None).export_timeline(path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_timeline_reports_filesystem_errors(tmp_path):
|
||||
job = AsyncJob(
|
||||
SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}'))
|
||||
)
|
||||
with pytest.raises(FileNotFoundError):
|
||||
await job.export_timeline(tmp_path / "missing" / "trace.json")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stack_preserves_evidence_and_does_not_wait(sync):
|
||||
evidence = {
|
||||
"worker_id": "worker",
|
||||
"status": "unavailable",
|
||||
"execution_epoch": 1,
|
||||
"stacks": [],
|
||||
"omitted_sessions": 0,
|
||||
}
|
||||
inner = SimpleNamespace(
|
||||
stack=AsyncMock(return_value=json.dumps(evidence)),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
actual = (
|
||||
await asyncio.to_thread(Job(job).stack, "worker")
|
||||
if sync
|
||||
else await job.stack("worker")
|
||||
)
|
||||
assert actual == evidence
|
||||
inner.stack.assert_awaited_once_with("worker")
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stack_propagates_errors_and_rejects_local_handles(sync):
|
||||
error = RuntimeError("system operate privilege required")
|
||||
job = AsyncJob(SimpleNamespace(stack=AsyncMock(side_effect=error)))
|
||||
with pytest.raises(RuntimeError) as failure:
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).stack, "worker")
|
||||
else:
|
||||
await job.stack("worker")
|
||||
assert failure.value is error
|
||||
with pytest.raises(NotImplementedError):
|
||||
if sync:
|
||||
Job(None).stack("worker")
|
||||
else:
|
||||
await AsyncJob(None).stack("worker")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"kind,planned_key,completed_key,unit",
|
||||
[
|
||||
("compact", "rows_planned", "rows_rewritten", " rows"),
|
||||
(
|
||||
"prewarm_page_cache",
|
||||
"executors_targeted",
|
||||
"executors_completed",
|
||||
" executors",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry(
|
||||
monkeypatch, kind, planned_key, completed_key, unit
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
total = None
|
||||
n = 0
|
||||
unit = " rows"
|
||||
closed = False
|
||||
|
||||
def update(self, delta):
|
||||
self.n += delta
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
class MaintenanceJob:
|
||||
id = "maintenance-job"
|
||||
job_type = kind
|
||||
|
||||
async def wait(self, progress):
|
||||
progress({"job_type": kind, "phase": "planning"})
|
||||
assert bar.total is None
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 2})
|
||||
assert bar.n == 2
|
||||
# Older responses can omit an epoch; revised observations still
|
||||
# replace the previous attempt's displayed work.
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 1})
|
||||
assert bar.n == 1
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 4})
|
||||
|
||||
assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None
|
||||
assert bar.n == 4
|
||||
assert bar.total == 4
|
||||
assert bar.unit == unit
|
||||
assert bar.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("known_empty", [False, True])
|
||||
async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals(
|
||||
monkeypatch, known_empty
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
total = None
|
||||
n = 0
|
||||
unit = " rows"
|
||||
|
||||
def update(self, delta):
|
||||
self.n += delta
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
class PrewarmJob:
|
||||
id = "prewarm-job"
|
||||
job_type = "prewarm_page_cache"
|
||||
|
||||
async def wait(self, progress):
|
||||
snapshot = {"job_type": self.job_type, "phase": "succeeded"}
|
||||
if known_empty:
|
||||
snapshot.update(executors_targeted=0, executors_completed=0)
|
||||
progress(snapshot)
|
||||
|
||||
assert await AsyncJob(PrewarmJob()).wait(progress=True) is None
|
||||
assert bar.n == 0
|
||||
assert bar.total == (0 if known_empty else None)
|
||||
assert bar.unit == " executors"
|
||||
|
||||
@@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
|
||||
if kind == "jobs":
|
||||
assert verb == "POST"
|
||||
assert path.path == "/v1/jobs/list"
|
||||
assert body == {"page_token": token, "limit": 2}
|
||||
assert body == {"database": "dev", "page_token": token, "limit": 2}
|
||||
else:
|
||||
namespace = "team"
|
||||
resource = kind.removesuffix("s")
|
||||
@@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l
|
||||
with pytest.raises(ValueError, match="limit"):
|
||||
await items.__anext__()
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [[], ["team", "project"]])
|
||||
@pytest.mark.parametrize("multiple_types", [False, True])
|
||||
async def test_job_filters_persist_across_pages_and_resume(
|
||||
listing_server, asynchronous, namespace, multiple_types
|
||||
):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)]
|
||||
)
|
||||
db = await connection(endpoint, asynchronous)
|
||||
types = ["column_refresh", "materialized_view_refresh"]
|
||||
filters = dict(
|
||||
table="events",
|
||||
namespace_path=namespace,
|
||||
state="in_progress",
|
||||
created_at_gte_millis=100,
|
||||
created_at_lt_millis=200,
|
||||
**({"job_types": types} if multiple_types else {"job_type": types[0]}),
|
||||
)
|
||||
items = db.list_jobs(page_limit=1, **filters)
|
||||
assert requests == []
|
||||
assert (await advance(items, asynchronous)).job_id == "a"
|
||||
assert len(requests) == 1
|
||||
resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters)
|
||||
assert (await advance(resumed, asynchronous)).job_id == "b"
|
||||
assert resumed.page_token() is None
|
||||
assert len(requests) == 3
|
||||
expected = dict(
|
||||
database="dev",
|
||||
limit=1,
|
||||
table_ref={
|
||||
"db_name": "dev",
|
||||
"table_id": {"namespace_path": namespace, "table_name": "events"},
|
||||
},
|
||||
state="in_progress",
|
||||
job_types=types if multiple_types else types[:1],
|
||||
created_at_gte_millis=100,
|
||||
created_at_lt_millis=200,
|
||||
)
|
||||
for (_, path, body), token in zip(requests, [None, "empty", "last"]):
|
||||
assert path == "/v1/jobs/list"
|
||||
assert body == {**expected, **({"page_token": token} if token else {})}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"filters",
|
||||
[
|
||||
{},
|
||||
{"state": "failed"},
|
||||
{"job_types": ["column_refresh"]},
|
||||
{"created_at_lt_millis": 200},
|
||||
],
|
||||
)
|
||||
async def test_job_listing_without_table_stays_in_connected_database(
|
||||
listing_server, asynchronous, filters
|
||||
):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.append((200, response_page("jobs", ["a"], None)))
|
||||
db = await connection(endpoint, asynchronous)
|
||||
items = db.list_jobs(**filters)
|
||||
assert (await advance(items, asynchronous)).job_id == "a"
|
||||
assert requests[0][2] == {"database": "dev", **filters}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"filters, message",
|
||||
[
|
||||
({"namespace_path": ["team"]}, "requires a table"),
|
||||
({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"),
|
||||
({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"),
|
||||
({"job_type": "column_refresh", "job_types": []}, "only one"),
|
||||
({"state": "unknown"}, "state must be"),
|
||||
],
|
||||
)
|
||||
async def test_invalid_job_filters_do_not_fetch(
|
||||
listing_server, asynchronous, filters, message
|
||||
):
|
||||
endpoint, requests, _ = listing_server
|
||||
db = await connection(endpoint, asynchronous)
|
||||
with pytest.raises(ValueError, match=message):
|
||||
items = db.list_jobs(**filters)
|
||||
await advance(items, asynchronous)
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a", "b"], "second"), (["c", "d"], "last")]
|
||||
)
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(table="events", page_limit=2)
|
||||
assert items[:0] == []
|
||||
assert items[5:2] == []
|
||||
assert requests == []
|
||||
assert [job.job_id for job in items[:2]] == ["a", "b"]
|
||||
assert len(requests) == 1
|
||||
assert items.num_page_results() == 2
|
||||
assert items.page_token() == "second"
|
||||
assert items[1].job_id == "b"
|
||||
assert next(items).job_id == "a"
|
||||
assert [job.job_id for job in items[:2]] == ["b", "c"]
|
||||
assert len(requests) == 2
|
||||
assert items.num_page_results() == 3
|
||||
assert items.page_token() == "last"
|
||||
assert [job.job_id for job in items[0:3:2][:1]] == ["b"]
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_length_and_slices_preserve_remaining_items(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)]
|
||||
)
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(page_limit=2)
|
||||
assert bool(items)
|
||||
assert len(requests) == 1
|
||||
assert next(items).job_id == "a"
|
||||
assert len(items) == 3
|
||||
assert len(requests) == 3
|
||||
assert items.num_page_results() == 3
|
||||
assert items.page_token() is None
|
||||
assert items[-1].job_id == "d"
|
||||
assert [job.job_id for job in items[::-1]] == ["d", "c", "b"]
|
||||
assert [job.job_id for job in items[1:]] == ["c", "d"]
|
||||
assert [job.job_id for job in items[:100:2]] == ["b", "d"]
|
||||
assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"]
|
||||
with pytest.raises(IndexError):
|
||||
_ = items[3]
|
||||
assert [job.job_id for job in items] == ["b", "c", "d"]
|
||||
assert len(items) == 0
|
||||
assert not items
|
||||
assert len(requests) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_invalid_slice_does_not_fetch(listing_server):
|
||||
endpoint, requests, _ = listing_server
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs()
|
||||
with pytest.raises(ValueError, match="step"):
|
||||
_ = items[::0]
|
||||
with pytest.raises(TypeError):
|
||||
_ = items["invalid"]
|
||||
with pytest.raises(TypeError):
|
||||
_ = items[:1.5]
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})])
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(page_limit=2)
|
||||
with pytest.raises(HttpError):
|
||||
_ = items[:3]
|
||||
assert items.page_token() == "retry"
|
||||
assert items.num_page_results() == 2
|
||||
assert [job.job_id for job in items[:2]] == ["a", "b"]
|
||||
assert [job.job_id for job in items] == ["a", "b"]
|
||||
assert len(requests) == 2
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [False, True])
|
||||
@pytest.mark.parametrize("defining_query", [False, True])
|
||||
async def test_exist_ok_preserves_materialized_data(
|
||||
tmp_path, asynchronous, background, namespace, defining_query
|
||||
):
|
||||
source_args = (
|
||||
{"query": "SELECT * FROM source"} if defining_query else {"source": "source"}
|
||||
)
|
||||
replacement_args = {
|
||||
**(
|
||||
{"query": "SELECT * FROM missing"}
|
||||
if defining_query
|
||||
else {"source": "missing"}
|
||||
),
|
||||
"auto_refresh_enabled": True,
|
||||
"auto_refresh_interval_seconds": 1,
|
||||
}
|
||||
options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}}
|
||||
if asynchronous:
|
||||
db = (
|
||||
lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options)
|
||||
if namespace
|
||||
else await lancedb.connect_async(tmp_path, **options)
|
||||
)
|
||||
source = await db.create_table("source", [{"id": 1}])
|
||||
original = await db.create_materialized_view(
|
||||
"saved", **source_args, exist_ok=True
|
||||
)
|
||||
definition = await original.definition()
|
||||
version = await original.table.version()
|
||||
await source.add([{"id": 2}])
|
||||
if background:
|
||||
job = await db.create_materialized_view_async(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
await job.wait()
|
||||
kept = await db.open_materialized_view("saved")
|
||||
else:
|
||||
kept = await db.create_materialized_view(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
assert (await kept.definition()).query == definition.query
|
||||
assert await kept.table.version() == version
|
||||
assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}]
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
await db.create_materialized_view("saved", **source_args)
|
||||
else:
|
||||
db = (
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options)
|
||||
if namespace
|
||||
else lancedb.connect(tmp_path, **options)
|
||||
)
|
||||
source = db.create_table("source", [{"id": 1}])
|
||||
original = db.create_materialized_view("saved", **source_args, exist_ok=True)
|
||||
definition = original.definition
|
||||
version = original.table.version
|
||||
source.add([{"id": 2}])
|
||||
if background:
|
||||
job = db.create_materialized_view_async(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
job.wait()
|
||||
kept = db.open_materialized_view("saved")
|
||||
else:
|
||||
kept = db.create_materialized_view(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
assert kept.definition.query == definition.query
|
||||
assert kept.table.version == version
|
||||
assert kept.table.to_arrow().to_pylist() == [{"id": 1}]
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
db.create_materialized_view("saved", **source_args)
|
||||
@@ -10,6 +10,7 @@ import lancedb
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
from lancedb.db import AsyncConnection
|
||||
from lancedb.exceptions import JobFailedError
|
||||
from lancedb.materialized_view import MaterializedViewDefinition
|
||||
from lancedb.remote.db import RemoteDBConnection
|
||||
from utils import start_server_thread
|
||||
@@ -63,7 +64,17 @@ def mock_remote_materialized_view_refresh():
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize("full", [False, True])
|
||||
async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
@pytest.mark.parametrize(
|
||||
"resources",
|
||||
[
|
||||
{},
|
||||
{"gpu_count": 2, "gpu_class": "h100"},
|
||||
{"cpu_millis": 8000, "memory_bytes": 16 * 1024**3, "gpu_count": 0},
|
||||
],
|
||||
)
|
||||
async def test_remote_refresh_reports_unknown_metrics(
|
||||
sync, background, full, resources
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class RefreshServer(flight.FlightServerBase):
|
||||
@@ -90,7 +101,7 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
mock_remote_materialized_view_refresh() as (host, requests),
|
||||
RefreshServer() as server,
|
||||
):
|
||||
options = {"full": True} if full else {}
|
||||
options = {"full": full, **resources}
|
||||
connect = lancedb.connect if sync else lancedb.connect_async
|
||||
db = connect(
|
||||
"db://dev",
|
||||
@@ -140,11 +151,33 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
)
|
||||
(refresh,) = refreshes
|
||||
assert b'REFRESH MATERIALIZED VIEW "view"' in refresh
|
||||
assert (b"WITH (full = true)" in refresh) is full
|
||||
assert (b"full = true" in refresh) is full
|
||||
for key, value in resources.items():
|
||||
expected = (
|
||||
f"{key} = '{value}'" if key == "gpu_class" else f"{key} = {value}"
|
||||
)
|
||||
assert expected.encode() in refresh
|
||||
previous = len(server.commands)
|
||||
for invalid in [
|
||||
{"cpu_millis": 0},
|
||||
{"memory_bytes": 1},
|
||||
{"gpu_count": -1},
|
||||
{"gpu_count": True},
|
||||
{"gpu_count": 2**32},
|
||||
{"gpu_class": "H200:8"},
|
||||
{"gpu_count": 0, "gpu_class": "h100"},
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
if sync:
|
||||
view.refresh(**invalid)
|
||||
else:
|
||||
await view.refresh(**invalid)
|
||||
assert len(server.commands) == previous
|
||||
assert not any("count_rows" in path for path in requests)
|
||||
|
||||
|
||||
def test_sync_remote_create_uses_public_async_connection():
|
||||
@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"])
|
||||
def test_sync_remote_create_uses_public_async_connection(query):
|
||||
calls = []
|
||||
|
||||
class StubAsyncTable:
|
||||
@@ -159,10 +192,12 @@ def test_sync_remote_create_uses_public_async_connection():
|
||||
name,
|
||||
source,
|
||||
*,
|
||||
query=None,
|
||||
select=None,
|
||||
where=None,
|
||||
limit=None,
|
||||
with_no_data=False,
|
||||
exist_ok=False,
|
||||
auto_refresh_enabled=None,
|
||||
auto_refresh_interval_seconds=None,
|
||||
):
|
||||
@@ -170,6 +205,7 @@ def test_sync_remote_create_uses_public_async_connection():
|
||||
(
|
||||
name,
|
||||
source,
|
||||
query,
|
||||
select,
|
||||
where,
|
||||
limit,
|
||||
@@ -188,18 +224,24 @@ def test_sync_remote_create_uses_public_async_connection():
|
||||
db.db_name = "example"
|
||||
db.serialize = lambda: "{}"
|
||||
|
||||
view = db.create_materialized_view(
|
||||
"adults",
|
||||
"people",
|
||||
select=["name"],
|
||||
where="age >= 18",
|
||||
limit=10,
|
||||
with_no_data=True,
|
||||
auto_refresh_enabled=True,
|
||||
auto_refresh_interval_seconds=0.5,
|
||||
)
|
||||
if query is None:
|
||||
view = db.create_materialized_view(
|
||||
"adults",
|
||||
"people",
|
||||
select=["name"],
|
||||
where="age >= 18",
|
||||
limit=10,
|
||||
with_no_data=True,
|
||||
auto_refresh_enabled=True,
|
||||
auto_refresh_interval_seconds=0.5,
|
||||
)
|
||||
assert calls == [
|
||||
("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5)
|
||||
]
|
||||
else:
|
||||
view = db.create_materialized_view("adults", query=query)
|
||||
assert calls == [("adults", None, query, None, None, None, False, None, None)]
|
||||
assert view.name == "adults"
|
||||
assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)]
|
||||
|
||||
db.drop_materialized_view("adults", namespace_path=["analytics"])
|
||||
assert calls[-1] == ("drop", "adults", ["analytics"])
|
||||
@@ -688,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
|
||||
"filter": None,
|
||||
"limit": None,
|
||||
"with_no_data": False,
|
||||
"exist_ok": False,
|
||||
"auto_refresh_enabled": options.get("auto_refresh_enabled"),
|
||||
"auto_refresh_interval_seconds": options.get(
|
||||
"auto_refresh_interval_seconds"
|
||||
@@ -759,3 +802,144 @@ def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path):
|
||||
db = make_db(tmp_path)
|
||||
view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False)
|
||||
assert view.table.count_rows() == 3
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query, expected",
|
||||
[
|
||||
(
|
||||
"SELECT kind, count(*) AS n FROM events GROUP BY kind",
|
||||
[{"kind": "a", "n": 2}, {"kind": "b", "n": 1}],
|
||||
),
|
||||
(
|
||||
"SELECT id, tag FROM events, UNNEST(tags) AS tag",
|
||||
[{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_query_defined_materialized_view(
|
||||
tmp_path, sync, namespace, background, query, expected
|
||||
):
|
||||
if namespace:
|
||||
connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async
|
||||
db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS)
|
||||
elif sync:
|
||||
db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS)
|
||||
else:
|
||||
db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
|
||||
rows = [
|
||||
{"id": 1, "kind": "a", "tags": ["x", "y"]},
|
||||
{"id": 2, "kind": "a", "tags": []},
|
||||
{"id": 3, "kind": "b", "tags": ["z"]},
|
||||
]
|
||||
if sync:
|
||||
db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
|
||||
if background:
|
||||
db.create_materialized_view_async("result", query=query).wait()
|
||||
view = db.open_materialized_view("result")
|
||||
else:
|
||||
view = db.create_materialized_view("result", query=query)
|
||||
actual = view.table.to_arrow().to_pylist()
|
||||
assert view.definition.query == query
|
||||
view.refresh()
|
||||
refreshed = view.table.to_arrow().to_pylist()
|
||||
else:
|
||||
await db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
|
||||
if background:
|
||||
job = await db.create_materialized_view_async("result", query=query)
|
||||
await job.wait()
|
||||
view = await db.open_materialized_view("result")
|
||||
else:
|
||||
view = await db.create_materialized_view("result", query=query)
|
||||
actual = (await view.table.to_arrow()).to_pylist()
|
||||
assert (await view.definition()).query == query
|
||||
await view.refresh()
|
||||
refreshed = (await view.table.to_arrow()).to_pylist()
|
||||
assert sorted(actual, key=str) == sorted(expected, key=str)
|
||||
assert sorted(refreshed, key=str) == sorted(expected, key=str)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"clauses",
|
||||
[{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}],
|
||||
)
|
||||
async def test_query_rejects_source_clauses_before_submission(
|
||||
sync, background, clauses
|
||||
):
|
||||
connect = lancedb.connect if sync else lancedb.connect_async
|
||||
db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1")
|
||||
if not sync:
|
||||
db = await db
|
||||
create = (
|
||||
db.create_materialized_view_async if background else db.create_materialized_view
|
||||
)
|
||||
with pytest.raises(ValueError, match="query cannot be combined"):
|
||||
if sync:
|
||||
create("invalid", query="SELECT * FROM people", **clauses)
|
||||
else:
|
||||
await create("invalid", query="SELECT * FROM people", **clauses)
|
||||
with pytest.raises(ValueError, match="either source or query"):
|
||||
if sync:
|
||||
create("missing")
|
||||
else:
|
||||
await create("missing")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"SELECT kind, count(*) AS n FROM events GROUP BY kind",
|
||||
"SELECT id, c.text FROM docs, chunk(body) AS c",
|
||||
"SELECT id, tag FROM events, UNNEST(tags) AS tag",
|
||||
"SELECT a.id FROM a JOIN b ON a.id = b.id",
|
||||
],
|
||||
)
|
||||
async def test_remote_create_forwards_defining_query(sync, query):
|
||||
native = CapturingCreateConnection()
|
||||
db = AsyncConnection(native)
|
||||
if sync:
|
||||
remote = RemoteDBConnection.__new__(RemoteDBConnection)
|
||||
remote._conn = db
|
||||
job = remote.create_materialized_view_async("result", query=query)
|
||||
job.wait()
|
||||
else:
|
||||
job = await db.create_materialized_view_async("result", query=query)
|
||||
await job.wait()
|
||||
assert native.calls[0][0:2] == ("result", None)
|
||||
assert native.calls[0][2]["query"] == query
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
def test_query_with_no_data_and_invalid_query(tmp_path, background):
|
||||
db = make_db(tmp_path)
|
||||
query = "SELECT name FROM people WHERE age >= 18"
|
||||
if background:
|
||||
db.create_materialized_view_async(
|
||||
"adults", query=query, with_no_data=True
|
||||
).wait()
|
||||
view = db.open_materialized_view("adults")
|
||||
else:
|
||||
view = db.create_materialized_view("adults", query=query, with_no_data=True)
|
||||
assert view.table.count_rows() == 0
|
||||
view.refresh()
|
||||
assert view.table.count_rows() == 2
|
||||
create = (
|
||||
db.create_materialized_view_async if background else db.create_materialized_view
|
||||
)
|
||||
error = JobFailedError if background else ValueError
|
||||
with pytest.raises(error, match="unsupported clause"):
|
||||
result = create("invalid", query="SELECT * FROM people ORDER BY age")
|
||||
if background:
|
||||
result.wait()
|
||||
assert "invalid" not in db.table_names()
|
||||
|
||||
@@ -278,7 +278,7 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path):
|
||||
|
||||
# with_row_id is unsupported by the LSM scanner; on an RTE table the default
|
||||
# (auto-routed) read hard-errors instead of silently reading a stale base.
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(Exception, match=r"with_row_id.*use_rte\(false\)"):
|
||||
table.search().with_row_id(True).to_arrow()
|
||||
|
||||
# use_rte(False) is the escape hatch: it reads the base table only.
|
||||
@@ -563,19 +563,28 @@ def test_lsm_read_time_travel_errors(tmp_path):
|
||||
assert sorted(base["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_take_row_ids_errors(tmp_path):
|
||||
@pytest.mark.parametrize("with_row_id", [False, True])
|
||||
@pytest.mark.parametrize("use_rte", [None, True])
|
||||
def test_lsm_read_take_row_ids_errors(tmp_path, with_row_id, use_rte):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
_lsm_upsert(table, [4])
|
||||
# take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid,
|
||||
# so it hard-errors instead of failing with an opaque column-not-found error.
|
||||
with pytest.raises(Exception, match="row id"):
|
||||
table.take_row_ids([0, 1]).to_arrow()
|
||||
# Automatic and explicit RTE routing must explain the unsupported take,
|
||||
# including when row IDs are only requested internally for ordering.
|
||||
take = table.take_row_ids([1, 0, 1, 2**64 - 1], with_row_id=with_row_id)
|
||||
if use_rte is not None:
|
||||
take = take.use_rte(use_rte)
|
||||
with pytest.raises(Exception, match=r"take by row id.*use_rte\(false\)"):
|
||||
take.to_arrow()
|
||||
# use_rte(False) is the escape hatch: it reads the base table.
|
||||
base = table.take_row_ids([0, 1]).use_rte(False).to_arrow()
|
||||
assert base.num_rows == 2
|
||||
base = take.use_rte(False).to_arrow()
|
||||
assert base["id"].to_pylist() == [2, 1, 2]
|
||||
assert base["value"].to_pylist() == [1, 0, 1]
|
||||
assert ("_rowid" in base.column_names) == with_row_id
|
||||
if with_row_id:
|
||||
assert base["_rowid"].to_pylist() == [1, 0, 1]
|
||||
|
||||
|
||||
def test_lsm_read_fts_postfilter_errors(tmp_path):
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
import tempfile
|
||||
import shutil
|
||||
import importlib
|
||||
import asyncio
|
||||
import pickle
|
||||
import warnings
|
||||
import http.server
|
||||
import json
|
||||
@@ -16,8 +18,10 @@ import copy
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
from lance_namespace import DescribeTableResponse
|
||||
from utils import start_server_thread
|
||||
from lancedb.listing import AsyncListing, Listing
|
||||
from lancedb.index import FTS
|
||||
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
|
||||
from lancedb.namespace import (
|
||||
_MAX_QUERY_K,
|
||||
@@ -25,7 +29,7 @@ from lancedb.namespace import (
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import Query
|
||||
from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
|
||||
@@ -34,6 +38,122 @@ PUSHDOWN_DATA = pa.table(
|
||||
)
|
||||
|
||||
|
||||
class _RefreshNamespaceWithExpiringOptions(LanceNamespace):
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
|
||||
def namespace_id(self):
|
||||
return f"refresh-test:{self.root}"
|
||||
|
||||
def describe_table(self, request):
|
||||
from pathlib import Path
|
||||
|
||||
return DescribeTableResponse(
|
||||
location=str(Path(self.root) / "t.lance"),
|
||||
storage_options={"vended": "fresh", "expires_at_millis": "1"},
|
||||
)
|
||||
|
||||
|
||||
class _DeclaredNamespaceWithoutProperties(LanceNamespace):
|
||||
root = None
|
||||
|
||||
def __init__(self):
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
self.client = DirectoryNamespace(root=self.root)
|
||||
|
||||
def namespace_id(self):
|
||||
return self.client.namespace_id()
|
||||
|
||||
def describe_table(self, request):
|
||||
return self.client.describe_table(request)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]])
|
||||
async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
|
||||
class ExistenceNamespace(LanceNamespace):
|
||||
def namespace_id(self):
|
||||
return "existence-test"
|
||||
|
||||
def table_exists(self, request):
|
||||
if request.id == ["missing"]:
|
||||
raise TableNotFoundError("Table not found")
|
||||
|
||||
def describe_table(self, request):
|
||||
raise AssertionError("Custom existence checks must not open tables")
|
||||
|
||||
namespace = ExistenceNamespace()
|
||||
db = LanceNamespaceDBConnection(namespace)
|
||||
adb = lancedb.AsyncLanceNamespaceDBConnection(namespace)
|
||||
assert db.table_exists(table_id) is (table_id != ["missing"])
|
||||
assert await adb.table_exists(table_id) is (table_id != ["missing"])
|
||||
|
||||
|
||||
def test_table_pickle_rejects_custom_namespace_connection(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
|
||||
"t", [{"id": 1}]
|
||||
)
|
||||
|
||||
class UnserializableNamespace(LanceNamespace):
|
||||
def __init__(self, root):
|
||||
from threading import Lock
|
||||
|
||||
self.client = DirectoryNamespace(root=str(root))
|
||||
self.lock = Lock()
|
||||
|
||||
def namespace_id(self):
|
||||
return self.client.namespace_id()
|
||||
|
||||
def describe_table(self, request):
|
||||
return self.client.describe_table(request)
|
||||
|
||||
db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path))
|
||||
table = db.open_table("t")
|
||||
|
||||
with pytest.raises(TypeError, match="namespace"):
|
||||
pickle.dumps(table)
|
||||
|
||||
|
||||
def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path):
|
||||
lancedb.connect(tmp_path).create_table("t", [{"id": 1}])
|
||||
db = lancedb.connect_namespace(
|
||||
f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)}
|
||||
)
|
||||
table = db.open_table("t", storage_options={"caller_only": "keep"})
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_only"] == "keep"
|
||||
assert options["vended"] == "fresh"
|
||||
|
||||
|
||||
def test_table_pickle_allows_declared_namespace_without_properties(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
|
||||
"t", [{"id": 1}]
|
||||
)
|
||||
_DeclaredNamespaceWithoutProperties.root = str(tmp_path)
|
||||
try:
|
||||
impl = f"{__name__}._DeclaredNamespaceWithoutProperties"
|
||||
db = LanceNamespaceDBConnection(
|
||||
_DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl
|
||||
)
|
||||
table = db.open_table("t")
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1]
|
||||
finally:
|
||||
_DeclaredNamespaceWithoutProperties.root = None
|
||||
|
||||
|
||||
class TestNamespaceCreateTableOptions:
|
||||
@pytest.mark.parametrize("version", ["legacy", "stable"])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
@@ -287,6 +407,328 @@ def paginated_rest_namespace():
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path):
|
||||
from time import time
|
||||
|
||||
local = lancedb.connect(tmp_path)
|
||||
local.create_table("t", [{"id": 1}])
|
||||
location = str(tmp_path / "t.lance")
|
||||
ipc = _ipc_file(pa.table({"id": [42]}))
|
||||
seen = []
|
||||
current_options = {
|
||||
"block_size": "4096",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
seen.append(path)
|
||||
if path.endswith("/describe"):
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": current_options}
|
||||
).encode()
|
||||
content_type = "application/json"
|
||||
elif path.endswith("/query"):
|
||||
body = ipc
|
||||
content_type = "application/vnd.apache.arrow.file"
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": f"http://127.0.0.1:{server.server_port}"},
|
||||
namespace_client_pushdown_operations=["QueryTable"],
|
||||
)
|
||||
table = db.open_table("t")
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
seen.clear()
|
||||
assert restored.search().limit(1).to_list() == [{"id": 42}]
|
||||
assert seen == ["/v1/table/t/query"]
|
||||
|
||||
current_options = {
|
||||
"block_size": "8192",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
}
|
||||
assert table.latest_storage_options()["block_size"] == "8192"
|
||||
assert restored.latest_storage_options()["block_size"] == "8192"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path):
|
||||
from time import time
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
current_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if not (path.endswith("/declare") or path.endswith("/describe")):
|
||||
self.send_error(404)
|
||||
return
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": current_options}
|
||||
).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest", {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
)
|
||||
table = db.create_table("t", [{"id": 1}])
|
||||
payload = pickle.dumps(table)
|
||||
assert b"short-lived" not in payload
|
||||
restored = pickle.loads(payload)
|
||||
|
||||
current_options = {}
|
||||
assert table.latest_storage_options() == {}
|
||||
assert restored.latest_storage_options() == {}
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entrypoint", ["create", "open"])
|
||||
def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint):
|
||||
from time import time
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
caller_options = {"caller_option": "kept", "conflict": "caller"}
|
||||
vended_options = {
|
||||
"vended_1": "old",
|
||||
"conflict": "vended",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if path.endswith("/declare") or path.endswith("/describe"):
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": vended_options}
|
||||
).encode()
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": f"http://127.0.0.1:{server.server_port}"},
|
||||
)
|
||||
if entrypoint == "create":
|
||||
table = db.create_table(
|
||||
"t", [{"id": 1}], storage_options=caller_options
|
||||
)
|
||||
else:
|
||||
db.create_table("t", [{"id": 1}])
|
||||
table = db.open_table("t", storage_options=caller_options)
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_option"] == "kept"
|
||||
assert options["conflict"] == "vended"
|
||||
|
||||
vended_options.update(
|
||||
{
|
||||
"vended_2": "new",
|
||||
"conflict": "vended-new",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
}
|
||||
)
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_option"] == "kept"
|
||||
assert options["vended_2"] == "new"
|
||||
assert options["conflict"] == "vended-new"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_namespace_open_uses_explicit_storage_options_provider(tmp_path):
|
||||
from time import time
|
||||
|
||||
from lancedb._lancedb import connect_namespace as connect_namespace_inner
|
||||
from lancedb.db import AsyncConnection
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
seed_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if not (path.endswith("/declare") or path.endswith("/describe")):
|
||||
self.send_error(404)
|
||||
return
|
||||
result = {"location": location, "storage_options": seed_options}
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class ExplicitClient(LanceNamespace):
|
||||
calls = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return "explicit-storage-options-provider"
|
||||
|
||||
def describe_table(self, request):
|
||||
self.calls += 1
|
||||
return DescribeTableResponse(
|
||||
location=location,
|
||||
storage_options={
|
||||
"explicit_provider": "fresh",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
},
|
||||
)
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
db = lancedb.connect_namespace("rest", properties)
|
||||
db.create_table("t", [{"id": 1}])
|
||||
|
||||
async def check():
|
||||
connection = AsyncConnection(
|
||||
connect_namespace_inner("rest", properties)
|
||||
)
|
||||
client = ExplicitClient()
|
||||
table = await connection.open_table("t", namespace_client=client)
|
||||
options = await table.latest_storage_options()
|
||||
assert client.calls > 0
|
||||
assert options["explicit_provider"] == "fresh"
|
||||
|
||||
asyncio.run(check())
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_namespace_create_without_seed_uses_connection_provider(tmp_path):
|
||||
from time import time
|
||||
|
||||
from lancedb._lancedb import connect_namespace as connect_namespace_inner
|
||||
from lancedb.db import AsyncConnection
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
seed_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
result = {"location": location}
|
||||
if path.endswith("/describe"):
|
||||
result["storage_options"] = seed_options
|
||||
elif not path.endswith("/declare"):
|
||||
self.send_error(404)
|
||||
return
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class ExplicitClient(LanceNamespace):
|
||||
calls = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return "explicit-storage-options-provider"
|
||||
|
||||
def describe_table(self, request):
|
||||
self.calls += 1
|
||||
return DescribeTableResponse(
|
||||
location=location,
|
||||
storage_options={
|
||||
"explicit_provider": "fresh",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
},
|
||||
)
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
|
||||
async def check():
|
||||
connection = AsyncConnection(
|
||||
connect_namespace_inner("rest", properties)
|
||||
)
|
||||
client = ExplicitClient()
|
||||
table = await connection.create_table(
|
||||
"t", [{"id": 1}], namespace_client=client
|
||||
)
|
||||
options = await table.latest_storage_options()
|
||||
assert client.calls == 0
|
||||
assert options["vended_seed"] == "short-lived"
|
||||
|
||||
asyncio.run(check())
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("namespace_path", [[], ["n"]])
|
||||
async def test_rest_namespace_table_names_collects_pages(
|
||||
@@ -411,8 +853,16 @@ class TestNamespaceConnection:
|
||||
assert "test_ns" in db.list_namespaces().namespaces
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
db.create_table("root_table", schema=schema)
|
||||
assert db.table_exists(["root_table"]) is True
|
||||
assert "root_table" in db
|
||||
assert db.table_exists(["missing"]) is False
|
||||
assert "missing" not in db
|
||||
table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"])
|
||||
assert table.namespace == ["test_ns"]
|
||||
assert db.table_exists(["test_ns", "test_table"]) is True
|
||||
assert db.table_exists(["test_ns", "missing"]) is False
|
||||
assert "test_table" not in db
|
||||
assert "test_table" in db.table_names(namespace_path=["test_ns"])
|
||||
assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables
|
||||
|
||||
@@ -420,7 +870,10 @@ class TestNamespaceConnection:
|
||||
assert opened.namespace == ["test_ns"]
|
||||
|
||||
db.drop_table("test_table", namespace_path=["test_ns"])
|
||||
assert db.table_exists(["test_ns", "test_table"]) is False
|
||||
assert db.list_tables(namespace_path=["test_ns"]).tables == []
|
||||
db.drop_table("root_table")
|
||||
assert "root_table" not in db
|
||||
db.drop_namespace(["test_ns"])
|
||||
assert "test_ns" not in db.list_namespaces().namespaces
|
||||
|
||||
@@ -942,12 +1395,18 @@ class TestAsyncNamespaceConnection:
|
||||
assert "test_ns" in (await db.list_namespaces()).namespaces
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
await db.create_table("root_table", schema=schema)
|
||||
assert await db.table_exists(["root_table"]) is True
|
||||
assert await db.table_exists(["missing"]) is False
|
||||
table = await db.create_table(
|
||||
"test_table", schema=schema, namespace_path=["test_ns"]
|
||||
)
|
||||
assert table._namespace_path == ["test_ns"]
|
||||
assert table._namespace_client is None
|
||||
assert table._route_pushdown_to_rust is True
|
||||
assert await db.table_exists(["test_ns", "test_table"]) is True
|
||||
assert await db.table_exists(["test_ns", "missing"]) is False
|
||||
assert await db.table_exists(["test_table"]) is False
|
||||
assert "test_table" in await db.table_names(namespace_path=["test_ns"])
|
||||
assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables
|
||||
|
||||
@@ -955,7 +1414,10 @@ class TestAsyncNamespaceConnection:
|
||||
assert opened._namespace_path == ["test_ns"]
|
||||
|
||||
await db.drop_table("test_table", namespace_path=["test_ns"])
|
||||
assert await db.table_exists(["test_ns", "test_table"]) is False
|
||||
assert (await db.list_tables(namespace_path=["test_ns"])).tables == []
|
||||
await db.drop_table("root_table")
|
||||
assert await db.table_exists(["root_table"]) is False
|
||||
await db.drop_namespace(["test_ns"])
|
||||
assert "test_ns" not in (await db.list_namespaces()).namespaces
|
||||
|
||||
@@ -1310,6 +1772,48 @@ class TestPushdownOperations:
|
||||
assert request.maximum_nprobes == 0
|
||||
assert request.to_dict()["maximum_nprobes"] == 0
|
||||
|
||||
def test_lance_table_order_by_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = table._execute_query(
|
||||
Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
|
||||
).read_all()
|
||||
|
||||
# Pushing this query down would drop order_by and return id 3.
|
||||
assert result.column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
).read_all()
|
||||
|
||||
# The namespace request has no scan-order field. Local execution keeps
|
||||
# membership order, projection and limit; a dropped order or a sort
|
||||
# would return [1, 3] or [1, 2].
|
||||
assert result.column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAsyncPushdownOperations:
|
||||
@@ -1372,6 +1876,47 @@ class TestAsyncPushdownOperations:
|
||||
assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K]
|
||||
assert all(r.k <= 2**31 - 1 for r in namespace_client.requests)
|
||||
|
||||
async def test_async_table_order_by_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = await lancedb.connect_async(str(tmp_path / "db"))
|
||||
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = await table._execute_query(
|
||||
Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
|
||||
)
|
||||
|
||||
# Pushing this query down would drop order_by and return id 3.
|
||||
batches = await result.read_all()
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = await lancedb.connect_async(str(tmp_path / "db"))
|
||||
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
await table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = await table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
)
|
||||
|
||||
batches = await result.read_all()
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query_kwargs",
|
||||
[
|
||||
@@ -1483,3 +2028,42 @@ def test_python_namespace_attribute_access(tmp_path):
|
||||
# Missing dunder lookups still raise, so copy/hasattr probes work.
|
||||
assert not hasattr(request, "__missing_dunder__")
|
||||
assert copy.deepcopy(request) == request
|
||||
|
||||
|
||||
@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
|
||||
def test_namespace_fts_operator_is_preserved(columns):
|
||||
request = _query_to_namespace_request(
|
||||
["matches"],
|
||||
Query(
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query="gripper closed", columns=columns, operator="AND"
|
||||
)
|
||||
),
|
||||
)
|
||||
structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
|
||||
if columns and len(columns) > 1:
|
||||
assert all(
|
||||
query["operator"] == "And"
|
||||
for query in structured["multi_match"]["match_queries"]
|
||||
)
|
||||
else:
|
||||
assert structured["match"]["operator"] == "And"
|
||||
assert structured["match"].get("column") == (columns[0] if columns else None)
|
||||
|
||||
|
||||
def test_namespace_fts_count_fast_search(tmp_path):
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace("dir", properties)
|
||||
table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
pushed = lancedb.connect_namespace(
|
||||
"dir", properties, namespace_client_pushdown_operations=["QueryTable"]
|
||||
).open_table("matches")
|
||||
assert pushed.search("gripper", query_type="fts").count_rows() == 20
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.use_rte(False).count_rows() == 15
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.count_rows() == 15
|
||||
assert len(query.limit(100).to_list()) == 15
|
||||
|
||||
@@ -7,7 +7,13 @@ import pytest
|
||||
|
||||
from lancedb import DBConnection, Table, connect
|
||||
from lancedb.background_loop import LOOP
|
||||
from lancedb.permutation import Permutation, Permutations, permutation_builder
|
||||
from lancedb.permutation import (
|
||||
DEFAULT_BATCH_SIZE,
|
||||
Permutation,
|
||||
Permutations,
|
||||
Transforms,
|
||||
permutation_builder,
|
||||
)
|
||||
from utils import (
|
||||
MockPermutationServer,
|
||||
assert_server_safe_row_id_requests,
|
||||
@@ -81,6 +87,43 @@ def test_pickled_permutation_reads_pinned_version(tmp_path):
|
||||
assert sorted(row["idx"] for row in rows) == list(range(20))
|
||||
|
||||
|
||||
def test_builder_copy_is_shallow_and_does_not_materialize(
|
||||
some_table: Table, some_perm_table: Table, monkeypatch
|
||||
):
|
||||
"""The with_* builders use copy.copy, which must stay a shallow copy.
|
||||
|
||||
Without ``Permutation.__copy__`` the copy falls back to the pickle path,
|
||||
which materializes the permutation table with ``to_arrow()`` before
|
||||
rebuilding the base table and reader. That is expensive for in-memory
|
||||
tables and fails for remote permutation tables.
|
||||
"""
|
||||
permutation = Permutation.from_tables(some_table, some_perm_table)
|
||||
|
||||
def fail_materialize(*args, **kwargs):
|
||||
raise AssertionError("copy.copy must not materialize the permutation table")
|
||||
|
||||
def fail_getstate(_self):
|
||||
raise AssertionError("copy.copy must not pickle the permutation")
|
||||
|
||||
monkeypatch.setattr(permutation.permutation_table, "to_arrow", fail_materialize)
|
||||
monkeypatch.setattr(Permutation, "__getstate__", fail_getstate)
|
||||
|
||||
formatted = permutation.with_format("arrow")
|
||||
assert formatted is not permutation
|
||||
assert formatted.transform_fn is Transforms.arrow2arrow
|
||||
assert permutation.transform_fn is Transforms.arrow2python
|
||||
assert formatted.base_table is permutation.base_table
|
||||
assert formatted.permutation_table is permutation.permutation_table
|
||||
assert formatted.reader is permutation.reader
|
||||
|
||||
resized = permutation.with_batch_size(7)
|
||||
assert resized.batch_size == 7
|
||||
assert permutation.batch_size == DEFAULT_BATCH_SIZE
|
||||
assert resized.selection is permutation.selection
|
||||
resized.selection = {"id": "id"}
|
||||
assert permutation.selection is not resized.selection
|
||||
|
||||
|
||||
def test_split_random_counts(mem_db):
|
||||
"""Test random splitting with absolute counts."""
|
||||
tbl = mem_db.create_table(
|
||||
@@ -275,6 +318,41 @@ def test_split_hash(mem_db):
|
||||
assert data["split_id"] == data2["split_id"] # Should be identical
|
||||
|
||||
|
||||
def test_split_hash_default_discard_weight_matches_zero(mem_db):
|
||||
"""Omitting discard_weight must assign every row like discard_weight=0."""
|
||||
tbl = mem_db.create_table(
|
||||
"test_table",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(100),
|
||||
"category": (["A", "B", "C"] * 34)[:100],
|
||||
"value": range(100),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
default = (
|
||||
permutation_builder(tbl)
|
||||
.split_hash(["category"], [1, 1], split_names=["train", "test"])
|
||||
.execute()
|
||||
)
|
||||
explicit_zero = (
|
||||
permutation_builder(tbl)
|
||||
.split_hash(
|
||||
["category"], [1, 1], discard_weight=0, split_names=["train", "test"]
|
||||
)
|
||||
.execute()
|
||||
)
|
||||
|
||||
default_data = default.search(None).to_arrow().to_pydict()
|
||||
explicit_data = explicit_zero.search(None).to_arrow().to_pydict()
|
||||
assert default.count_rows() == 100
|
||||
assert default.count_rows() == explicit_zero.count_rows()
|
||||
assert dict(zip(default_data["row_id"], default_data["split_id"])) == dict(
|
||||
zip(explicit_data["row_id"], explicit_data["split_id"])
|
||||
)
|
||||
|
||||
|
||||
def test_split_hash_with_discard(mem_db):
|
||||
"""Test hash-based splitting with discard weight."""
|
||||
tbl = mem_db.create_table(
|
||||
@@ -1146,6 +1224,31 @@ def test_transform_fn_pandas(mem_db):
|
||||
assert isinstance(result, pd.DataFrame)
|
||||
|
||||
|
||||
def test_numpy_format_mixed_columns_is_object_ndarray(mem_db):
|
||||
pytest.importorskip("pandas")
|
||||
import numpy as np
|
||||
|
||||
tbl = mem_db.create_table(
|
||||
"test_table",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(3),
|
||||
"vector": pa.array(
|
||||
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(tbl).with_format("numpy")
|
||||
result = next(permutation.iter(2, skip_last_batch=False))
|
||||
|
||||
assert isinstance(result, np.ndarray)
|
||||
assert result.dtype == object
|
||||
assert result.shape == (2, 2)
|
||||
np.testing.assert_array_equal(result[0, 1], [1.0, 2.0])
|
||||
|
||||
|
||||
def test_custom_transform(mem_db):
|
||||
tbl = mem_db.create_table(
|
||||
"test_table", pa.table({"id": range(10), "value": range(10)})
|
||||
|
||||
@@ -69,6 +69,36 @@ def _blob_query_data():
|
||||
)
|
||||
|
||||
|
||||
def _fragment_query_data():
|
||||
return pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
||||
"text": pa.array(["one", "two", "three", "four"], pa.utf8()),
|
||||
"vector": pa.array(
|
||||
[[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]],
|
||||
type=pa.list_(pa.float32(), list_size=2),
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _fragment_query_table(db, name):
|
||||
data = _fragment_query_data()
|
||||
table = db.create_table(name, data.slice(0, 2))
|
||||
table.add(data.slice(2, 2))
|
||||
return table
|
||||
|
||||
|
||||
def _apply_fragment_restriction(query, restriction, fragment):
|
||||
if restriction == "ids":
|
||||
return query.fragment_ids([fragment.fragment_id])
|
||||
if restriction == "empty":
|
||||
return query.fragment_ids([])
|
||||
if restriction == "fragments":
|
||||
return query.with_fragments([fragment])
|
||||
raise AssertionError(f"unknown restriction: {restriction}")
|
||||
|
||||
|
||||
def _create_blob_v2_query_table(db, name):
|
||||
schema = pa.schema(
|
||||
[
|
||||
@@ -348,7 +378,7 @@ def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
||||
def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
|
||||
def test_plain_scan_query_to_pandas_blob_mode_uses_native_path(
|
||||
tmp_db, monkeypatch, blob_mode
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
@@ -362,7 +392,8 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
|
||||
def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("to_arrow should not be called before native pandas")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
if blob_mode == "descriptions":
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
df = query.to_pandas(blob_mode=blob_mode)
|
||||
|
||||
@@ -434,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db):
|
||||
)
|
||||
assert df_by_fragment["id"].tolist() == [1, 2]
|
||||
|
||||
empty = (
|
||||
table.search()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([])
|
||||
.to_pandas(blob_mode="descriptions")
|
||||
)
|
||||
assert empty.empty
|
||||
with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"):
|
||||
(
|
||||
table.search()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([999])
|
||||
.to_pandas(blob_mode="descriptions")
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"terminal",
|
||||
[
|
||||
"to_arrow",
|
||||
"to_batches",
|
||||
"to_pandas",
|
||||
"to_polars",
|
||||
"to_list",
|
||||
"explain_plan",
|
||||
"analyze_plan",
|
||||
],
|
||||
)
|
||||
def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal):
|
||||
pytest.importorskip("lance")
|
||||
table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}")
|
||||
fragment_id = table.to_lance().get_fragments()[0].fragment_id
|
||||
query = table.search().fragment_ids([fragment_id])
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
getattr(query, terminal)()
|
||||
|
||||
|
||||
def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db):
|
||||
pytest.importorskip("lance")
|
||||
table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments")
|
||||
fragment = table.to_lance().get_fragments()[0]
|
||||
|
||||
for query in (
|
||||
table.search().with_fragments([fragment]),
|
||||
table.search([0.0, 0.0]).with_fragments([fragment]),
|
||||
):
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
||||
def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction):
|
||||
pytest.importorskip("lance")
|
||||
table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}")
|
||||
table.create_index("text", config=FTS(with_position=False))
|
||||
fragment = table.to_lance().get_fragments()[1]
|
||||
query = _apply_fragment_restriction(
|
||||
table.search("one", query_type="fts"), restriction, fragment
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.count_rows()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"terminal",
|
||||
[
|
||||
"to_arrow",
|
||||
"to_batches",
|
||||
"to_pandas",
|
||||
"to_polars",
|
||||
"to_list",
|
||||
"explain_plan",
|
||||
"analyze_plan",
|
||||
],
|
||||
)
|
||||
async def test_async_fragment_constraints_fail_loud_on_unsupported_paths(
|
||||
tmp_db_async, terminal
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
f"async_fragment_guard_{terminal}", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
query = table.query().fragment_ids([fragments[0].fragment_id])
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await getattr(query, terminal)()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries(
|
||||
tmp_db_async,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"async_fragment_guard_with_fragments", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
|
||||
for query in (
|
||||
table.query().with_fragments([fragments[0]]),
|
||||
table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]),
|
||||
):
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"async_fragment_supported",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
|
||||
df = await (
|
||||
table.query()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([fragments[1].fragment_id])
|
||||
.to_pandas(blob_mode="descriptions")
|
||||
)
|
||||
|
||||
assert df["id"].tolist() == [3, 4]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
||||
async def test_async_fts_count_rows_rejects_fragment_constraints(
|
||||
tmp_db_async, restriction
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
f"async_fts_count_rows_{restriction}", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.create_index("text", config=FTS(with_position=False))
|
||||
fragment = (await table.to_lance()).get_fragments()[1]
|
||||
query = _apply_fragment_restriction(
|
||||
table.query().nearest_to_text("one"), restriction, fragment
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.count_rows()
|
||||
|
||||
transitioned = _apply_fragment_restriction(
|
||||
table.query(), restriction, fragment
|
||||
).nearest_to_text("one")
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await transitioned.count_rows()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
||||
@pytest.mark.parametrize(
|
||||
"transition",
|
||||
["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"],
|
||||
)
|
||||
async def test_async_fragment_constraints_survive_query_transitions(
|
||||
tmp_db_async, transition, restriction
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
f"async_transition_{transition}_{restriction}", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.create_index("text", config=FTS(with_position=False))
|
||||
fragment = (await table.to_lance()).get_fragments()[1]
|
||||
|
||||
if transition == "query_to_vector":
|
||||
query = _apply_fragment_restriction(
|
||||
table.query(), restriction, fragment
|
||||
).nearest_to([0.0, 0.0])
|
||||
elif transition == "query_to_fts":
|
||||
query = _apply_fragment_restriction(
|
||||
table.query(), restriction, fragment
|
||||
).nearest_to_text("one")
|
||||
elif transition == "fts_to_hybrid":
|
||||
query = _apply_fragment_restriction(
|
||||
table.query().nearest_to_text("one"), restriction, fragment
|
||||
).nearest_to([0.0, 0.0])
|
||||
else:
|
||||
query = _apply_fragment_restriction(
|
||||
table.query().nearest_to([0.0, 0.0]), restriction, fragment
|
||||
).nearest_to_text("one")
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async):
|
||||
@@ -488,7 +720,7 @@ async def test_async_plain_scan_query_to_pandas_blob_bytes_projection(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
||||
async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
|
||||
async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path(
|
||||
tmp_db_async, monkeypatch, blob_mode
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
@@ -502,7 +734,8 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow
|
||||
async def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("to_arrow should not be called before native pandas")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
if blob_mode == "descriptions":
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
df = await query.to_pandas(blob_mode=blob_mode)
|
||||
|
||||
@@ -541,12 +774,14 @@ def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db):
|
||||
df = query.to_pandas(blob_mode="descriptions")
|
||||
assert df["blob"].tolist() == [{"position": 0, "size": 3}]
|
||||
|
||||
with pytest.raises(ValueError, match="legacy blob columns"):
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
||||
query.to_pandas(blob_mode="bytes")
|
||||
with pytest.raises(ValueError, match="legacy blob columns"):
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
||||
query.to_arrow(blob_mode="bytes")
|
||||
with pytest.raises(ValueError, match="legacy blob columns"):
|
||||
table.to_arrow(blob_mode="bytes")
|
||||
table_arrow = table.to_arrow(blob_mode="bytes")
|
||||
assert table_arrow.schema.field("blob").type == pa.large_binary()
|
||||
assert "_rowid" not in table_arrow.column_names
|
||||
assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"]
|
||||
assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [
|
||||
b"one",
|
||||
b"two",
|
||||
@@ -740,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
|
||||
|
||||
df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
|
||||
assert set(df["blob"]) == {b"two", b"three"}
|
||||
ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["blob"].tolist() == [b"three", b"two"]
|
||||
|
||||
|
||||
def test_order_by_plain_query(mem_db):
|
||||
@@ -807,6 +1046,308 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection):
|
||||
]
|
||||
|
||||
|
||||
def test_order_by_accepts_strings_tuples_and_dicts(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"test_order_by_forms",
|
||||
pa.table(
|
||||
{
|
||||
"group": [1, 1, 1, 2],
|
||||
"score": [None, 1.0, 1.0, 0.5],
|
||||
"name": ["z", "b", "a", "c"],
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
rows = (
|
||||
table.search()
|
||||
.order_by(
|
||||
[
|
||||
"group",
|
||||
("score", "desc"),
|
||||
{"column_name": "name", "ascending": True},
|
||||
]
|
||||
)
|
||||
.select(["name"])
|
||||
.to_list()
|
||||
)
|
||||
assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}]
|
||||
|
||||
# A bare tuple is one direction pair; a list holds separate orderings.
|
||||
assert table.search().order_by("name").select(["name"]).to_list() == [
|
||||
{"name": "a"},
|
||||
{"name": "b"},
|
||||
{"name": "c"},
|
||||
{"name": "z"},
|
||||
]
|
||||
assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [
|
||||
{"name": "z"},
|
||||
{"name": "c"},
|
||||
{"name": "b"},
|
||||
{"name": "a"},
|
||||
]
|
||||
assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [
|
||||
{"name": "a"},
|
||||
{"name": "b"},
|
||||
{"name": "z"},
|
||||
{"name": "c"},
|
||||
]
|
||||
|
||||
|
||||
def test_order_by_clears_with_none_and_empty_list(mem_db):
|
||||
table = mem_db.create_table("test_order_by_clear", [{"name": "a"}])
|
||||
|
||||
query = table.search().order_by("name")
|
||||
assert query.to_query_object().order_by is not None
|
||||
assert query.order_by(None).to_query_object().order_by is None
|
||||
assert query.order_by([]).to_query_object().order_by is None
|
||||
|
||||
|
||||
def test_scan_in_order_plain_query(tmp_db):
|
||||
table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]}))
|
||||
table.add(pa.table({"id": [2, 3]}))
|
||||
table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
assert len(fragments) == 3, "the test needs real multi-fragment data"
|
||||
|
||||
version = table.version
|
||||
table.checkout(version)
|
||||
|
||||
default = table.search().select(["id"]).to_arrow()["id"].to_pylist()
|
||||
assert default == [0, 1, 2, 3, 4, 5]
|
||||
assert table.search().to_query_object().scan_in_order is None
|
||||
|
||||
ordered = table.search().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
repeated = table.search().scan_in_order(True).select(["id"]).to_arrow()
|
||||
assert repeated.equals(ordered)
|
||||
|
||||
unordered = (
|
||||
table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist()
|
||||
)
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
sorted_desc = (
|
||||
table.search()
|
||||
.scan_in_order(False)
|
||||
.order_by(("id", "desc"))
|
||||
.select(["id"])
|
||||
.to_arrow()["id"]
|
||||
.to_pylist()
|
||||
)
|
||||
assert sorted_desc == [5, 4, 3, 2, 1, 0]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
table.search().scan_in_order().order_by("id").to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection):
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_async", pa.table({"id": [0, 1]})
|
||||
)
|
||||
await table.add(pa.table({"id": [2, 3]}))
|
||||
await table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
assert len((await table.to_lance()).get_fragments()) == 3
|
||||
version = await table.version()
|
||||
await table.checkout(version)
|
||||
|
||||
ordered = await table.query().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
assert table.query().to_query_object().scan_in_order is None
|
||||
|
||||
unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[
|
||||
"id"
|
||||
].to_pylist()
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
await table.query().scan_in_order().order_by("id").to_arrow()
|
||||
with pytest.raises(ValueError, match="ranked results"):
|
||||
await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ordered", [False, True])
|
||||
def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
f"scan_in_order_scanner_{ordered}",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
|
||||
query = table.search().select(["id", "blob"]).scan_in_order(ordered)
|
||||
|
||||
def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("scanner-backed pandas must not collect through to_arrow")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
dataset = table.to_lance()
|
||||
dataset_cls = type(dataset)
|
||||
real_scanner = dataset_cls.scanner
|
||||
captured = {}
|
||||
|
||||
def capture_scanner(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return real_scanner(self, **kwargs)
|
||||
|
||||
monkeypatch.setattr(dataset_cls, "scanner", capture_scanner)
|
||||
|
||||
df = query.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
|
||||
assert captured["scan_in_order"] is ordered
|
||||
assert captured.get("use_scalar_index") is (False if ordered else None)
|
||||
assert sorted(df["id"].tolist()) == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("storage_version", ["legacy", "stable"])
|
||||
def test_scan_in_order_indexed_filter_preserves_manifest_order(
|
||||
tmp_path, storage_version
|
||||
):
|
||||
lance = pytest.importorskip("lance")
|
||||
data = pa.table({"id": list(range(20)), "value": list(range(20))})
|
||||
dataset = lance.write_dataset(
|
||||
data,
|
||||
tmp_path / "t.lance",
|
||||
data_storage_version=storage_version,
|
||||
max_rows_per_file=10,
|
||||
)
|
||||
dataset.create_scalar_index("value", "BTREE")
|
||||
version_before_update = dataset.version
|
||||
dataset.update({"value": "100"}, where="id = 0")
|
||||
|
||||
table = lancedb.connect(str(tmp_path)).open_table("t")
|
||||
for version in (version_before_update, dataset.version):
|
||||
table.checkout(version)
|
||||
base = table.search().scan_in_order(True).select(["id"]).limit(100)
|
||||
expected = base.to_arrow()["id"].to_pylist()
|
||||
actual = base.where("value < 1000").to_arrow()["id"].to_pylist()
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
"scan_in_order_fragments",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
table.checkout(table.version)
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
(
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.with_fragments(reversed_fragments)
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
# fragment_ids is already resolved from the manifest and stays ordered.
|
||||
df_by_id = (
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(
|
||||
tmp_db_async,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_fragments_async",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.checkout(await table.version())
|
||||
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.with_fragments(fragments[::-1])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
df_by_id = await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_order_by_rejects_invalid_input_early(mem_db):
|
||||
table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
|
||||
|
||||
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
||||
table.search().order_by([{"column": "name", "ascending": True}])
|
||||
with pytest.raises(ValueError, match="missing 'column_name'"):
|
||||
table.search().order_by({"ascending": True})
|
||||
with pytest.raises(ValueError, match="invalid direction"):
|
||||
table.search().order_by([("name", "sideways")])
|
||||
with pytest.raises(TypeError, match="must be a column name"):
|
||||
table.search().order_by([42])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection):
|
||||
table = await mem_db_async.create_table(
|
||||
"test_order_by_async_forms",
|
||||
pa.table({"name": ["z", "b", "a", "c"]}),
|
||||
)
|
||||
|
||||
rows = await (
|
||||
table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow()
|
||||
)
|
||||
assert rows["name"].to_pylist() == ["z", "c", "b", "a"]
|
||||
|
||||
query = table.query().order_by("name")
|
||||
assert query.to_query_object().order_by is not None
|
||||
assert query.order_by(None).to_query_object().order_by is None
|
||||
assert query.order_by([]).to_query_object().order_by is None
|
||||
|
||||
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
||||
table.query().order_by([{"column": "name"}])
|
||||
|
||||
|
||||
def test_column_ordering_is_exported_at_top_level():
|
||||
assert lancedb.ColumnOrdering is ColumnOrdering
|
||||
|
||||
|
||||
def test_order_by_hybrid_sync_is_explicitly_unsupported(table):
|
||||
query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a")
|
||||
|
||||
with pytest.raises(NotImplementedError, match="order_by is not supported"):
|
||||
query.order_by(["id"])
|
||||
|
||||
# Clearing is still allowed, and invalid input still fails on its own terms.
|
||||
query.order_by(None)
|
||||
query.order_by([])
|
||||
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
||||
query.order_by([{"column": "id"}])
|
||||
|
||||
|
||||
def test_query_builder(table):
|
||||
rs = (
|
||||
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
||||
@@ -1397,18 +1938,16 @@ def test_query_builder_with_different_vector_column():
|
||||
ds = mock.Mock()
|
||||
table.to_lance.return_value = ds
|
||||
builder.to_arrow()
|
||||
table._execute_query.assert_called_once_with(
|
||||
Query(
|
||||
vector=query,
|
||||
filter="b < 10",
|
||||
limit=2,
|
||||
distance_type="cosine",
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
),
|
||||
batch_size=None,
|
||||
timeout=None,
|
||||
expected = Query(
|
||||
vector=query,
|
||||
filter="b < 10",
|
||||
limit=2,
|
||||
distance_type="cosine",
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
)
|
||||
expected._blob_row_id_prepared = True
|
||||
table._execute_arrow.assert_called_once_with(expected, timeout=None)
|
||||
|
||||
|
||||
def cosine_distance(vec1, vec2):
|
||||
@@ -2316,6 +2855,61 @@ def test_query_schema(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"test",
|
||||
pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"vector": pa.array(
|
||||
[[1, 2], [3, 4], [5, 6]],
|
||||
pa.list_(pa.float32(), list_size=2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
calls = 0
|
||||
original = AsyncTable._schema_sync
|
||||
|
||||
def counted(self):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return original(self)
|
||||
|
||||
monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
|
||||
|
||||
table.search().where("id = 1").select(["id"]).to_arrow()
|
||||
assert calls <= 1
|
||||
|
||||
calls = 0
|
||||
table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
|
||||
assert calls <= 1
|
||||
|
||||
calls = 0
|
||||
table.search([1, 2]).limit(1).to_arrow()
|
||||
# At most one lookup infers the vector column, one prepares execution.
|
||||
assert calls <= 2
|
||||
|
||||
calls = 0
|
||||
table.search().where("id = 1").select(["id"]).to_batches().read_all()
|
||||
assert calls <= 1
|
||||
|
||||
builder = table.search().where("id = 1")
|
||||
before = builder.to_arrow()
|
||||
assert "extra" not in before.column_names
|
||||
assert "image" not in before.column_names
|
||||
|
||||
table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
|
||||
calls = 0
|
||||
after = builder.to_arrow()
|
||||
assert calls <= 1
|
||||
assert after["extra"].to_pylist() == [None]
|
||||
assert "_lance_row_id" in str(after.schema)
|
||||
assert "_rowid" not in after.column_names
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_schema_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
@@ -2417,13 +3011,116 @@ def test_take_queries(tmp_path):
|
||||
assert sorted(converted["idx"].to_pylist()) == [2, 5, 5, 17]
|
||||
|
||||
# Take by row id
|
||||
assert list(
|
||||
sorted(table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list())
|
||||
) == [
|
||||
2,
|
||||
5,
|
||||
17,
|
||||
]
|
||||
assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
|
||||
|
||||
|
||||
def test_take_offsets_preserve_order_sync(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test", pa.table({"idx": range(4)}))
|
||||
table.add(pa.table({"idx": range(4, 8)}))
|
||||
table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
batches = list(
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
# The default path keeps its unspecified-order behavior.
|
||||
default = table.take_offsets(requested).select(["idx"]).to_arrow()
|
||||
assert sorted(default["idx"].to_pylist()) == sorted(expected)
|
||||
|
||||
assert table.take_offsets(requested).to_query_object().preserve_order is None
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
|
||||
|
||||
empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
|
||||
assert empty.num_rows == 0
|
||||
assert empty.column_names == ["idx"]
|
||||
|
||||
query.order_by = [ColumnOrdering(column_name="idx")]
|
||||
with pytest.raises(
|
||||
ValueError, match="preserve_order cannot be combined with an explicit order_by"
|
||||
):
|
||||
table._execute_query(query)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_take_offsets_preserve_order_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", pa.table({"idx": range(4)}))
|
||||
await table.add(pa.table({"idx": range(4, 8)}))
|
||||
await table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
reader = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
batches = [batch async for batch in reader]
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
|
||||
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": [0, 1]}))
|
||||
table.add(pa.table({"idx": [2, 3]}))
|
||||
rows = table.search().with_row_id(True).to_arrow().to_pylist()
|
||||
row_ids = {row["idx"]: row["_rowid"] for row in rows}
|
||||
table.delete("idx = 1")
|
||||
requested = (
|
||||
[] if empty else [row_ids[3], row_ids[1], row_ids[3], 2**64 - 1, row_ids[0]]
|
||||
)
|
||||
take = table.take_row_ids(requested)
|
||||
if selection is not None:
|
||||
take = take.select(selection)
|
||||
actual = take.to_arrow()
|
||||
assert actual.num_rows == (0 if empty else 3)
|
||||
if selection == {"_rowid": "100 - idx"}:
|
||||
assert actual.column_names == ["_rowid"]
|
||||
assert actual["_rowid"].to_pylist() == ([] if empty else [97, 97, 100])
|
||||
elif selection == []:
|
||||
assert actual.num_columns == 0
|
||||
else:
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == ([] if empty else [3, 3, 0])
|
||||
query = take.to_query_object()
|
||||
assert query.take_row_ids == requested
|
||||
assert table._execute_query(query).read_all() == actual
|
||||
|
||||
|
||||
def test_take_queries_with_row_id(tmp_path):
|
||||
@@ -2432,6 +3129,7 @@ def test_take_queries_with_row_id(tmp_path):
|
||||
|
||||
by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_row_id.column_names
|
||||
assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
|
||||
by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_offset.column_names
|
||||
|
||||
@@ -2446,6 +3144,7 @@ async def test_take_queries_with_row_id_async(tmp_path):
|
||||
|
||||
by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_row_id.column_names
|
||||
assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
|
||||
by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_offset.column_names
|
||||
|
||||
@@ -2472,16 +3171,12 @@ def test_take_queries_to_batches(tmp_path):
|
||||
rs = list(table.take_row_ids([5, 2, 17]).to_batches())
|
||||
assert all(isinstance(b, pa.RecordBatch) for b in rs)
|
||||
assert sum(b.num_rows for b in rs) == 3
|
||||
assert sorted(v for b in rs for v in b.column("idx").to_pylist()) == [2, 5, 17]
|
||||
assert [v for b in rs for v in b.column("idx").to_pylist()] == [5, 2, 17]
|
||||
|
||||
# Take with select projection → to_batches preserves the projection
|
||||
rs = list(table.take_row_ids([5, 2, 17]).select(["label"]).to_batches())
|
||||
assert all(b.schema.names == ["label"] for b in rs)
|
||||
assert sorted(v for b in rs for v in b.column("label").to_pylist()) == [
|
||||
"17",
|
||||
"2",
|
||||
"5",
|
||||
]
|
||||
assert [v for b in rs for v in b.column("label").to_pylist()] == ["5", "2", "17"]
|
||||
|
||||
|
||||
def test_getitems(tmp_path):
|
||||
@@ -2505,6 +3200,13 @@ def test_getitems(tmp_path):
|
||||
assert table.__getitems__(offsets) == pa.table({"idx": offsets})
|
||||
|
||||
|
||||
def test_getitems_rejects_missing_offsets(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
|
||||
|
||||
with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
|
||||
table.__getitems__([0, 99])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_timeout_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
@@ -2637,17 +3339,24 @@ def test_blob_v2_to_batches_row_id(tmp_db):
|
||||
assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metric", ["l2", "cosine", "dot"])
|
||||
@pytest.mark.parametrize(
|
||||
"effort,probes", [(None, 4), (0, 1), (0.25, 2), (0.5, 4), (0.75, 8), (1, 16)]
|
||||
"metric,probes80,probes90", [("l2", 2, 3), ("cosine", 1, 2), ("dot", 1, 2)]
|
||||
)
|
||||
def test_search_effort_probe_budget(tmp_path, monkeypatch, metric, effort, probes):
|
||||
@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
|
||||
def test_search_effort_probe_budget(
|
||||
tmp_path, monkeypatch, metric, effort, probes80, probes90
|
||||
):
|
||||
import re
|
||||
from lancedb.index import IvfFlat
|
||||
|
||||
monkeypatch.setenv("LANCE_AUTO_PROBE_MARGIN", "0")
|
||||
monkeypatch.setenv("LANCE_AUTO_MIN_INITIAL_NPROBES", "4")
|
||||
monkeypatch.setenv("LANCE_AUTO_MAX_INITIAL_NPROBES", "4")
|
||||
# The lower tiers use metric/k calibration; Auto and the upper tiers retain
|
||||
# their existing budgets. Keep exact execution counts and precedence checks.
|
||||
probes = {None: 4, 0: 1, 0.1: probes80, 0.25: probes90, 0.5: 4, 0.75: 8, 1: 16}[
|
||||
effort
|
||||
]
|
||||
rng = np.random.default_rng(42)
|
||||
vectors = np.repeat(np.eye(16, dtype=np.float32), 32, axis=0)
|
||||
vectors += rng.normal(0, 0.001, vectors.shape).astype(np.float32)
|
||||
@@ -2731,7 +3440,7 @@ def test_search_effort_invalid_sync(table, effort):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("hybrid", [False, True])
|
||||
@pytest.mark.parametrize("effort", [None, 0, 0.25, 0.5, 0.75, 1])
|
||||
@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
|
||||
async def test_search_effort_async_roundtrip(table_async, hybrid, effort):
|
||||
query = table_async.vector_search([0, 0])
|
||||
if hybrid:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,6 +20,7 @@ NIL_QUERY_ID = UUID(int=0)
|
||||
|
||||
class FakeNativeQuery:
|
||||
id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef")
|
||||
job_id = None
|
||||
|
||||
async def reader(self):
|
||||
return pa.table({"value": [1, 2]})
|
||||
@@ -68,6 +69,15 @@ def test_query_id_is_uuid():
|
||||
assert Query(query).id == query.id
|
||||
|
||||
|
||||
def test_query_job_id_is_optional_and_separate_from_query_id():
|
||||
native = FakeNativeQuery()
|
||||
native.job_id = "j1-durable"
|
||||
query = AsyncQuery(native)
|
||||
assert query.id != query.job_id
|
||||
assert query.job_id == "j1-durable"
|
||||
assert Query(query).job_id == "j1-durable"
|
||||
|
||||
|
||||
def test_connection_serializes_sql_host_override():
|
||||
endpoint = "grpc+tls://sql.example.com:10026"
|
||||
restored = lancedb.deserialize_conn(
|
||||
@@ -283,6 +293,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent():
|
||||
assert echoed.column("k").to_pylist() == [10]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("exist_ok", "status"),
|
||||
[
|
||||
(None, "created"),
|
||||
(False, "created"),
|
||||
(True, "created"),
|
||||
(True, "already_exists"),
|
||||
],
|
||||
)
|
||||
async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class SecretServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.writes = []
|
||||
|
||||
def do_exchange(self, context, descriptor, reader, writer):
|
||||
self.writes.append((descriptor.command, reader.read_all()))
|
||||
result = pa.table({"status": [status]})
|
||||
writer.begin(result.schema)
|
||||
writer.write_table(result)
|
||||
writer.close()
|
||||
|
||||
with SecretServer() as server:
|
||||
options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {"namespace_path": ["team", "production"]}
|
||||
if exist_ok is not None:
|
||||
kwargs["exist_ok"] = exist_ok
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async("db://analytics", **options)
|
||||
await db.create_secret("api-key", "credential's value", **kwargs)
|
||||
else:
|
||||
db = lancedb.connect("db://analytics", **options)
|
||||
db.create_secret("api-key", "credential's value", **kwargs)
|
||||
((command, parameters),) = server.writes
|
||||
|
||||
prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET"
|
||||
sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1'
|
||||
assert sql.encode() in command
|
||||
assert b"credential's value" not in command
|
||||
assert parameters.column(0).to_pylist() == ["credential's value"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("job_id", [None, "sql-job-1"])
|
||||
def test_sql_input_error_metadata_crosses_native_boundary(job_id):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -39,7 +40,30 @@ def remote_server(text_type=pa.string()):
|
||||
command = ticket.ticket
|
||||
calls.append(command)
|
||||
if b"SHOW STORAGE INTEGRATIONS" in command:
|
||||
result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
|
||||
match = re.search(
|
||||
rb'SHOW STORAGE INTEGRATIONS IN "public" '
|
||||
rb"LIMIT (\d+)(?: FROM '([^']+)')?",
|
||||
command,
|
||||
)
|
||||
assert match is not None, command
|
||||
limit = int(match.group(1))
|
||||
names = [NAME, "zeta"]
|
||||
if match.group(2) is not None:
|
||||
assert match.group(2) == b"server-storage-page", command
|
||||
names = names[1:]
|
||||
page = names[:limit]
|
||||
result = pa.table(
|
||||
{
|
||||
"namespace_path": pa.array(
|
||||
["[]"] * len(page), type=pa.string()
|
||||
),
|
||||
"name": pa.array(page, type=text_type),
|
||||
}
|
||||
)
|
||||
if len(names) > limit:
|
||||
result = result.replace_schema_metadata(
|
||||
{b"lancedb.next_page_token": b"server-storage-page"}
|
||||
)
|
||||
elif b"DROP STORAGE INTEGRATION" in command:
|
||||
result = pa.table({"dropped": [True]})
|
||||
else:
|
||||
@@ -195,6 +219,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
|
||||
assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0]
|
||||
assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0]
|
||||
assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1]
|
||||
listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call]
|
||||
assert len(listings) == 2
|
||||
assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0]
|
||||
assert b"FROM 'server-storage-page'" in listings[1]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("exist_ok", "existing"),
|
||||
[(None, False), (False, False), (True, False), (True, True)],
|
||||
)
|
||||
async def test_storage_integration_exist_ok_preserves_server_metadata(
|
||||
asynchronous, exist_ok, existing
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
fixture = (
|
||||
Path(__file__).parents[3]
|
||||
/ "rust/lancedb/tests/fixtures/storage_integration.json"
|
||||
)
|
||||
stored = json.loads(fixture.read_text())
|
||||
stored["namespace_path"] = ["team"]
|
||||
columns = {}
|
||||
for key, value in stored.items():
|
||||
if isinstance(value, (dict, list)):
|
||||
value = json.dumps(value)
|
||||
columns[key] = pa.array([None], type=pa.string()) if value is None else [value]
|
||||
result = pa.table(columns)
|
||||
prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"]
|
||||
role = (
|
||||
"arn:aws:iam::999999999999:role/replacement"
|
||||
if existing
|
||||
else stored["aws_role_arn"]
|
||||
)
|
||||
|
||||
class IntegrationServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with IntegrationServer() as server:
|
||||
connection_options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
|
||||
kwargs.update(
|
||||
storage_provider="S3",
|
||||
storage_prefix=prefix,
|
||||
aws_role_arn=role,
|
||||
namespace_path=["team"],
|
||||
)
|
||||
uri = f"db://{stored['database']}"
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(uri, **connection_options)
|
||||
info = await db.create_storage_integration(stored["name"], **kwargs)
|
||||
else:
|
||||
db = lancedb.connect(uri, **connection_options)
|
||||
info = db.create_storage_integration(stored["name"], **kwargs)
|
||||
(request,) = server.requests
|
||||
|
||||
command = (
|
||||
"CREATE STORAGE INTEGRATION IF NOT EXISTS"
|
||||
if exist_ok
|
||||
else "CREATE STORAGE INTEGRATION"
|
||||
)
|
||||
assert f'{command} "raw"'.encode() in request
|
||||
assert prefix.encode() in request
|
||||
assert role.encode() in request
|
||||
assert info.storage_prefix == stored["storage_prefix"]
|
||||
assert info.aws_role_arn == stored["aws_role_arn"]
|
||||
assert info.aws_external_id == stored["aws_external_id"]
|
||||
assert info.created_at_millis == stored["created_at_millis"]
|
||||
assert info.namespace_path == ["team"]
|
||||
@@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table):
|
||||
]
|
||||
|
||||
|
||||
def respond(request, body):
|
||||
request.send_response(200)
|
||||
def respond(request, body, status=200):
|
||||
request.send_response(status)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(json.dumps(body).encode())
|
||||
@@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tables", [[], ["first", "last"]])
|
||||
def test_remote_len_and_contains_follow_pages(tables):
|
||||
def test_remote_len_paginates_and_contains_looks_up_table(tables):
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request.path)
|
||||
query = parse_qs(urlparse(request.path).query)
|
||||
url = urlparse(request.path)
|
||||
if request.command == "POST":
|
||||
name = url.path.split("/")[3]
|
||||
assert url.path == f"/v1/table/{name}/describe/"
|
||||
respond(request, {}, status=200 if name in tables else 404)
|
||||
return
|
||||
assert request.command == "GET"
|
||||
assert url.path == "/v1/namespace/$/table/list"
|
||||
query = parse_qs(url.query)
|
||||
if tables and "page_token" not in query:
|
||||
respond(request, {"tables": [tables[0]], "page_token": "opaque-next"})
|
||||
else:
|
||||
@@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables):
|
||||
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
assert len(db) == len(tables)
|
||||
assert ("last" in db) == bool(tables)
|
||||
assert "missing" not in db
|
||||
assert len(requests) == (2 if tables else 1)
|
||||
requests.clear()
|
||||
assert ("first" in db) == bool(tables)
|
||||
assert len(requests) == 1
|
||||
for name in ("last", "missing", "first"):
|
||||
assert (name in db) is (name in tables)
|
||||
assert requests == [f"/v1/table/{name}/describe/"]
|
||||
requests.clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("namespace", [[], ["parent", "child"]])
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import signal
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from datetime import timedelta
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb import background_loop
|
||||
from lancedb.index import BTree, FTS, IvfFlat
|
||||
|
||||
|
||||
def _direct_query_table(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"direct",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
||||
"text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"],
|
||||
"vector": pa.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
pa.list_(pa.float32(), 4),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
table.create_index("id", config=BTree())
|
||||
table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1))
|
||||
table.create_index("text", config=FTS(with_position=True))
|
||||
return table
|
||||
|
||||
|
||||
def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch):
|
||||
table = _direct_query_table(tmp_path)
|
||||
expected_empty_schema = table.search().where("id < 0").output_schema()
|
||||
|
||||
def fail(*_args, **_kwargs):
|
||||
raise AssertionError("LOOP.run must not be used by direct sync queries")
|
||||
|
||||
monkeypatch.setattr(background_loop.LOOP, "run", fail)
|
||||
|
||||
point = table.search().where("id = 1").select(["id", "text"]).to_arrow()
|
||||
assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}]
|
||||
|
||||
with_row_id = (
|
||||
table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow()
|
||||
)
|
||||
assert with_row_id["_rowid"].to_pylist() == [0]
|
||||
|
||||
# The vector column is inferred from the sync schema binding.
|
||||
vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow()
|
||||
assert vector["id"].to_pylist() == [1, 2]
|
||||
assert "_distance" in vector.column_names
|
||||
|
||||
fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow()
|
||||
assert sorted(fts["id"].to_pylist()) == [1, 2]
|
||||
assert "_score" in fts.column_names
|
||||
|
||||
phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow()
|
||||
assert phrase["id"].to_pylist() == [1]
|
||||
|
||||
empty = table.search().where("id < 0").to_arrow()
|
||||
assert empty.num_rows == 0
|
||||
assert empty.schema == expected_empty_schema
|
||||
|
||||
with pytest.raises(Exception, match="Query timeout"):
|
||||
table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0))
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity")
|
||||
def test_direct_sync_query_from_single_worker_progress_callback(tmp_path):
|
||||
script = r"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
cpus = sorted(os.sched_getaffinity(0))
|
||||
if not cpus:
|
||||
print("SKIP")
|
||||
sys.exit(0)
|
||||
os.sched_setaffinity(0, {cpus[0]})
|
||||
except OSError:
|
||||
print("SKIP")
|
||||
sys.exit(0)
|
||||
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("memory:///")
|
||||
target = db.create_table(
|
||||
"target",
|
||||
[{"id": 1, "value": "one"}, {"id": 2, "value": "two"}],
|
||||
)
|
||||
source = db.create_table("source", [{"id": 1}])
|
||||
seen = []
|
||||
|
||||
def progress(_update):
|
||||
if not seen:
|
||||
seen.append(
|
||||
target.search()
|
||||
.where("id = 1")
|
||||
.select(["value"])
|
||||
.to_arrow()
|
||||
.to_pylist()
|
||||
)
|
||||
|
||||
source.add([{"id": 2}], progress=progress)
|
||||
assert seen == [[{"value": "one"}]], seen
|
||||
print("OK")
|
||||
"""
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script],
|
||||
cwd=tmp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
if "SKIP" in result.stdout:
|
||||
pytest.skip("sched_setaffinity did not leave a usable CPU")
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "OK" in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path):
|
||||
rows = 500_000
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"sigint",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(rows), pa.int64()),
|
||||
"text": pa.array([f"row-{row}" for row in range(rows)]),
|
||||
}
|
||||
),
|
||||
)
|
||||
# Warm the runtime and page cache so the timed call is long enough to observe.
|
||||
table.search().select(["id"]).to_arrow()
|
||||
|
||||
timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT))
|
||||
timer.start()
|
||||
try:
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
table.search().select(["id", "text"]).to_arrow()
|
||||
finally:
|
||||
timer.cancel()
|
||||
timer.join()
|
||||
|
||||
# The shared runtime and its generation counter remain usable.
|
||||
after = table.search().where("id = 1").select(["id", "text"]).to_arrow()
|
||||
assert after.to_pylist() == [{"id": 1, "text": "row-1"}]
|
||||
@@ -6,6 +6,7 @@ import ctypes
|
||||
import gc
|
||||
import json
|
||||
import os
|
||||
import pickle
|
||||
import sys
|
||||
import threading
|
||||
import warnings
|
||||
@@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote():
|
||||
assert versions[0]["timestamp"].microsecond == 274000
|
||||
|
||||
|
||||
def test_lance_table_is_picklable(tmp_db: DBConnection):
|
||||
table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]}))
|
||||
payload = pickle.dumps(table)
|
||||
|
||||
# A standard-mode handle must reopen at latest, not freeze the version that
|
||||
# happened to be current when pickle.dumps ran.
|
||||
tmp_db.open_table("pickle_table").add(pa.table({"id": [4]}))
|
||||
|
||||
restored = pickle.loads(payload)
|
||||
assert restored.name == "pickle_table"
|
||||
assert restored.count_rows() == 4
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection):
|
||||
table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]}))
|
||||
table.add(pa.table({"id": [2]}))
|
||||
table.checkout(1)
|
||||
payload = pickle.dumps(table)
|
||||
|
||||
tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]}))
|
||||
|
||||
restored = pickle.loads(payload)
|
||||
assert restored.version == 1
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1]
|
||||
|
||||
restored.checkout_latest()
|
||||
assert restored.version == 3
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
main = db.create_table("pickle_tag_branch", pa.table({"id": [0]}))
|
||||
branch = main.branches.create("exp")
|
||||
branch.add(pa.table({"id": [1]}))
|
||||
branch.tags.create("exp_tag", branch.version)
|
||||
|
||||
# Advance main independently, then resolve a tag that points into exp.
|
||||
main.add(pa.table({"id": [9]}))
|
||||
main.checkout("exp_tag")
|
||||
assert main.current_branch() == "exp"
|
||||
assert main.version == 2
|
||||
assert main.to_arrow()["id"].to_pylist() == [0, 1]
|
||||
|
||||
restored = pickle.loads(pickle.dumps(main))
|
||||
assert restored.current_branch() == "exp"
|
||||
assert restored.version == 2
|
||||
assert restored.to_arrow()["id"].to_pylist() == [0, 1]
|
||||
|
||||
|
||||
def test_lance_table_pickle_preserves_branch_and_version(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
main = db.create_table("pickle_branch", pa.table({"id": [0]}))
|
||||
branch = main.branches.create("exp")
|
||||
branch.add(pa.table({"id": [1]}))
|
||||
branch_version = branch.version
|
||||
|
||||
branch_payload = pickle.dumps(branch)
|
||||
pinned = db.open_table("pickle_branch", branch="exp", version=branch_version)
|
||||
pinned_payload = pickle.dumps(pinned)
|
||||
|
||||
db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]}))
|
||||
|
||||
restored_branch = pickle.loads(branch_payload)
|
||||
assert restored_branch.current_branch() == "exp"
|
||||
assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2]
|
||||
|
||||
restored_pinned = pickle.loads(pinned_payload)
|
||||
assert restored_pinned.current_branch() == "exp"
|
||||
assert restored_pinned.version == branch_version
|
||||
assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1]
|
||||
assert main.count_rows() == 1
|
||||
|
||||
|
||||
def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection):
|
||||
table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]}))
|
||||
payload = pickle.dumps(table)
|
||||
|
||||
table.add(pa.table({"id": [3]}))
|
||||
|
||||
restored = pickle.loads(payload)
|
||||
assert restored.name == "pickle_memory"
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1, 2]
|
||||
|
||||
|
||||
def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection):
|
||||
with pytest.raises(TypeError, match="in-memory LanceDBConnection"):
|
||||
pickle.dumps(mem_db)
|
||||
|
||||
|
||||
def test_pickle_rejects_session_backed_connection(tmp_path):
|
||||
db = lancedb.connect(tmp_path, session=lancedb.Session())
|
||||
table = db.create_table("pickle_session", pa.table({"id": [1]}))
|
||||
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(db)
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(table)
|
||||
|
||||
|
||||
def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection):
|
||||
table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]}))
|
||||
table._namespace_client = threading.Lock()
|
||||
|
||||
with pytest.raises(TypeError, match="namespace_client"):
|
||||
pickle.dumps(table)
|
||||
|
||||
|
||||
def test_lance_table_pickle_preserves_namespace_path(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
|
||||
db.create_namespace(["ns1"])
|
||||
table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"])
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
assert restored.namespace == ["ns1"]
|
||||
assert restored.count_rows() == 1
|
||||
assert restored._conn._namespace_client_properties == {"root": str(tmp_path)}
|
||||
|
||||
|
||||
def test_versioning(mem_db: DBConnection):
|
||||
table = mem_db.create_table(
|
||||
"test",
|
||||
@@ -1303,6 +1426,31 @@ def test_tags(mem_db: DBConnection):
|
||||
)
|
||||
|
||||
|
||||
def test_tags_create_defaults_to_visible_version(mem_db: DBConnection):
|
||||
table = mem_db.create_table("test", data=[{"id": 1}])
|
||||
table.add(data=[{"id": 2}])
|
||||
|
||||
table.tags.create("live")
|
||||
assert table.tags.get_version("live") == 2
|
||||
|
||||
table.checkout(1)
|
||||
table.tags.create("pinned")
|
||||
assert table.tags.get_version("pinned") == 1
|
||||
|
||||
# An explicit version is independent of the version this handle shows.
|
||||
table.tags.create("explicit", 2)
|
||||
assert table.tags.get_version("explicit") == 2
|
||||
|
||||
# A tag checkout is still a visible version, not "latest".
|
||||
table.checkout_latest()
|
||||
table.add(data=[{"id": 3}])
|
||||
assert table.version == 3
|
||||
table.checkout("live")
|
||||
assert table.version == 2
|
||||
table.tags.create("tag-checkout")
|
||||
assert table.tags.get_version("tag-checkout") == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_tags(mem_db_async: AsyncConnection):
|
||||
table = await mem_db_async.create_table(
|
||||
@@ -1357,6 +1505,34 @@ async def test_async_tags(mem_db_async: AsyncConnection):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_tags_create_defaults_to_visible_version(
|
||||
mem_db_async: AsyncConnection,
|
||||
):
|
||||
table = await mem_db_async.create_table("test", data=[{"id": 1}])
|
||||
await table.add(data=[{"id": 2}])
|
||||
|
||||
await table.tags.create("live")
|
||||
assert await table.tags.get_version("live") == 2
|
||||
|
||||
await table.checkout(1)
|
||||
await table.tags.create("pinned")
|
||||
assert await table.tags.get_version("pinned") == 1
|
||||
|
||||
# An explicit version is independent of the version this handle shows.
|
||||
await table.tags.create("explicit", 2)
|
||||
assert await table.tags.get_version("explicit") == 2
|
||||
|
||||
# A tag checkout is still a visible version, not "latest".
|
||||
await table.checkout_latest()
|
||||
await table.add(data=[{"id": 3}])
|
||||
assert await table.version() == 3
|
||||
await table.checkout("live")
|
||||
assert await table.version() == 2
|
||||
await table.tags.create("tag-checkout")
|
||||
assert await table.tags.get_version("tag-checkout") == 2
|
||||
|
||||
|
||||
def test_branches(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table(
|
||||
@@ -1396,6 +1572,62 @@ def test_branches(tmp_path):
|
||||
assert "exp" not in table.branches.list()
|
||||
|
||||
|
||||
def test_branches_create_from_tag(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table("test", data=[{"i": 0}])
|
||||
|
||||
exp = table.branches.create("exp")
|
||||
exp.add([{"i": 10}])
|
||||
exp_version = exp.version
|
||||
exp.tags.create("exp-v2", exp_version)
|
||||
|
||||
# main reaches the same numeric version with different rows.
|
||||
table.add([{"i": 100}])
|
||||
assert table.version == exp_version
|
||||
|
||||
forked = table.branches.create("from-tag", from_tag="exp-v2")
|
||||
assert forked.current_branch() == "from-tag"
|
||||
assert forked.count_rows("i = 10") == 1
|
||||
assert forked.count_rows("i = 100") == 0
|
||||
|
||||
|
||||
def test_branches_create_from_tag_rejects_other_sources(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test", data=[{"i": 0}])
|
||||
table.tags.create("baseline")
|
||||
|
||||
# from_ref="main" must be rejected before it is normalized to the default.
|
||||
with pytest.raises(ValueError, match="from_tag cannot be combined"):
|
||||
table.branches.create("exp", from_ref="main", from_tag="baseline")
|
||||
with pytest.raises(ValueError, match="from_tag cannot be combined"):
|
||||
table.branches.create("exp", from_version=1, from_tag="baseline")
|
||||
|
||||
|
||||
def test_branches_create_from_missing_ref_hint_applies_only_to_branches(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test", data=[{"i": 0}])
|
||||
base = table.branches.create("base")
|
||||
base.add([{"i": 1}])
|
||||
table.tags.create("baseline")
|
||||
|
||||
# A tag passed through from_ref is not a branch. Keep the original failure
|
||||
# classification and add guidance without probing the ref a second time.
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
table.branches.create("exp", from_ref="baseline")
|
||||
|
||||
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
|
||||
assert "from_tag='baseline'" in detail
|
||||
|
||||
# An existing branch with an absent version is a version failure, not an
|
||||
# unresolved branch, so it must not suggest from_tag.
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
table.branches.create("exp", from_ref="base", from_version=9999)
|
||||
|
||||
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
|
||||
assert "9999" in detail
|
||||
assert "from_tag=" not in detail
|
||||
|
||||
|
||||
def test_branch_handle_tracks_concurrent_writes(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table("t", [{"id": 1}])
|
||||
@@ -1691,6 +1923,64 @@ async def test_async_branches(tmp_path):
|
||||
assert "exp" not in await table.branches.list()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_branches_create_from_tag(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = await db.create_table("test", data=[{"i": 0}])
|
||||
|
||||
exp = await table.branches.create("exp")
|
||||
await exp.add([{"i": 10}])
|
||||
exp_version = await exp.version()
|
||||
await exp.tags.create("exp-v2", exp_version)
|
||||
|
||||
# main reaches the same numeric version with different rows.
|
||||
await table.add([{"i": 100}])
|
||||
assert await table.version() == exp_version
|
||||
|
||||
forked = await table.branches.create("from-tag", from_tag="exp-v2")
|
||||
assert forked.current_branch() == "from-tag"
|
||||
assert await forked.count_rows("i = 10") == 1
|
||||
assert await forked.count_rows("i = 100") == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_branches_create_from_tag_rejects_other_sources(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", data=[{"i": 0}])
|
||||
await table.tags.create("baseline")
|
||||
|
||||
with pytest.raises(ValueError, match="from_tag cannot be combined"):
|
||||
await table.branches.create("exp", from_ref="main", from_tag="baseline")
|
||||
with pytest.raises(ValueError, match="from_tag cannot be combined"):
|
||||
await table.branches.create("exp", from_version=1, from_tag="baseline")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_branches_create_from_missing_ref_hint_applies_only_to_branches(
|
||||
tmp_path,
|
||||
):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", data=[{"i": 0}])
|
||||
base = await table.branches.create("base")
|
||||
await base.add([{"i": 1}])
|
||||
await table.tags.create("baseline")
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
await table.branches.create("exp", from_ref="baseline")
|
||||
|
||||
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
|
||||
assert "from_tag='baseline'" in detail
|
||||
|
||||
# An existing branch with an absent version is a version failure, not an
|
||||
# unresolved branch, so it must not suggest from_tag.
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
await table.branches.create("exp", from_ref="base", from_version=9999)
|
||||
|
||||
detail = "\n".join((str(exc_info.value), *getattr(exc_info.value, "__notes__", ())))
|
||||
assert "9999" in detail
|
||||
assert "from_tag=" not in detail
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_open_table_with_branch_version(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path, read_consistency_interval=timedelta(0))
|
||||
@@ -1837,6 +2127,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Test with target_partition_size
|
||||
@@ -1862,6 +2153,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# target_partition_size has a default value,
|
||||
@@ -1886,6 +2178,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
table.create_index(
|
||||
@@ -1902,6 +2195,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
table.create_index(
|
||||
@@ -1922,6 +2216,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
table.create_index(
|
||||
@@ -1942,6 +2237,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -2073,6 +2369,7 @@ def test_create_index_name_and_train_parameters(
|
||||
wait_timeout=None,
|
||||
name="my_custom_index",
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Test with train=False
|
||||
@@ -2084,6 +2381,7 @@ def test_create_index_name_and_train_parameters(
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=False,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Test with both name and train
|
||||
@@ -2095,6 +2393,7 @@ def test_create_index_name_and_train_parameters(
|
||||
wait_timeout=None,
|
||||
name="my_index_name",
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -2132,6 +2431,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Scalar index via new API
|
||||
@@ -2143,6 +2443,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# FTS index via new API
|
||||
@@ -2154,6 +2455,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -3436,7 +3738,8 @@ def test_merge_insert(mem_db: DBConnection):
|
||||
table.merge_insert("a")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(new_data, timeout=timedelta(seconds=10))
|
||||
.use_index(False)
|
||||
.execute(new_data, timeout=timedelta(seconds=10), retries=0)
|
||||
)
|
||||
assert merge_insert_res.version == 2
|
||||
assert merge_insert_res.num_inserted_rows == 1
|
||||
@@ -3515,7 +3818,7 @@ def test_merge_insert(mem_db: DBConnection):
|
||||
# timeout
|
||||
with pytest.raises(Exception, match="merge insert timed out"):
|
||||
table.merge_insert("a").when_matched_update_all().execute(
|
||||
new_data, timeout=timedelta(0)
|
||||
new_data, timeout=timedelta(0), retries=255
|
||||
)
|
||||
|
||||
|
||||
@@ -5984,6 +6287,62 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
|
||||
getattr(table, method)("x", batch_size=batch_size)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
|
||||
@pytest.mark.parametrize(
|
||||
"refresh_kwargs,option",
|
||||
[
|
||||
({"retry_policy": lancedb.FunctionRetryPolicy(transient=True)}, "retry_policy"),
|
||||
({"where": "x > 0"}, "where"),
|
||||
({"error_policy": "skip"}, "error_policy"),
|
||||
({"max_failed_fraction": 0.5}, "max_failed_fraction"),
|
||||
({"max_failed_rows": 10}, "max_failed_rows"),
|
||||
({"row_timeout_seconds": 30}, "row_timeout_seconds"),
|
||||
({"init_timeout_seconds": 60}, "init_timeout_seconds"),
|
||||
({"max_concurrency": 4}, "max_concurrency"),
|
||||
({"publication_interval_rows": 60}, "publication_interval_rows"),
|
||||
(
|
||||
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
|
||||
"resource_budget",
|
||||
),
|
||||
(
|
||||
{
|
||||
"supervisor_resources": {
|
||||
"cpu_millis": 1000,
|
||||
"memory_bytes": 1024,
|
||||
"ephemeral_storage_bytes": 2048,
|
||||
}
|
||||
},
|
||||
"supervisor_resources",
|
||||
),
|
||||
(
|
||||
{
|
||||
"planning_workers": {
|
||||
"resources": {
|
||||
"cpu_millis": 1000,
|
||||
"memory_bytes": 1024,
|
||||
"ephemeral_storage_bytes": 2048,
|
||||
},
|
||||
"max_workers": 2,
|
||||
"rows_per_worker": 100,
|
||||
"fragments_per_worker": 1,
|
||||
}
|
||||
},
|
||||
"planning_workers",
|
||||
),
|
||||
({"num_workers": 2}, "num_workers"),
|
||||
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
|
||||
],
|
||||
)
|
||||
def test_local_refresh_rejects_enterprise_options(
|
||||
tmp_path, method, refresh_kwargs, option
|
||||
):
|
||||
table = lancedb.connect(tmp_path).create_table("rows", [{"x": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match=f"{option} requires a LanceDB Enterprise refresh"
|
||||
):
|
||||
getattr(table, method)("x", **refresh_kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
|
||||
@pytest.mark.parametrize("batch_size", [0, -1])
|
||||
@@ -6005,6 +6364,16 @@ def test_function_errors_are_remote_only(tmp_path):
|
||||
table.function_errors()
|
||||
|
||||
|
||||
def test_function_column_status_is_remote_only(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", [{"x": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError,
|
||||
match="exact Function column status is supported only in LanceDB Enterprise",
|
||||
):
|
||||
table.wait_fresh("x")
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.parametrize("batch_size", [None, 8])
|
||||
def test_refresh_column_async_returns_job(tmp_path, batch_size):
|
||||
@@ -6225,6 +6594,21 @@ def test_auto_refresh_options_require_computed_columns(tmp_path):
|
||||
table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True)
|
||||
|
||||
|
||||
def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("invalid_budget", [{"x": 1}])
|
||||
before = table.version
|
||||
with pytest.raises(ValueError, match="registered Function"):
|
||||
table.add_columns(
|
||||
computed={"doubled": "x * 2"},
|
||||
auto_refresh_resource_budget={
|
||||
"cpu_millis": 1_000,
|
||||
"memory_bytes": 1_024,
|
||||
},
|
||||
)
|
||||
assert table.version == before
|
||||
assert table.schema.names == ["x"]
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
|
||||
@@ -6236,3 +6620,108 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
|
||||
metadata = (await table.schema()).field("doubled").metadata
|
||||
assert metadata[b"computed_column.auto_refresh_enabled"] == b"true"
|
||||
assert b"computed_column.auto_refresh_interval_seconds" not in metadata
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method",
|
||||
["create_index", "create_index_async", "create_scalar_index", "create_fts_index"],
|
||||
)
|
||||
@pytest.mark.parametrize("name", [None, "kept_index"])
|
||||
def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name):
|
||||
table = mem_db.create_table(
|
||||
"keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)]
|
||||
)
|
||||
column = "text" if method == "create_fts_index" else "id"
|
||||
config = FTS() if column == "text" else BTree()
|
||||
table.create_index(column, config=config, name=name, exist_ok=True)
|
||||
before = table.version
|
||||
original = table.list_indices()
|
||||
kwargs = dict(name=name, exist_ok=True)
|
||||
if method in ("create_index", "create_index_async"):
|
||||
kwargs["config"] = config
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", DeprecationWarning)
|
||||
result = getattr(table, method)(column, **kwargs)
|
||||
if method == "create_index_async":
|
||||
result.wait()
|
||||
assert table.version == before
|
||||
assert [(index.name, index.index_type) for index in table.list_indices()] == [
|
||||
(index.name, index.index_type) for index in original
|
||||
]
|
||||
with pytest.raises((ValueError, RuntimeError), match="already exists"):
|
||||
table.create_index(column, config=config, name=name, replace=False)
|
||||
table.create_index(column, config=config, name=name)
|
||||
assert table.version > before
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"column,name,existing",
|
||||
[
|
||||
("vector", "kept", "kept"),
|
||||
("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"),
|
||||
],
|
||||
)
|
||||
def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing):
|
||||
dataset = MagicMock()
|
||||
dataset.list_indices.return_value = [{"name": existing}]
|
||||
with patch("lancedb.table._validate_index_accelerator") as validate:
|
||||
table_module._create_accelerated_index(
|
||||
dataset, column=column, accelerator="cuda", name=name, exist_ok=True
|
||||
)
|
||||
validate.assert_not_called()
|
||||
dataset.create_index.assert_not_called()
|
||||
|
||||
|
||||
def test_accelerated_index_exist_ok_preserves_concurrent_winner():
|
||||
dataset = MagicMock()
|
||||
dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]]
|
||||
dataset.create_index.side_effect = RuntimeError("concurrent create")
|
||||
with patch("lancedb.table._validate_index_accelerator"):
|
||||
table_module._create_accelerated_index(
|
||||
dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True
|
||||
)
|
||||
assert dataset.create_index.call_args.kwargs["replace"] is False
|
||||
assert dataset.create_index.call_args.kwargs["name"] == "vector_idx"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"])
|
||||
def test_index_exist_ok_matches_lance_default_name(mem_db, column):
|
||||
table = mem_db.create_table(
|
||||
"quoted_index",
|
||||
[{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}],
|
||||
)
|
||||
table.create_index(column, config=BTree())
|
||||
before = table.version
|
||||
table.create_index(column, config=BTree(), exist_ok=True)
|
||||
assert table.version == before
|
||||
assert len(table.list_indices()) == 1
|
||||
|
||||
|
||||
def test_fts_exist_ok_matches_quoted_default_name(mem_db):
|
||||
table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}])
|
||||
table.create_index("`body-text`", config=FTS())
|
||||
before = table.version
|
||||
table.create_index("`body-text`", config=FTS(), exist_ok=True)
|
||||
assert table.version == before
|
||||
assert len(table.list_indices()) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"]
|
||||
)
|
||||
async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method):
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
await getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
else:
|
||||
table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
|
||||
@@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table):
|
||||
}.items():
|
||||
assert getattr(config, name) == value
|
||||
assert kwargs == dict(
|
||||
wait_timeout=timeout, name="custom_idx", replace=False, train=False
|
||||
wait_timeout=timeout,
|
||||
name="custom_idx",
|
||||
replace=False,
|
||||
train=False,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -8,13 +8,15 @@ import json
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb.permutation import Permutation, Permutations, permutation_builder
|
||||
from lancedb.util import tbl_to_tensor
|
||||
from lancedb.util import batch_to_tensor, batch_to_tensor_columns, tbl_to_tensor
|
||||
from utils import start_server_thread
|
||||
|
||||
torch = pytest.importorskip("torch")
|
||||
@@ -23,6 +25,43 @@ torch = pytest.importorskip("torch")
|
||||
REMOTE_ROWS = list(range(100))
|
||||
|
||||
|
||||
def _identity_collate(batch):
|
||||
return batch
|
||||
|
||||
|
||||
class _LanceBFloat16Type(pa.ExtensionType):
|
||||
def __init__(self):
|
||||
pa.ExtensionType.__init__(self, pa.binary(2), "lance.bfloat16")
|
||||
|
||||
def __arrow_ext_serialize__(self):
|
||||
return b""
|
||||
|
||||
@classmethod
|
||||
def __arrow_ext_deserialize__(cls, storage_type, serialized):
|
||||
return cls()
|
||||
|
||||
|
||||
def _bf16_storage(values):
|
||||
bits = torch.tensor(values, dtype=torch.bfloat16).view(torch.int16).tolist()
|
||||
return [struct.pack("<H", bit & 0xFFFF) for bit in bits]
|
||||
|
||||
|
||||
def _bf16_array(values):
|
||||
storage = pa.array(_bf16_storage(values), type=pa.binary(2))
|
||||
return pa.ExtensionArray.from_storage(_LanceBFloat16Type(), storage)
|
||||
|
||||
|
||||
def _fixed_shape_tensor_array(physical_values, shape, permutation=None):
|
||||
tensor_type = pa.fixed_shape_tensor(
|
||||
pa.float32(), shape, permutation=permutation or []
|
||||
)
|
||||
flat_values = np.asarray(physical_values, dtype=np.float32).reshape(-1)
|
||||
storage = pa.FixedSizeListArray.from_arrays(
|
||||
pa.array(flat_values), int(np.prod(shape))
|
||||
)
|
||||
return pa.ExtensionArray.from_storage(tensor_type, storage)
|
||||
|
||||
|
||||
def _make_mock_http_handler(handler):
|
||||
class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
@@ -135,6 +174,23 @@ def _open_native_table(uri: str, table_name: str):
|
||||
return lancedb.connect(uri).open_table(table_name)
|
||||
|
||||
|
||||
class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset):
|
||||
"""User-style Dataset that keeps both the connection and table."""
|
||||
|
||||
def __init__(self, db, table):
|
||||
self._db = db
|
||||
self._table = table
|
||||
|
||||
def __len__(self):
|
||||
return self._table.count_rows()
|
||||
|
||||
def __getitem__(self, index):
|
||||
row = self._table.take_offsets([index]).to_arrow().to_pylist()[0]
|
||||
# Touch the connection too, so workers prove both objects were restored.
|
||||
row["db_uri"] = self._db.uri
|
||||
return row
|
||||
|
||||
|
||||
def test_table_dataloader(mem_db):
|
||||
table = mem_db.create_table("test_table", pa.table({"a": range(1000)}))
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
@@ -229,6 +285,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db):
|
||||
assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("start_method", ["spawn", "forkserver"])
|
||||
def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method):
|
||||
if start_method not in mp.get_all_start_methods():
|
||||
pytest.skip(f"{start_method} start method is not available")
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test_table", pa.table({"a": range(20)}))
|
||||
dataset = _DatasetHoldingConnectionAndTable(db, table)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
dataset,
|
||||
batch_size=4,
|
||||
num_workers=2,
|
||||
multiprocessing_context=start_method,
|
||||
)
|
||||
|
||||
seen = []
|
||||
expected_uri = str(tmp_path)
|
||||
for batch in dataloader:
|
||||
seen.extend(batch["a"].tolist())
|
||||
assert all(uri == expected_uri for uri in batch["db_uri"])
|
||||
assert sorted(seen) == list(range(20))
|
||||
|
||||
|
||||
def test_permutation_dataloader_multiprocessing(tmp_db):
|
||||
"""Using a Permutation with a PyTorch DataLoader that has num_workers > 0
|
||||
must work end-to-end. Each worker process gets a pickled copy of the
|
||||
@@ -455,3 +535,472 @@ def test_remote_permutation_dataloader_fork_workers():
|
||||
finally:
|
||||
server.shutdown()
|
||||
handle.join()
|
||||
|
||||
|
||||
def test_permutation_torch_dict_mixed_columns(mem_db):
|
||||
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
|
||||
grids = [
|
||||
[[float(row), float(row) + 1.0], [float(row) + 2.0, float(row) + 3.0]]
|
||||
for row in range(5)
|
||||
]
|
||||
table = mem_db.create_table(
|
||||
"mixed",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(5), type=pa.int32()),
|
||||
"score": pa.array([i / 2 for i in range(5)], type=pa.float32()),
|
||||
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 3)),
|
||||
"grid": pa.array(grids, type=pa.list_(pa.list_(pa.float32(), 2), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table).with_format("torch_dict")
|
||||
|
||||
batch = next(permutation.iter(5, skip_last_batch=False))
|
||||
assert set(batch) == {"id", "score", "vector", "grid"}
|
||||
assert batch["id"].shape == (5,)
|
||||
assert batch["id"].dtype == torch.int32
|
||||
assert batch["score"].dtype == torch.float32
|
||||
assert batch["vector"].shape == (5, 3)
|
||||
assert batch["grid"].shape == (5, 2, 2)
|
||||
assert torch.equal(batch["vector"], torch.tensor(vectors))
|
||||
assert torch.equal(batch["grid"], torch.tensor(grids))
|
||||
|
||||
items = permutation.__getitems__([0, 2, 4])
|
||||
assert items["id"].shape == (3,)
|
||||
assert items["score"].shape == (3,)
|
||||
assert items["vector"].shape == (3, 3)
|
||||
assert items["grid"].shape == (3, 2, 2)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation,
|
||||
batch_size=2,
|
||||
shuffle=False,
|
||||
collate_fn=_identity_collate,
|
||||
)
|
||||
batches = list(dataloader)
|
||||
assert [batch["id"].shape[0] for batch in batches] == [2, 2, 1]
|
||||
assert batches[0]["vector"].shape == (2, 3)
|
||||
assert batches[-1]["grid"].shape == (1, 2, 2)
|
||||
|
||||
empty = permutation.take_offsets([])
|
||||
assert empty["id"].shape == (0,)
|
||||
assert empty["vector"].shape == (0, 3)
|
||||
assert empty["grid"].shape == (0, 2, 2)
|
||||
|
||||
torch_permutation = Permutation.identity(table).with_format("torch")
|
||||
per_row = next(torch_permutation.iter(2, skip_last_batch=False))
|
||||
assert isinstance(per_row, list)
|
||||
assert per_row[0]["vector"].shape == (3,)
|
||||
assert per_row[0]["grid"].shape == (2, 2)
|
||||
torch_loader = torch.utils.data.DataLoader(
|
||||
torch_permutation, batch_size=2, shuffle=False
|
||||
)
|
||||
collated = next(iter(torch_loader))
|
||||
assert collated["vector"].shape == (2, 3)
|
||||
assert collated["grid"].shape == (2, 2, 2)
|
||||
|
||||
|
||||
def test_permutation_torch_dict_dataloader_spawn(tmp_db):
|
||||
vectors = [[float(i), float(i) + 0.5] for i in range(11)]
|
||||
table = tmp_db.create_table(
|
||||
"spawn",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(11),
|
||||
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table).with_format("torch_dict")
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation,
|
||||
batch_size=4,
|
||||
shuffle=False,
|
||||
num_workers=2,
|
||||
multiprocessing_context="spawn",
|
||||
collate_fn=_identity_collate,
|
||||
)
|
||||
seen = []
|
||||
for batch in dataloader:
|
||||
assert isinstance(batch, dict)
|
||||
assert batch["id"].shape == (batch["id"].shape[0],)
|
||||
assert batch["vector"].shape == (batch["id"].shape[0], 2)
|
||||
seen.extend(batch["id"].tolist())
|
||||
assert sorted(seen) == list(range(11))
|
||||
|
||||
|
||||
def test_batch_to_tensor_columns_zero_copy_and_slice_offsets():
|
||||
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
|
||||
nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2)
|
||||
batch = pa.record_batch(
|
||||
[
|
||||
pa.array(range(5), type=pa.int64()),
|
||||
pa.array(vectors, type=pa.list_(pa.float32(), 3)),
|
||||
pa.array(
|
||||
nested_values.tolist(),
|
||||
type=pa.list_(pa.list_(pa.float32(), 2), 3),
|
||||
),
|
||||
pa.array([True, False, True, False, True]),
|
||||
],
|
||||
names=["id", "vector", "nested", "active"],
|
||||
).slice(2, 2)
|
||||
|
||||
tensors = batch_to_tensor_columns(batch)
|
||||
assert tensors["id"].tolist() == [2, 3]
|
||||
assert torch.equal(tensors["vector"], torch.tensor(vectors[2:4]))
|
||||
assert torch.equal(tensors["nested"], torch.from_numpy(nested_values[2:4].copy()))
|
||||
assert tensors["active"].dtype == torch.bool
|
||||
assert tensors["active"].tolist() == [True, False]
|
||||
|
||||
id_array = batch.column("id")
|
||||
assert tensors["id"].data_ptr() == (
|
||||
id_array.buffers()[1].address + id_array.offset * 8
|
||||
)
|
||||
vector_array = batch.column("vector")
|
||||
vector_values = vector_array.values
|
||||
expected_vector_offset = (vector_array.offset * 3 + vector_values.offset) * 4
|
||||
assert tensors["vector"].data_ptr() == (
|
||||
vector_values.buffers()[1].address + expected_vector_offset
|
||||
)
|
||||
|
||||
single_column = pa.record_batch([batch.column("vector")], names=["vector"])
|
||||
column_tensor = batch_to_tensor(single_column)
|
||||
assert column_tensor.shape == (1, 2, 3)
|
||||
assert column_tensor.data_ptr() == tensors["vector"].data_ptr()
|
||||
|
||||
|
||||
def test_permutation_torch_col_and_row_vector_layouts(mem_db):
|
||||
left = [[float(i), float(i) + 0.5] for i in range(4)]
|
||||
right = [[float(i) + 1.0, float(i) + 1.5] for i in range(4)]
|
||||
table = mem_db.create_table(
|
||||
"uniform",
|
||||
pa.table(
|
||||
{
|
||||
"left": pa.array(left, type=pa.list_(pa.float32(), 2)),
|
||||
"right": pa.array(right, type=pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
|
||||
column_batch = next(
|
||||
permutation.with_format("torch_col").iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert column_batch.shape == (2, 4, 2)
|
||||
assert column_batch.dtype == torch.float32
|
||||
assert torch.equal(column_batch[0], torch.tensor(left))
|
||||
|
||||
row_batch = next(
|
||||
permutation.with_format("torch_row").iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert len(row_batch) == 4
|
||||
assert row_batch[0].shape == (2, 2)
|
||||
assert torch.equal(
|
||||
row_batch[0], torch.stack([torch.tensor(left[0]), torch.tensor(right[0])])
|
||||
)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation.with_format("torch_row"), batch_size=4, shuffle=False
|
||||
)
|
||||
stacked = next(iter(dataloader))
|
||||
assert stacked.shape == (4, 2, 2)
|
||||
|
||||
scalar_table = mem_db.create_table(
|
||||
"single_scalar", pa.table({"x": pa.array(range(4), type=pa.int64())})
|
||||
)
|
||||
scalar_rows = next(
|
||||
Permutation.identity(scalar_table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert scalar_rows[0].shape == (1,)
|
||||
assert scalar_rows[0].dtype == torch.int64
|
||||
|
||||
vector_table = mem_db.create_table(
|
||||
"single_vector",
|
||||
pa.table({"v": pa.array(left, type=pa.list_(pa.float32(), 2))}),
|
||||
)
|
||||
vector_rows = next(
|
||||
Permutation.identity(vector_table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert vector_rows[0].shape == (1, 2)
|
||||
vector_column = next(
|
||||
Permutation.identity(vector_table)
|
||||
.with_format("torch_col")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert vector_column.shape == (1, 4, 2)
|
||||
|
||||
|
||||
def test_torch_col_and_row_reject_heterogeneous_shapes(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"heterogeneous",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(4), type=pa.int64()),
|
||||
"vector": pa.array(
|
||||
[[float(i), float(i) + 1.0, float(i) + 2.0] for i in range(4)],
|
||||
type=pa.list_(pa.float32(), 3),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
for format_name in ("torch_col", "torch_row"):
|
||||
with pytest.raises(ValueError, match="torch_dict") as exc_info:
|
||||
next(permutation.with_format(format_name).iter(2, skip_last_batch=False))
|
||||
message = str(exc_info.value)
|
||||
assert "`vector`" in message
|
||||
assert "(3,)" in message
|
||||
assert "`id`" in message
|
||||
assert "()" in message
|
||||
|
||||
different_dims = mem_db.create_table(
|
||||
"different_dims",
|
||||
pa.table(
|
||||
{
|
||||
"left": pa.array(
|
||||
[[1.0, 2.0] for _ in range(4)],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
"right": pa.array(
|
||||
[[1.0, 2.0, 3.0] for _ in range(4)],
|
||||
type=pa.list_(pa.float32(), 3),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="torch_dict") as exc_info:
|
||||
next(
|
||||
Permutation.identity(different_dims)
|
||||
.with_format("torch_row")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
message = str(exc_info.value)
|
||||
assert "`right`" in message and "(3,)" in message
|
||||
assert "`left`" in message and "(2,)" in message
|
||||
|
||||
|
||||
def test_torch_row_uses_pytorch_numeric_promotion(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"promotion",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(4), type=pa.int64()),
|
||||
"score": pa.array([i / 2 for i in range(4)], type=pa.float32()),
|
||||
"count": pa.array(range(4), type=pa.int32()),
|
||||
}
|
||||
),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].shape == (3,)
|
||||
assert rows[0].dtype == torch.float32
|
||||
assert rows[0].tolist() == [0.0, 0.0, 0.0]
|
||||
assert rows[2].tolist() == [2.0, 1.0, 2.0]
|
||||
|
||||
|
||||
def test_torch_row_preserves_nullable_numeric_scalar_nan(mem_db):
|
||||
nullable_int = mem_db.create_table(
|
||||
"nullable_int",
|
||||
pa.table({"value": pa.array([1, None, 3], type=pa.int64())}),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_int)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].shape == (1,)
|
||||
assert rows[0].dtype == torch.float64
|
||||
assert rows[0].tolist() == [1.0]
|
||||
assert torch.isnan(rows[1]).all()
|
||||
assert rows[2].tolist() == [3.0]
|
||||
|
||||
nullable_float = mem_db.create_table(
|
||||
"nullable_float",
|
||||
pa.table({"value": pa.array([0.5, None, 2.5], type=pa.float32())}),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_float)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].dtype == torch.float32
|
||||
assert rows[0].tolist() == [0.5]
|
||||
assert torch.isnan(rows[1]).all()
|
||||
assert rows[2].tolist() == [2.5]
|
||||
|
||||
nullable_mixed = mem_db.create_table(
|
||||
"nullable_mixed",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array([1, None, 3], type=pa.int64()),
|
||||
"score": pa.array([0.5, 1.5, 2.5], type=pa.float32()),
|
||||
}
|
||||
),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_mixed)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].dtype == torch.float64
|
||||
assert rows[0].tolist() == [1.0, 0.5]
|
||||
assert torch.isnan(rows[1][0])
|
||||
assert rows[1][1].item() == 1.5
|
||||
assert rows[2].tolist() == [3.0, 2.5]
|
||||
|
||||
|
||||
def test_permutation_torch_formats_fixed_shape_tensor_permutation(mem_db):
|
||||
physical_values = np.arange(2 * 2 * 3 * 4, dtype=np.float32).reshape(2, 2, 3, 4)
|
||||
tensor_array = _fixed_shape_tensor_array(
|
||||
physical_values, shape=(2, 3, 4), permutation=[0, 2, 1]
|
||||
)
|
||||
table = mem_db.create_table(
|
||||
"tensor_permutation",
|
||||
pa.table({"id": range(2), "tensor": tensor_array}),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
expected = np.transpose(physical_values, (0, 1, 3, 2))
|
||||
|
||||
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
|
||||
assert batch["tensor"].shape == (2, 2, 4, 3)
|
||||
assert torch.equal(batch["tensor"], torch.from_numpy(expected.copy()))
|
||||
|
||||
tensor_only = permutation.select_columns(["tensor"])
|
||||
rows = next(tensor_only.with_format("torch_row").iter(2, skip_last_batch=False))
|
||||
assert rows[0].shape == (1, 2, 4, 3)
|
||||
assert torch.equal(rows[0][0], torch.from_numpy(expected[0].copy()))
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
tensor_only.with_format("torch"), batch_size=2, shuffle=False
|
||||
)
|
||||
default_collated = next(iter(dataloader))
|
||||
assert default_collated["tensor"].shape == (2, 2, 4, 3)
|
||||
|
||||
|
||||
def test_permutation_torch_formats_bfloat16(mem_db):
|
||||
values = [1.0, -1.5, 2.5, 0.0]
|
||||
scalar_values = _bf16_array(values)
|
||||
vector_values = pa.FixedSizeListArray.from_arrays(
|
||||
_bf16_array([value for value in values for _ in range(2)]), 2
|
||||
)
|
||||
table = mem_db.create_table(
|
||||
"bfloat16",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(4),
|
||||
"scalar": scalar_values,
|
||||
"vector": vector_values,
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
|
||||
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
|
||||
assert batch["scalar"].dtype == torch.bfloat16
|
||||
assert batch["vector"].dtype == torch.bfloat16
|
||||
assert torch.equal(batch["scalar"], torch.tensor(values[:2], dtype=torch.bfloat16))
|
||||
assert torch.equal(
|
||||
batch["vector"],
|
||||
torch.tensor([[value, value] for value in values[:2]], dtype=torch.bfloat16),
|
||||
)
|
||||
|
||||
arrow_batch = next(permutation.with_format("arrow").iter(2, skip_last_batch=False))
|
||||
arrow_tensors = batch_to_tensor_columns(arrow_batch)
|
||||
scalar_array = arrow_batch.column("scalar")
|
||||
assert arrow_tensors["scalar"].data_ptr() == (
|
||||
scalar_array.buffers()[1].address + scalar_array.offset * 2
|
||||
)
|
||||
|
||||
sliced = arrow_batch.slice(1, 1)
|
||||
sliced_tensors = batch_to_tensor_columns(sliced)
|
||||
assert torch.equal(
|
||||
sliced_tensors["scalar"],
|
||||
torch.tensor([values[1]], dtype=torch.bfloat16),
|
||||
)
|
||||
assert torch.equal(
|
||||
sliced_tensors["vector"],
|
||||
torch.tensor([[values[1], values[1]]], dtype=torch.bfloat16),
|
||||
)
|
||||
|
||||
skipped = next(
|
||||
permutation.with_skip(1)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
assert torch.equal(
|
||||
skipped["scalar"], torch.tensor(values[1:3], dtype=torch.bfloat16)
|
||||
)
|
||||
|
||||
empty = permutation.with_format("torch_dict").take_offsets([])
|
||||
assert empty["scalar"].shape == (0,)
|
||||
assert empty["scalar"].dtype == torch.bfloat16
|
||||
assert empty["vector"].shape == (0, 2)
|
||||
assert empty["vector"].dtype == torch.bfloat16
|
||||
|
||||
unmarked = mem_db.create_table(
|
||||
"unmarked_bfloat16",
|
||||
pa.table(
|
||||
{
|
||||
"vector": pa.FixedSizeListArray.from_arrays(
|
||||
pa.array(_bf16_storage(values), type=pa.binary(2)), 2
|
||||
)
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="not marked.*lance.bfloat16"):
|
||||
next(
|
||||
Permutation.identity(unmarked)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
|
||||
|
||||
def test_torch_formats_reject_nulls(mem_db):
|
||||
parent_nulls = mem_db.create_table(
|
||||
"parent_nulls",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(3),
|
||||
"values": pa.array(
|
||||
[[1.0, 2.0], None, [5.0, 6.0]],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(
|
||||
Permutation.identity(parent_nulls)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
|
||||
leaf_nulls = mem_db.create_table(
|
||||
"leaf_nulls",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(2),
|
||||
"values": pa.FixedSizeListArray.from_arrays(
|
||||
pa.array([1.0, None, 5.0, 6.0], type=pa.float32()), 2
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(
|
||||
Permutation.identity(leaf_nulls)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
leaf_only = Permutation.identity(leaf_nulls).select_columns(["values"])
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(leaf_only.with_format("torch_row").iter(2, skip_last_batch=False))
|
||||
|
||||
@@ -407,6 +407,33 @@ def test_value_to_sql_nan_and_infinity(tmp_path):
|
||||
assert rows[4]["f64"] == 4.0 and rows[4]["f32"] == 4.0
|
||||
|
||||
|
||||
def test_value_to_sql_enum_members(tmp_path):
|
||||
# str() of an int- or float-valued Enum member is its name, which SQL reads
|
||||
# as a field access, and a plain Enum member raised NotImplementedError.
|
||||
import enum
|
||||
|
||||
class Priority(int, enum.Enum):
|
||||
LOW = 1
|
||||
HIGH = 2
|
||||
|
||||
class Weight(float, enum.Enum):
|
||||
HALF = 0.5
|
||||
|
||||
class Color(enum.Enum):
|
||||
RED = "red"
|
||||
|
||||
assert value_to_sql(Priority.HIGH) == "2"
|
||||
assert value_to_sql(Weight.HALF) == "0.5"
|
||||
assert value_to_sql(Color.RED) == "'red'"
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"test", pa.table({"id": [1], "p": [1], "w": [1.0], "c": ["blue"]})
|
||||
)
|
||||
table.update(values={"p": Priority.HIGH, "w": Weight.HALF, "c": Color.RED})
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1, "p": 2, "w": 0.5, "c": "red"}]
|
||||
|
||||
|
||||
def test_append_vector_columns():
|
||||
registry = EmbeddingFunctionRegistry.get_instance()
|
||||
registry.register("test")(MockTextEmbeddingFunction)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("exist_ok", "existing"),
|
||||
[(None, False), (False, False), (True, False), (True, True)],
|
||||
)
|
||||
async def test_create_view_exist_ok_preserves_server_metadata(
|
||||
asynchronous, exist_ok, existing
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
original_query = "SELECT 'original' AS original"
|
||||
submitted_query = (
|
||||
"SELECT 'replacement' AS replacement" if existing else original_query
|
||||
)
|
||||
schema = {
|
||||
"fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}],
|
||||
"metadata": {
|
||||
"lancedb::view::default_db": "analytics",
|
||||
"lancedb::view::default_namespace": "team",
|
||||
},
|
||||
}
|
||||
result = pa.table(
|
||||
{"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]}
|
||||
)
|
||||
|
||||
class ViewServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with ViewServer() as server:
|
||||
connection_options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async("db://analytics", **connection_options)
|
||||
view = await db.create_view(
|
||||
"saved", submitted_query, namespace_path=["team"], **kwargs
|
||||
)
|
||||
else:
|
||||
db = lancedb.connect("db://analytics", **connection_options)
|
||||
view = db.create_view(
|
||||
"saved", submitted_query, namespace_path=["team"], **kwargs
|
||||
)
|
||||
(request,) = server.requests
|
||||
|
||||
prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW"
|
||||
assert f'{prefix} "saved" AS {submitted_query}'.encode() in request
|
||||
assert view.name == "saved"
|
||||
assert view.namespace_path == ["team"]
|
||||
assert view.default_namespace_path == ["team"]
|
||||
assert view.query == original_query
|
||||
assert view.schema.names == ["original"]
|
||||
@@ -120,7 +120,7 @@ def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
|
||||
with_row_ids=True,
|
||||
)
|
||||
results = builder._finish_hybrid_results(
|
||||
combined, blob_mode="lazy", blob_sources={}
|
||||
combined, blob_mode="lazy", blob_sources={}, schema=None
|
||||
)
|
||||
|
||||
assert "_rowid" not in results.column_names, "the surrogate is internal"
|
||||
|
||||
@@ -4,12 +4,30 @@
|
||||
from typing import assert_type
|
||||
|
||||
import lancedb
|
||||
from lancedb import AsyncConnection, DBConnection
|
||||
from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection
|
||||
|
||||
|
||||
def check_connect_type() -> None:
|
||||
assert_type(lancedb.connect("memory://"), DBConnection)
|
||||
assert_type(
|
||||
lancedb.connect_catalog(
|
||||
uri="db://analytics",
|
||||
api_key="secret",
|
||||
region="us-west-2",
|
||||
host_override="https://my-server.example",
|
||||
),
|
||||
Catalog,
|
||||
)
|
||||
|
||||
|
||||
async def check_connect_async_type() -> None:
|
||||
assert_type(await lancedb.connect_async("memory://"), AsyncConnection)
|
||||
assert_type(
|
||||
await lancedb.connect_catalog_async(
|
||||
uri="db://analytics",
|
||||
api_key="secret",
|
||||
region="us-west-2",
|
||||
host_override="https://my-server.example",
|
||||
),
|
||||
AsyncCatalog,
|
||||
)
|
||||
|
||||
+71
-3
@@ -2,15 +2,20 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::error::PythonErrorExt;
|
||||
use crate::runtime::future_into_py;
|
||||
use crate::runtime::{block_on_interruptible, future_into_py};
|
||||
use arrow::{
|
||||
datatypes::SchemaRef,
|
||||
pyarrow::{IntoPyArrow, ToPyArrow},
|
||||
record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader},
|
||||
};
|
||||
use futures::{TryStreamExt, stream::StreamExt};
|
||||
use lancedb::{
|
||||
arrow::SendableRecordBatchStream,
|
||||
query::{ExecutableQuery, QueryExecutionOptions},
|
||||
};
|
||||
use futures::stream::StreamExt;
|
||||
use lancedb::arrow::SendableRecordBatchStream;
|
||||
use pyo3::{
|
||||
Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods,
|
||||
};
|
||||
@@ -63,3 +68,66 @@ impl RecordBatchStream {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute `query` and collect every batch in Rust before returning to Python.
|
||||
///
|
||||
/// `to_arrow()` needs the complete table, so the default 1024-row output
|
||||
/// slicing only adds work. Returning an Arrow C Stream reader also avoids a
|
||||
/// Python future per batch while python materializes the table.
|
||||
///
|
||||
/// The stream is collected inside the returned future, so timeout and
|
||||
/// cancellation keep the same observable behavior as reading the stream from
|
||||
/// Python: errors surface from the awaited call and dropping the future drops
|
||||
/// the underlying stream.
|
||||
pub fn execute_to_reader<Q>(
|
||||
py: Python<'_>,
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
future_into_py(py, async move {
|
||||
let reader = collect_to_reader(query, max_batch_length, timeout).await?;
|
||||
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Synchronous counterpart of [`execute_to_reader`].
|
||||
///
|
||||
/// The returned reader owns the collected batches; the caller converts it to
|
||||
/// Python after reattaching to the interpreter. The wait releases the GIL and
|
||||
/// keeps Python signal handlers on the calling thread.
|
||||
pub fn execute_to_reader_sync<Q>(
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
block_on_interruptible(collect_to_reader(query, max_batch_length, timeout))
|
||||
}
|
||||
|
||||
async fn collect_to_reader<Q>(
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
// `None` means the caller wants one eager result, not the core's
|
||||
// default batch size. An explicit value is still honored.
|
||||
options.max_batch_length = max_batch_length.unwrap_or(0);
|
||||
options.timeout = timeout;
|
||||
let stream = query.execute_with_options(options).await.infer_error()?;
|
||||
let schema = stream.schema();
|
||||
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
|
||||
Ok(Box::new(RecordBatchIterator::new(
|
||||
batches.into_iter().map(Ok),
|
||||
schema,
|
||||
)))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -127,7 +128,8 @@ impl DatabaseNames {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))]
|
||||
pub fn connect_catalog(
|
||||
py: Python<'_>,
|
||||
endpoint: String,
|
||||
@@ -136,6 +138,7 @@ pub fn connect_catalog(
|
||||
sql_host_override: Option<String>,
|
||||
read_consistency_interval: Option<f64>,
|
||||
oauth_config: Option<crate::oauth::PyOAuthConfig>,
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let interval = read_consistency_interval
|
||||
.map(Duration::try_from_secs_f64)
|
||||
@@ -151,6 +154,9 @@ pub fn connect_catalog(
|
||||
if let Some(config) = client_config {
|
||||
builder = builder.client_config(config.into());
|
||||
}
|
||||
if let Some(options) = storage_options {
|
||||
builder = builder.storage_options(options);
|
||||
}
|
||||
if let Some(endpoint) = sql_host_override {
|
||||
builder = builder.sql_host_override(endpoint);
|
||||
}
|
||||
|
||||
+297
-29
@@ -20,20 +20,176 @@ use arrow::{
|
||||
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
|
||||
};
|
||||
use lancedb::{
|
||||
BasePath,
|
||||
connection::Connection as LanceConnection,
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
database::{CreateTableMode, Database, ReadConsistency},
|
||||
function::GpuClass as LanceGpuClass,
|
||||
database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency},
|
||||
function::{GpuClass as LanceGpuClass, RefreshColumnResult},
|
||||
graph::PropertyGraphDefinition,
|
||||
materialized_view::CreateMaterializedViewBuilder,
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
|
||||
exceptions::{PyRuntimeError, PyValueError},
|
||||
exceptions::{PyRuntimeError, PyTypeError, PyValueError},
|
||||
pyclass, pyfunction, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
|
||||
types::{PyAnyMethods, PyBool, PyDict, PyDictMethods, PyList},
|
||||
};
|
||||
|
||||
fn materialized_view_builder(
|
||||
connection: &LanceConnection,
|
||||
name: String,
|
||||
source: Option<String>,
|
||||
query: Option<String>,
|
||||
has_clauses: bool,
|
||||
) -> PyResult<CreateMaterializedViewBuilder> {
|
||||
match (source, query) {
|
||||
(None, Some(query)) if !has_clauses => {
|
||||
Ok(connection.create_materialized_view_from_query(name, query))
|
||||
}
|
||||
(Some(source), None) => Ok(connection.create_materialized_view(name, source)),
|
||||
(None, None) => Err(PyValueError::new_err(
|
||||
"either source or query must be provided",
|
||||
)),
|
||||
_ => Err(PyValueError::new_err(
|
||||
"query cannot be combined with source, select, where or limit",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `initial_bases` into Lance base paths.
|
||||
///
|
||||
/// Accepts LanceDB's lightweight `BasePath`, a mapping with the same keys, or
|
||||
/// a duck-typed `lance.DatasetBasePath`. `None` maps to no bases. Object
|
||||
/// attributes follow `DatasetBasePath`: a reported `id` of `0` means
|
||||
/// automatic assignment, while a mapping that sets `id=0` explicitly is
|
||||
/// rejected because `0` is reserved for unregistered blob URIs. Explicit
|
||||
/// non-zero ids must be unique.
|
||||
fn parse_initial_bases(initial_bases: Option<Bound<'_, PyAny>>) -> PyResult<Option<Vec<BasePath>>> {
|
||||
let Some(value) = initial_bases else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut bases = Vec::new();
|
||||
let mut explicit_ids: HashSet<u32> = HashSet::new();
|
||||
for (index, item) in value.try_iter()?.enumerate() {
|
||||
let item = item?;
|
||||
let base = parse_base_path(&item, index)?;
|
||||
if base.id != 0 && !explicit_ids.insert(base.id) {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] reuses base id {}; explicit ids must be unique",
|
||||
base.id
|
||||
)));
|
||||
}
|
||||
bases.push(base);
|
||||
}
|
||||
Ok(Some(bases))
|
||||
}
|
||||
|
||||
fn parse_base_path(item: &Bound<'_, PyAny>, index: usize) -> PyResult<BasePath> {
|
||||
let (path, name, is_dataset_root, id) = if let Ok(dict) = item.cast::<PyDict>() {
|
||||
let path = required_string(dict.get_item("path")?, index, "path")?;
|
||||
let name = optional_string(dict.get_item("name")?, index, "name")?;
|
||||
let is_dataset_root =
|
||||
optional_bool(dict.get_item("is_dataset_root")?, index, "is_dataset_root")?;
|
||||
let id = match dict.get_item("id")? {
|
||||
None => 0,
|
||||
Some(value) if value.is_none() => 0,
|
||||
Some(value) => {
|
||||
let id = base_id(&value, index)?;
|
||||
if id == 0 {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] sets id=0, which is reserved for unregistered \
|
||||
blob URIs; pass id=None to let Lance assign an ID"
|
||||
)));
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
(path, name, is_dataset_root, id)
|
||||
} else {
|
||||
let path = item.getattr("path").map_err(|_| {
|
||||
PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}] must be a BasePath, dict, or DatasetBasePath"
|
||||
))
|
||||
})?;
|
||||
let path = required_string(Some(path), index, "path")?;
|
||||
let name = item.getattr("name").ok().filter(|value| !value.is_none());
|
||||
let name = optional_string(name, index, "name")?;
|
||||
let is_dataset_root = match item.getattr("is_dataset_root") {
|
||||
Ok(value) if !value.is_none() => value.extract::<bool>().map_err(|_| {
|
||||
PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}].is_dataset_root must be a bool"
|
||||
))
|
||||
})?,
|
||||
_ => false,
|
||||
};
|
||||
let id = match item.getattr("id") {
|
||||
Ok(value) if !value.is_none() => base_id(&value, index)?,
|
||||
_ => 0,
|
||||
};
|
||||
(path, name, is_dataset_root, id)
|
||||
};
|
||||
|
||||
if path.is_empty() {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}].path must not be empty"
|
||||
)));
|
||||
}
|
||||
Ok(BasePath::new(id, path, name, is_dataset_root))
|
||||
}
|
||||
|
||||
fn required_string(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<String> {
|
||||
let Some(value) = value else {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] is missing '{field}'"
|
||||
)));
|
||||
};
|
||||
value.extract::<String>().map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_string(
|
||||
value: Option<Bound<'_, PyAny>>,
|
||||
index: usize,
|
||||
field: &str,
|
||||
) -> PyResult<Option<String>> {
|
||||
match value {
|
||||
None => Ok(None),
|
||||
Some(value) if value.is_none() => Ok(None),
|
||||
Some(value) => value.extract::<String>().map(Some).map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_bool(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<bool> {
|
||||
match value {
|
||||
None => Ok(false),
|
||||
Some(value) if value.is_none() => Ok(false),
|
||||
Some(value) => value.extract::<bool>().map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a bool"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn base_id(value: &Bound<'_, PyAny>, index: usize) -> PyResult<u32> {
|
||||
if value.is_instance_of::<PyBool>() {
|
||||
return Err(PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}].id must be a positive integer, not a bool"
|
||||
)));
|
||||
}
|
||||
value.extract::<u32>().map_err(|_| {
|
||||
PyValueError::new_err(format!(
|
||||
"initial_bases[{index}].id must be a positive integer that fits in a u32"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyclass]
|
||||
pub struct Connection {
|
||||
inner: Option<LanceConnection>,
|
||||
@@ -289,7 +445,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
|
||||
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None, allow_external_blob_outside_bases=false))]
|
||||
pub fn create_table<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
name: String,
|
||||
@@ -299,11 +455,14 @@ impl Connection {
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
location: Option<String>,
|
||||
namespace_client: Option<Py<PyAny>>,
|
||||
initial_bases: Option<Bound<'_, PyAny>>,
|
||||
allow_external_blob_outside_bases: bool,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let py = self_.py();
|
||||
|
||||
let mode = Self::parse_create_mode_str(mode)?;
|
||||
let initial_bases = parse_initial_bases(initial_bases)?;
|
||||
|
||||
let batches: Box<dyn arrow::array::RecordBatchReader + Send> =
|
||||
Box::new(ArrowArrayStreamReader::from_pyarrow_bound(&data)?);
|
||||
@@ -311,6 +470,12 @@ impl Connection {
|
||||
let ns_path = namespace_path.clone().unwrap_or_default();
|
||||
let mut builder = inner.create_table(name.clone(), batches).mode(mode);
|
||||
|
||||
if let Some(bases) = initial_bases {
|
||||
builder = builder.initial_bases(bases);
|
||||
}
|
||||
if allow_external_blob_outside_bases {
|
||||
builder = builder.allow_external_blob_outside_bases(true);
|
||||
}
|
||||
builder = builder.namespace(ns_path.clone());
|
||||
if let Some(storage_options) = storage_options {
|
||||
builder = builder.storage_options(storage_options);
|
||||
@@ -337,7 +502,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
|
||||
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None))]
|
||||
pub fn create_empty_table<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
name: String,
|
||||
@@ -347,11 +512,13 @@ impl Connection {
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
location: Option<String>,
|
||||
namespace_client: Option<Py<PyAny>>,
|
||||
initial_bases: Option<Bound<'_, PyAny>>,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let py = self_.py();
|
||||
|
||||
let mode = Self::parse_create_mode_str(mode)?;
|
||||
let initial_bases = parse_initial_bases(initial_bases)?;
|
||||
|
||||
let schema = Schema::from_pyarrow_bound(&schema)?;
|
||||
|
||||
@@ -360,6 +527,9 @@ impl Connection {
|
||||
.create_empty_table(name.clone(), Arc::new(schema))
|
||||
.mode(mode);
|
||||
|
||||
if let Some(bases) = initial_bases {
|
||||
builder = builder.initial_bases(bases);
|
||||
}
|
||||
builder = builder.namespace(ns_path.clone());
|
||||
if let Some(storage_options) = storage_options {
|
||||
builder = builder.storage_options(storage_options);
|
||||
@@ -435,7 +605,8 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))]
|
||||
pub fn clone_table(
|
||||
self_: PyRef<'_, Self>,
|
||||
target_table_name: String,
|
||||
@@ -444,6 +615,7 @@ impl Connection {
|
||||
source_version: Option<u64>,
|
||||
source_tag: Option<String>,
|
||||
is_shallow: bool,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
|
||||
@@ -455,7 +627,7 @@ impl Connection {
|
||||
if let Some(tag) = source_tag {
|
||||
builder = builder.source_tag(tag);
|
||||
}
|
||||
builder = builder.is_shallow(is_shallow);
|
||||
builder = builder.is_shallow(is_shallow).exist_ok(exist_ok);
|
||||
|
||||
future_into_py(self_.py(), async move {
|
||||
let table = builder.execute().await.infer_error()?;
|
||||
@@ -483,21 +655,30 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
|
||||
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
|
||||
pub fn create_materialized_view(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
source: String,
|
||||
source: Option<String>,
|
||||
projections: Option<Vec<(String, String)>>,
|
||||
filter: Option<String>,
|
||||
limit: Option<u64>,
|
||||
with_no_data: bool,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
query: Option<String>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let builder = materialized_view_builder(
|
||||
&inner,
|
||||
name,
|
||||
source,
|
||||
query,
|
||||
projections.is_some() || filter.is_some() || limit.is_some(),
|
||||
)?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut builder = inner.create_materialized_view(name, source);
|
||||
let mut builder = builder.exist_ok(exist_ok);
|
||||
if let Some(enabled) = auto_refresh_enabled {
|
||||
builder = builder.auto_refresh_enabled(enabled);
|
||||
}
|
||||
@@ -520,21 +701,30 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
|
||||
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
|
||||
pub fn create_materialized_view_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
source: String,
|
||||
source: Option<String>,
|
||||
projections: Option<Vec<(String, String)>>,
|
||||
filter: Option<String>,
|
||||
limit: Option<u64>,
|
||||
with_no_data: bool,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
query: Option<String>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let builder = materialized_view_builder(
|
||||
&inner,
|
||||
name,
|
||||
source,
|
||||
query,
|
||||
projections.is_some() || filter.is_some() || limit.is_some(),
|
||||
)?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut builder = inner.create_materialized_view(name, source);
|
||||
let mut builder = builder.exist_ok(exist_ok);
|
||||
if let Some(enabled) = auto_refresh_enabled {
|
||||
builder = builder.auto_refresh_enabled(enabled);
|
||||
}
|
||||
@@ -854,19 +1044,36 @@ impl Connection {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.open_job(&job_id).await.infer_error()?;
|
||||
Ok(crate::job::Job::new(job))
|
||||
match job.job_type().as_deref() {
|
||||
Some("function_refresh" | "computed_refresh" | "refresh_column") => {
|
||||
Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<RefreshColumnResult>().infer_error()?,
|
||||
))
|
||||
}
|
||||
Some("prewarm_page_cache") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::PrewarmDataResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
Some("compact") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CompactionResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
_ => Ok(crate::job::Job::new(job)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (request_json, namespace_path=None))]
|
||||
#[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))]
|
||||
pub fn create_function_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
request_json: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json)
|
||||
let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json)
|
||||
.infer_error()?;
|
||||
request.exist_ok = exist_ok;
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
@@ -877,22 +1084,22 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, version, namespace_path=None))]
|
||||
#[pyo3(signature = (name, version=None, namespace_path=None))]
|
||||
pub fn get_function(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
version: String,
|
||||
version: Option<String>,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.get_function(name, version, &namespace_path)
|
||||
.await
|
||||
.infer_error()?
|
||||
.to_canonical_json()
|
||||
.infer_error()
|
||||
let function = match version {
|
||||
Some(version) => inner.get_function(name, version, &namespace_path).await,
|
||||
None => inner.get_function_latest(name, &namespace_path).await,
|
||||
}
|
||||
.infer_error()?;
|
||||
function.to_canonical_json().infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -928,6 +1135,23 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, version, namespace_path=None))]
|
||||
pub fn _drop_function_with_warnings(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
version: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.drop_function_with_warnings(name, version, &namespace_path)
|
||||
.await
|
||||
.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, version, namespace_path=None))]
|
||||
pub fn drop_function_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
@@ -1012,18 +1236,20 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, value, namespace_path=None))]
|
||||
#[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))]
|
||||
pub fn create_secret(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
value: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.create_secret(name, value, &namespace_path)
|
||||
.exist_ok(exist_ok)
|
||||
.await
|
||||
.infer_error()
|
||||
})
|
||||
@@ -1094,18 +1320,20 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, query, namespace_path=None))]
|
||||
#[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))]
|
||||
pub fn create_view(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
query: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
let view = inner
|
||||
.create_view(name, query, &namespace_path)
|
||||
.exist_ok(exist_ok)
|
||||
.await
|
||||
.infer_error()?;
|
||||
view_description_to_py(view)
|
||||
@@ -1247,18 +1475,58 @@ impl Connection {
|
||||
))
|
||||
}
|
||||
|
||||
#[pyo3(signature = (*, page_token=None, page_limit=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))]
|
||||
pub fn list_jobs(
|
||||
&self,
|
||||
page_token: Option<String>,
|
||||
page_limit: Option<u32>,
|
||||
table: Option<String>,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
state: Option<String>,
|
||||
job_type: Option<String>,
|
||||
job_types: Option<Vec<String>>,
|
||||
created_at_gte_millis: Option<i64>,
|
||||
created_at_lt_millis: Option<i64>,
|
||||
) -> PyResult<crate::listing::JobListing> {
|
||||
if job_type.is_some() && job_types.is_some() {
|
||||
return Err(PyValueError::new_err(
|
||||
"set only one of job_type and job_types",
|
||||
));
|
||||
}
|
||||
let mut filter = JobListFilter::default();
|
||||
filter.table = table;
|
||||
filter.namespace_path = namespace_path.unwrap_or_default();
|
||||
filter.state = state
|
||||
.as_deref()
|
||||
.map(|state| match state {
|
||||
"in_progress" => Ok(JobListState::InProgress),
|
||||
"succeeded" => Ok(JobListState::Succeeded),
|
||||
"failed" => Ok(JobListState::Failed),
|
||||
"canceled" => Ok(JobListState::Canceled),
|
||||
"timed_out" => Ok(JobListState::TimedOut),
|
||||
_ => Err(PyValueError::new_err(
|
||||
"state must be one of: in_progress, succeeded, failed, canceled, timed_out",
|
||||
)),
|
||||
})
|
||||
.transpose()?;
|
||||
filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect());
|
||||
filter.created_at_gte_millis = created_at_gte_millis;
|
||||
filter.created_at_lt_millis = created_at_lt_millis;
|
||||
Ok(crate::listing::JobListing::new(
|
||||
self.get_inner()?
|
||||
.list_jobs(crate::listing::options(page_token, page_limit)),
|
||||
.list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn server_info(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let info = inner.server_info().await.infer_error()?;
|
||||
serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
@@ -168,6 +168,28 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
|
||||
err.setattr(intern!(py, "__cause__"), cause_err)?;
|
||||
Err(PyErr::from_value(err))
|
||||
}),
|
||||
LanceError::ResponseInterrupted {
|
||||
request_id,
|
||||
batches,
|
||||
rows,
|
||||
table_version,
|
||||
source,
|
||||
} => Python::attach(|py| {
|
||||
let error = py
|
||||
.import(intern!(py, "lancedb.remote.errors"))?
|
||||
.getattr(intern!(py, "ResponseInterruptedError"))?
|
||||
.call1((
|
||||
err.to_string(),
|
||||
request_id,
|
||||
*batches,
|
||||
*rows,
|
||||
*table_version,
|
||||
is_transport_error(&**source),
|
||||
))?;
|
||||
let cause = http_from_rust_error(py, &**source, request_id, None)?;
|
||||
error.setattr(intern!(py, "__cause__"), cause)?;
|
||||
Err(PyErr::from_value(error))
|
||||
}),
|
||||
LanceError::Sql {
|
||||
message,
|
||||
request_id,
|
||||
@@ -310,6 +332,9 @@ fn new_py_sql_error<'py>(
|
||||
grpc_code: i32,
|
||||
metadata: &RemoteErrorMetadata,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
if sql_has_resource_error(metadata, grpc_code) {
|
||||
return new_py_sql_resource_error(py, message, request_id, grpc_code, metadata);
|
||||
}
|
||||
py.import("lancedb.remote.errors")?
|
||||
.getattr("SqlError")?
|
||||
.call1((
|
||||
@@ -322,6 +347,51 @@ fn new_py_sql_error<'py>(
|
||||
))
|
||||
}
|
||||
|
||||
fn new_py_sql_resource_error<'py>(
|
||||
py: Python<'py>,
|
||||
message: &str,
|
||||
request_id: &str,
|
||||
grpc_code: i32,
|
||||
metadata: &RemoteErrorMetadata,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let resource = metadata.resource.as_ref().unwrap();
|
||||
py.import("lancedb.remote.errors")?
|
||||
.getattr("HttpError")?
|
||||
.call1((
|
||||
message,
|
||||
request_id,
|
||||
grpc_code_to_http_status(grpc_code),
|
||||
metadata.error_code.as_deref(),
|
||||
resource.kind.as_str(),
|
||||
resource.name.as_str(),
|
||||
resource.namespace_path.clone(),
|
||||
false,
|
||||
metadata.job_id.as_deref(),
|
||||
metadata.job_request_id.as_deref(),
|
||||
))
|
||||
}
|
||||
|
||||
fn sql_has_resource_error(metadata: &RemoteErrorMetadata, grpc_code: i32) -> bool {
|
||||
metadata.resource.is_some()
|
||||
&& matches!(
|
||||
(metadata.error_code.as_deref(), grpc_code),
|
||||
// These are gRPC status codes, not HTTP status codes.
|
||||
(Some("not_found"), 5) | (Some("already_exists"), 6)
|
||||
)
|
||||
}
|
||||
|
||||
fn grpc_code_to_http_status(grpc_code: i32) -> Option<u16> {
|
||||
match grpc_code {
|
||||
3 => Some(400),
|
||||
5 => Some(404),
|
||||
6 => Some(409),
|
||||
7 => Some(403),
|
||||
9 => Some(400),
|
||||
12 => Some(501),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve the typed transport classification across the Python boundary.
|
||||
// A missing status code alone also covers malformed job responses, which
|
||||
// waiting longer cannot repair.
|
||||
@@ -335,3 +405,243 @@ fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool {
|
||||
}
|
||||
err.source().is_some_and(is_transport_error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::ffi::CString;
|
||||
use std::sync::{Arc, Once};
|
||||
|
||||
use lancedb::error::{JobFailure, RemoteResourceIdentity};
|
||||
use pyo3::types::{PyAnyMethods, PyModule};
|
||||
|
||||
use super::*;
|
||||
|
||||
static INSTALL_PYTHON_ERROR_MODULES: Once = Once::new();
|
||||
|
||||
fn install_python_error_modules(py: Python<'_>) -> PyResult<()> {
|
||||
// Load the checked-in error classes without requiring an installed wheel.
|
||||
// The namespace exception is only a base for an unrelated remote class.
|
||||
PyModule::from_code(
|
||||
py,
|
||||
c"import sys\n\nimport types\n\n\
|
||||
lancedb = types.ModuleType('lancedb')\n\
|
||||
lancedb.__path__ = []\n\
|
||||
lancedb_remote = types.ModuleType('lancedb.remote')\n\
|
||||
lancedb_remote.__path__ = []\n\
|
||||
lancedb.remote = lancedb_remote\n\
|
||||
namespace = types.ModuleType('lance_namespace')\n\
|
||||
namespace_errors = types.ModuleType('lance_namespace.errors')\n\
|
||||
namespace_errors.TableNotFoundError = RuntimeError\n\
|
||||
namespace.errors = namespace_errors\n\
|
||||
sys.modules['lancedb'] = lancedb\n\
|
||||
sys.modules['lancedb.remote'] = lancedb_remote\n\
|
||||
sys.modules['lance_namespace'] = namespace\n\
|
||||
sys.modules['lance_namespace.errors'] = namespace_errors",
|
||||
c"error_test_bootstrap.py",
|
||||
c"lancedb_error_test_bootstrap",
|
||||
)?;
|
||||
|
||||
let exceptions_code =
|
||||
CString::new(include_str!("../../python/python/lancedb/exceptions.py")).unwrap();
|
||||
let exceptions = PyModule::from_code(
|
||||
py,
|
||||
&exceptions_code,
|
||||
c"exceptions.py",
|
||||
c"lancedb.exceptions",
|
||||
)?;
|
||||
let lancedb = py.import("lancedb")?;
|
||||
lancedb.setattr("exceptions", &exceptions)?;
|
||||
py.import("sys")?
|
||||
.getattr("modules")?
|
||||
.set_item("lancedb.exceptions", &exceptions)?;
|
||||
|
||||
let remote_errors_code =
|
||||
CString::new(include_str!("../../python/python/lancedb/remote/errors.py")).unwrap();
|
||||
let remote_errors = PyModule::from_code(
|
||||
py,
|
||||
&remote_errors_code,
|
||||
c"remote/errors.py",
|
||||
c"lancedb.remote.errors",
|
||||
)?;
|
||||
lancedb
|
||||
.getattr("remote")?
|
||||
.setattr("errors", &remote_errors)?;
|
||||
py.import("sys")?
|
||||
.getattr("modules")?
|
||||
.set_item("lancedb.remote.errors", &remote_errors)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_python_error_modules() {
|
||||
Python::initialize();
|
||||
// Once waits without holding the GIL; only its one-time closure attaches.
|
||||
INSTALL_PYTHON_ERROR_MODULES.call_once(|| {
|
||||
Python::attach(install_python_error_modules).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_job_failure_retains_the_named_resource_as_its_cause() {
|
||||
ensure_python_error_modules();
|
||||
let source = LanceError::Sql {
|
||||
message: "Function 'missing' was not found".into(),
|
||||
request_id: "current-request".into(),
|
||||
grpc_code: 5,
|
||||
metadata: Box::new({
|
||||
let mut metadata = RemoteErrorMetadata::default();
|
||||
metadata.error_code = Some("not_found".into());
|
||||
metadata.job_id = Some("outer-job".into());
|
||||
metadata.job_request_id = Some("worker-request".into());
|
||||
metadata.resource = Some(RemoteResourceIdentity::new(
|
||||
"function",
|
||||
"missing",
|
||||
vec!["ns".into()],
|
||||
));
|
||||
metadata
|
||||
}),
|
||||
};
|
||||
let error = LanceError::JobFailed {
|
||||
job_id: Some("outer-job".into()),
|
||||
failure: Box::new(JobFailure {
|
||||
message: Some("Function 'missing' was not found".into()),
|
||||
traceback: None,
|
||||
sql_job_id: Some("outer-job".into()),
|
||||
source: Some(Arc::new(source)),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
|
||||
let py_err = Python::attach(|_| {
|
||||
let result: std::result::Result<(), LanceError> = Err(error);
|
||||
result.infer_error().unwrap_err()
|
||||
});
|
||||
Python::attach(|py| {
|
||||
let value = py_err.value(py);
|
||||
let job_failed = py
|
||||
.import("lancedb.exceptions")
|
||||
.unwrap()
|
||||
.getattr("JobFailedError")
|
||||
.unwrap();
|
||||
assert!(value.is_instance(&job_failed).unwrap(), "{py_err:?}");
|
||||
let cause = value.getattr("__cause__").unwrap();
|
||||
let function_not_found = py
|
||||
.import("lancedb.remote.errors")
|
||||
.unwrap()
|
||||
.getattr("FunctionNotFoundError")
|
||||
.unwrap();
|
||||
assert!(
|
||||
cause.is_instance(&function_not_found).unwrap(),
|
||||
"{py_err:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("error_code")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"not_found"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("resource_kind")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"function"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("resource_name")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"missing"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("namespace_path")
|
||||
.unwrap()
|
||||
.extract::<Vec<String>>()
|
||||
.unwrap(),
|
||||
["ns"]
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("status_code")
|
||||
.unwrap()
|
||||
.extract::<u16>()
|
||||
.unwrap(),
|
||||
404
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("request_id")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"current-request"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("job_id")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"outer-job"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("job_request_id")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"worker-request"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_catalog_lookup_is_raised_as_the_named_resource_error() {
|
||||
ensure_python_error_modules();
|
||||
for (kind, name, namespace_path, exception) in [
|
||||
(
|
||||
"function",
|
||||
"missing",
|
||||
vec!["ns".into()],
|
||||
"FunctionNotFoundError",
|
||||
),
|
||||
("namespace", "ns", Vec::new(), "NamespaceNotFoundError"),
|
||||
] {
|
||||
let mut metadata = RemoteErrorMetadata::default();
|
||||
metadata.error_code = Some("not_found".into());
|
||||
metadata.resource = Some(RemoteResourceIdentity::new(kind, name, namespace_path));
|
||||
let error = LanceError::Sql {
|
||||
message: format!("{kind} '{name}' was not found"),
|
||||
request_id: "current-request".into(),
|
||||
grpc_code: 5,
|
||||
metadata: Box::new(metadata),
|
||||
};
|
||||
let py_err = Python::attach(|_| {
|
||||
let result: std::result::Result<(), LanceError> = Err(error);
|
||||
result.infer_error().unwrap_err()
|
||||
});
|
||||
Python::attach(|py| {
|
||||
let value = py_err.value(py);
|
||||
let class = py
|
||||
.import("lancedb.remote.errors")
|
||||
.unwrap()
|
||||
.getattr(exception)
|
||||
.unwrap();
|
||||
assert!(value.is_instance(&class).unwrap(), "{py_err:?}");
|
||||
assert_eq!(
|
||||
value
|
||||
.getattr("resource_name")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
name
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-1
@@ -164,9 +164,12 @@ pub fn expr_col(name: &str) -> PyExpr {
|
||||
/// Create a literal value expression.
|
||||
///
|
||||
/// Supported Python types: `bool`, `int`, `float`, `str`, `bytes`, `date`,
|
||||
/// `datetime`, `Decimal`.
|
||||
/// `datetime`, `Decimal`, and `None` (SQL NULL).
|
||||
#[pyfunction]
|
||||
pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult<PyExpr> {
|
||||
if value.is_none() {
|
||||
return Ok(PyExpr(df_lit(ScalarValue::Null)));
|
||||
}
|
||||
// bool must be checked before int because bool is a subclass of int in Python
|
||||
if let Ok(b) = value.extract::<bool>() {
|
||||
return Ok(PyExpr(df_lit(b)));
|
||||
@@ -174,6 +177,9 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult<PyExpr> {
|
||||
if let Ok(i) = value.extract::<i64>() {
|
||||
return Ok(PyExpr(df_lit(i)));
|
||||
}
|
||||
if let Ok(i) = value.extract::<u64>() {
|
||||
return Ok(PyExpr(df_lit(i)));
|
||||
}
|
||||
// Decimal must be checked before f64: Python's Decimal implements __float__,
|
||||
// so value.extract::<f64>() would succeed and silently truncate the value to
|
||||
// f64, losing precision. Build a Decimal128 scalar to preserve it instead.
|
||||
|
||||
+18
-1
@@ -10,6 +10,7 @@ use lancedb::index::{
|
||||
Index as LanceDbIndex,
|
||||
scalar::{
|
||||
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
|
||||
RTreeIndexBuilder, ZoneMapIndexBuilder,
|
||||
},
|
||||
};
|
||||
use pyo3::IntoPyObject;
|
||||
@@ -117,6 +118,17 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
"LabelList" => Ok(LanceDbIndex::LabelList(Default::default())),
|
||||
"Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
|
||||
"NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
|
||||
"ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())),
|
||||
"RTree" => {
|
||||
let params = source.extract::<RTreeParams>()?;
|
||||
let mut builder = RTreeIndexBuilder::default();
|
||||
if let Some(page_size) = params.page_size {
|
||||
builder = builder
|
||||
.page_size(page_size)
|
||||
.map_err(|err| PyValueError::new_err(err.to_string()))?;
|
||||
}
|
||||
Ok(LanceDbIndex::RTree(builder))
|
||||
}
|
||||
"FTS" => {
|
||||
let params = source.extract::<FtsParams>()?;
|
||||
let code_options = CodeAnalyzerOptions {
|
||||
@@ -291,7 +303,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
|
||||
}
|
||||
not_supported => Err(PyValueError::new_err(format!(
|
||||
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
|
||||
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
|
||||
not_supported
|
||||
))),
|
||||
}
|
||||
@@ -325,6 +337,11 @@ struct FtsParams {
|
||||
index_operators: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
struct RTreeParams {
|
||||
page_size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
struct IvfFlatParams {
|
||||
distance_type: String,
|
||||
|
||||
+35
-7
@@ -152,6 +152,25 @@ impl Job {
|
||||
self.inner.description().map(JobDescription::from)
|
||||
}
|
||||
|
||||
pub fn timeline(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
Ok(inner.timeline().await.infer_error()?.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stack(self_: PyRef<'_, Self>, worker_id: String) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
Ok(inner.stack(worker_id).await.infer_error()?.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stats(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move { inner.stats().await.infer_error() })
|
||||
}
|
||||
|
||||
#[pyo3(signature = (*, limit=None, filter=None))]
|
||||
pub fn events(
|
||||
self_: PyRef<'_, Self>,
|
||||
@@ -228,14 +247,28 @@ impl From<lancedb::database::JobInfo> for JobInfo {
|
||||
|
||||
/// The server's account of why a job failed.
|
||||
#[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct JobFailureInfo {
|
||||
phase: Option<String>,
|
||||
message: Option<String>,
|
||||
/// User-code traceback, possibly truncated by the server.
|
||||
traceback: Option<String>,
|
||||
retryable: Option<bool>,
|
||||
sql_job_id: Option<String>,
|
||||
}
|
||||
|
||||
impl From<lancedb::error::JobFailure> for JobFailureInfo {
|
||||
fn from(failure: lancedb::error::JobFailure) -> Self {
|
||||
Self {
|
||||
phase: failure.phase,
|
||||
message: failure.message,
|
||||
traceback: failure.traceback,
|
||||
retryable: failure.retryable,
|
||||
sql_job_id: failure.sql_job_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl JobFailureInfo {
|
||||
fn __repr__(&self) -> String {
|
||||
@@ -339,12 +372,7 @@ impl From<lancedb::database::JobDescription> for JobDescription {
|
||||
.filter(|result| !result.is_null())
|
||||
.map(|result| result.to_string()),
|
||||
_progress_json: Some(progress_json),
|
||||
failure: description.failure.map(|failure| JobFailureInfo {
|
||||
phase: failure.phase,
|
||||
message: failure.message,
|
||||
retryable: failure.retryable,
|
||||
sql_job_id: failure.sql_job_id,
|
||||
}),
|
||||
failure: description.failure.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-3
@@ -16,9 +16,10 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery};
|
||||
use session::Session;
|
||||
use table::{
|
||||
AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken,
|
||||
FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile,
|
||||
RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table,
|
||||
UpdateFieldMetadataResult, UpdateResult,
|
||||
FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus,
|
||||
FunctionColumnVersionStatus, FunctionErrorFragment, FunctionErrorRecord, FunctionErrors,
|
||||
MergeResult, PyBlobFile, RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult,
|
||||
Table, UpdateFieldMetadataResult, UpdateResult,
|
||||
};
|
||||
|
||||
pub mod arrow;
|
||||
@@ -117,6 +118,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<FunctionErrors>()?;
|
||||
m.add_class::<FunctionErrorRecord>()?;
|
||||
m.add_class::<FunctionErrorFragment>()?;
|
||||
m.add_class::<FunctionColumnStatus>()?;
|
||||
m.add_class::<FunctionColumnVersionStatus>()?;
|
||||
m.add_class::<FunctionColumnLastRefreshJob>()?;
|
||||
m.add_class::<FunctionColumnAutoRefreshStatus>()?;
|
||||
m.add_class::<RefreshMaterializedViewResult>()?;
|
||||
m.add_class::<AlterColumnsResult>()?;
|
||||
m.add_class::<UpdateFieldMetadataResult>()?;
|
||||
@@ -145,6 +150,8 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(table::tokenize, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(expr_col, m)?)?;
|
||||
|
||||
@@ -123,14 +123,15 @@ impl PyAsyncPermutationBuilder {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (columns, split_weights, *, discard_weight=0, split_names=None))]
|
||||
#[pyo3(signature = (columns, split_weights, *, discard_weight=None, split_names=None))]
|
||||
pub fn split_hash(
|
||||
slf: PyRefMut<'_, Self>,
|
||||
columns: Vec<String>,
|
||||
split_weights: Vec<u64>,
|
||||
discard_weight: u64,
|
||||
discard_weight: Option<u64>,
|
||||
split_names: Option<Vec<String>>,
|
||||
) -> PyResult<Self> {
|
||||
let discard_weight = discard_weight.unwrap_or(0);
|
||||
slf.modify(|builder| {
|
||||
builder.with_split_strategy(
|
||||
SplitStrategy::Hash {
|
||||
|
||||
+166
-2
@@ -16,22 +16,24 @@ use arrow::array::make_array;
|
||||
use arrow::pyarrow::FromPyArrow;
|
||||
use arrow::pyarrow::IntoPyArrow;
|
||||
use arrow::pyarrow::ToPyArrow;
|
||||
use futures::TryStreamExt;
|
||||
use lancedb::ApproxMode;
|
||||
use lancedb::index::scalar::{
|
||||
BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery,
|
||||
FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery,
|
||||
};
|
||||
use lancedb::query::AnalyzePlanDistributedMetrics;
|
||||
use lancedb::query::QueryBase;
|
||||
use lancedb::query::QueryExecutionOptions;
|
||||
use lancedb::query::QueryFilter;
|
||||
use lancedb::query::{
|
||||
ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery,
|
||||
VectorQuery as LanceDbVectorQuery,
|
||||
};
|
||||
use lancedb::query::{HasQuery, QueryBase};
|
||||
use lancedb::table::AnyQuery;
|
||||
use pyo3::Bound;
|
||||
use pyo3::IntoPyObject;
|
||||
use pyo3::Py;
|
||||
use pyo3::PyAny;
|
||||
use pyo3::PyRef;
|
||||
use pyo3::PyResult;
|
||||
@@ -64,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult<QueryExec
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn execute_to_reader_sync<Q>(
|
||||
py: Python<'_>,
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
let reader =
|
||||
py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?;
|
||||
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
|
||||
}
|
||||
|
||||
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
|
||||
type Error = PyErr;
|
||||
|
||||
@@ -355,6 +371,8 @@ pub struct PyQueryRequest {
|
||||
pub limit: Option<usize>,
|
||||
pub offset: Option<usize>,
|
||||
pub take_offsets: Option<Vec<u64>>,
|
||||
pub take_row_ids: Option<Vec<u64>>,
|
||||
pub preserve_order: Option<bool>,
|
||||
pub filter: Option<PyQueryFilter>,
|
||||
pub full_text_search: Option<PyLanceDB<FtsQuery>>,
|
||||
pub select: PySelect,
|
||||
@@ -378,6 +396,7 @@ pub struct PyQueryRequest {
|
||||
pub postfilter: Option<bool>,
|
||||
pub norm: Option<String>,
|
||||
pub order_by: Option<Vec<PyColumnOrdering>>,
|
||||
pub scan_in_order: Option<bool>,
|
||||
}
|
||||
|
||||
impl From<AnyQuery> for PyQueryRequest {
|
||||
@@ -387,6 +406,8 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
limit: query_request.limit,
|
||||
offset: query_request.offset,
|
||||
take_offsets: query_request.take_offsets,
|
||||
take_row_ids: query_request.take_row_ids,
|
||||
preserve_order: query_request.preserve_order.then_some(true),
|
||||
filter: query_request.filter.map(PyQueryFilter),
|
||||
full_text_search: query_request
|
||||
.full_text_search
|
||||
@@ -414,11 +435,14 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
order_by: query_request
|
||||
.order_by
|
||||
.map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()),
|
||||
scan_in_order: query_request.scan_in_order,
|
||||
},
|
||||
AnyQuery::VectorQuery(vector_query) => Self {
|
||||
limit: vector_query.base.limit,
|
||||
offset: vector_query.base.offset,
|
||||
take_offsets: vector_query.base.take_offsets,
|
||||
take_row_ids: vector_query.base.take_row_ids,
|
||||
preserve_order: vector_query.base.preserve_order.then_some(true),
|
||||
filter: vector_query.base.filter.map(PyQueryFilter),
|
||||
full_text_search: None,
|
||||
select_source_columns: PySelect::source_columns(&vector_query.base.select),
|
||||
@@ -445,6 +469,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
.base
|
||||
.order_by
|
||||
.map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()),
|
||||
scan_in_order: vector_query.base.scan_in_order,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -613,8 +638,18 @@ impl Query {
|
||||
query_text = query_text[1..query_text.len() - 1].to_string();
|
||||
}
|
||||
|
||||
let operator = query
|
||||
.get_item("operator")?
|
||||
.filter(|operator| !operator.is_none())
|
||||
.map(|operator| {
|
||||
let operator = operator.extract::<String>()?;
|
||||
Operator::try_from(operator.as_str())
|
||||
.map_err(|err| PyValueError::new_err(err.to_string()))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(Operator::Or);
|
||||
let query: FtsQuery = match (is_phrase, is_multi_match) {
|
||||
(false, _) => MatchQuery::new(query_text).into(),
|
||||
(false, _) => MatchQuery::new(query_text).with_operator(operator).into(),
|
||||
(true, false) => PhraseQuery::new(query_text).into(),
|
||||
(true, true) => {
|
||||
return Err(PyValueError::new_err(
|
||||
@@ -653,6 +688,10 @@ impl Query {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn scan_in_order(&mut self, ordered: bool) {
|
||||
self.inner = self.inner.clone().scan_in_order(ordered);
|
||||
}
|
||||
|
||||
#[pyo3(signature = ())]
|
||||
pub fn output_schema(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
@@ -682,6 +721,29 @@ impl Query {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>> {
|
||||
execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -737,6 +799,10 @@ impl TakeQuery {
|
||||
self.inner = self.inner.clone().with_row_id();
|
||||
}
|
||||
|
||||
pub fn preserve_order(&mut self) {
|
||||
self.inner = self.inner.clone().preserve_order();
|
||||
}
|
||||
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
@@ -770,6 +836,20 @@ impl TakeQuery {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -895,6 +975,67 @@ impl FTSQuery {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(
|
||||
self_.py(),
|
||||
self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone()),
|
||||
max_batch_length,
|
||||
timeout,
|
||||
)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>> {
|
||||
execute_to_reader_sync(
|
||||
self_.py(),
|
||||
self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone()),
|
||||
max_batch_length,
|
||||
timeout,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut inner = self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone());
|
||||
let request = inner.mut_query();
|
||||
request.limit = None;
|
||||
request.offset = None;
|
||||
request.select = Select::columns(&["_score"]);
|
||||
request.order_by = None;
|
||||
request.with_row_id = false;
|
||||
request.reranker = None;
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut stream = inner.execute().await.infer_error()?;
|
||||
let mut count = 0_u64;
|
||||
while let Some(batch) = stream.try_next().await.infer_error()? {
|
||||
count += batch.num_rows() as u64;
|
||||
}
|
||||
Ok(count)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult<HybridQuery> {
|
||||
let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?;
|
||||
Ok(HybridQuery {
|
||||
@@ -1112,6 +1253,29 @@ impl VectorQuery {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>> {
|
||||
execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
+674
-63
@@ -21,37 +21,47 @@
|
||||
//! rests on three separate mechanisms, each solving one problem the others
|
||||
//! cannot:
|
||||
//!
|
||||
//! **`OUTSTANDING`, not `Arc::strong_count`, decides when the runtime is
|
||||
//! idle.** Early versions tried to infer "is anything still using this
|
||||
//! runtime" from how many `Arc<Runtime>` clones existed. That signal is
|
||||
//! wrong in both directions: a clone taken only for the instant a task is
|
||||
//! *submitted* says nothing about whether that task has actually finished
|
||||
//! running (`Runtime::shutdown_timeout` gives spawned, non-blocking tasks
|
||||
//! no grace period at all -- a task "keeps running until it yields, then is
|
||||
//! dropped" -- so a reclaim landing right after submission would silently
|
||||
//! abandon it before it ever got to run); and a clone held for a task's
|
||||
//! *whole* lifetime can end up making that task the final owner of the
|
||||
//! `Runtime`, so completing it drops the `Runtime` from inside one of its
|
||||
//! own worker threads, which tokio itself forbids ("cannot drop a runtime
|
||||
//! in a context where blocking is not allowed") and panics. `OUTSTANDING`
|
||||
//! is an explicit courtesy counter instead: every top-level `spawn`,
|
||||
//! `spawn_blocking`, or `block_on` call increments it before it starts and
|
||||
//! decrements it (via [`OutstandingGuard`]) when it is truly done, entirely
|
||||
//! decoupled from how many `Arc` clones exist at any instant. `shutdown`
|
||||
//! waits for it to reach zero before ever touching the runtime, which also
|
||||
//! closes a narrower race: because the counter is incremented *before*
|
||||
//! `get_runtime()` is even called, an install already in progress when
|
||||
//! `shutdown` runs is never invisible to it the way an empty slot would be.
|
||||
//! If the counter never reaches zero within the bound, `shutdown` stops
|
||||
//! waiting and forces the retirement attempt anyway -- silently returning
|
||||
//! with the runtime and its workers still fully alive would just recreate
|
||||
//! the exact race this function exists to close, for any call slower than
|
||||
//! the grace period.
|
||||
//! **A per-generation counter, not `Arc::strong_count`, decides when the
|
||||
//! runtime is idle.** Early versions tried to infer "is anything still
|
||||
//! using this runtime" from how many `Arc<Runtime>` clones existed. That
|
||||
//! signal is wrong in both directions: a clone taken only for the instant a
|
||||
//! task is *submitted* says nothing about whether that task has actually
|
||||
//! finished running (`Runtime::shutdown_timeout` gives spawned, non-blocking
|
||||
//! tasks no grace period at all -- a task "keeps running until it yields,
|
||||
//! then is dropped" -- so a reclaim landing right after submission would
|
||||
//! silently abandon it before it ever got to run); and a clone held for a
|
||||
//! task's *whole* lifetime can end up making that task the final owner of
|
||||
//! the `Runtime`, so completing it drops the `Runtime` from inside one of
|
||||
//! its own worker threads, which tokio itself forbids ("cannot drop a
|
||||
//! runtime in a context where blocking is not allowed") and panics.
|
||||
//! [`GenerationCalls`] is an explicit courtesy counter instead: every
|
||||
//! top-level `spawn`, `spawn_blocking`, or `block_on` call increments it
|
||||
//! before it starts and decrements it (via [`OutstandingGuard`]) when it is
|
||||
//! truly done, entirely decoupled from how many `Arc` clones exist at any
|
||||
//! instant. `shutdown` waits for the current generation's counter to reach
|
||||
//! zero before ever touching the runtime, which also closes a narrower
|
||||
//! race: because the counter is incremented *before* `get_runtime()` is
|
||||
//! even called, an install already in progress when `shutdown` runs is
|
||||
//! never invisible to it the way an empty slot would be. If the counter
|
||||
//! never reaches zero within the bound, `shutdown` stops waiting and forces
|
||||
//! the retirement attempt anyway -- silently returning with the runtime and
|
||||
//! its workers still fully alive would just recreate the exact race this
|
||||
//! function exists to close, for any call slower than the grace period.
|
||||
//!
|
||||
//! **Tasks never hold an `Arc<Runtime>`.** Because `OUTSTANDING` (not
|
||||
//! reference counting) is what `shutdown` waits on, a top-level task only
|
||||
//! needs to carry an `OutstandingGuard` -- a token whose `Drop` is a plain
|
||||
//! atomic decrement -- not a clone of the runtime itself. That is what
|
||||
//! **The counter is scoped to a fork generation, not the process.** A
|
||||
//! single process-wide count cannot survive `fork()`: the child inherits the
|
||||
//! parent's in-flight value, but the tasks that would decrement it do not
|
||||
//! run there, and a guard copied onto the forking thread would later
|
||||
//! decrement the child's count even though it belongs to the parent. Every
|
||||
//! [`OutstandingGuard`] therefore holds an `Arc<GenerationCalls>` for the
|
||||
//! generation it was created in. A stale guard can only decrement its own
|
||||
//! counter, while the child's first call lazily creates a fresh counter, and
|
||||
//! `shutdown` only waits on the counter matching the live generation.
|
||||
//!
|
||||
//! **Tasks never hold an `Arc<Runtime>`.** Because the generation counter
|
||||
//! (not reference counting) is what `shutdown` waits on, a top-level task
|
||||
//! only needs to carry an `OutstandingGuard` -- a token whose `Drop` is a
|
||||
//! plain atomic decrement -- not a clone of the runtime itself. That is what
|
||||
//! makes it impossible for a task's completion to become the final,
|
||||
//! worker-thread-side drop of the `Runtime`: nothing a task holds ever
|
||||
//! *is* the `Runtime`.
|
||||
@@ -74,17 +84,28 @@
|
||||
//! installed runtime was built in against the live counter on every call,
|
||||
//! from ordinary (non-signal) context, and treats a mismatch as "stale,
|
||||
//! rebuild" -- exactly the check `atfork_child` used to perform directly.
|
||||
//! [`shutdown`] makes the same comparison, because a child that exits
|
||||
//! without ever installing its own runtime still finds the parent's stale
|
||||
//! [`Tagged`] in the slot. It removes that slot and deliberately leaks the
|
||||
//! instance instead of calling `shutdown_timeout` on it: its worker threads
|
||||
//! do not exist in this process, so waiting for its counter or trying to
|
||||
//! join them would hang, and a leaked reference prevents any inherited
|
||||
//! `Arc` clone from becoming the final owner that drops it.
|
||||
|
||||
use std::future::Future;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject};
|
||||
use futures::FutureExt;
|
||||
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError};
|
||||
use pyo3_async_runtimes::{
|
||||
TaskLocals,
|
||||
err::RustPanic,
|
||||
generic::{ContextExt, JoinError, Runtime},
|
||||
};
|
||||
use tokio::{runtime, task};
|
||||
@@ -110,12 +131,21 @@ static RUNTIME: ArcSwapOption<Tagged> = ArcSwapOption::const_empty();
|
||||
/// access -- just one atomic add, which is all a `pthread_atfork` child
|
||||
/// handler is ever safe to do.
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
/// Count of top-level `spawn`/`spawn_blocking`/`block_on` calls that have
|
||||
/// started but not yet finished. See the module docs for why this, and not
|
||||
/// `Arc::strong_count`, is what `shutdown` waits on.
|
||||
static OUTSTANDING: AtomicU64 = AtomicU64::new(0);
|
||||
/// In-flight top-level calls for one fork generation. Guards hold an `Arc`
|
||||
/// to this object for their whole lifetime, so one inherited across `fork()`
|
||||
/// can only decrement the counter it was created against, never the child's
|
||||
/// fresh one.
|
||||
struct GenerationCalls {
|
||||
generation: u64,
|
||||
outstanding: AtomicUsize,
|
||||
}
|
||||
static CALLS: ArcSwapOption<GenerationCalls> = ArcSwapOption::const_empty();
|
||||
static ATFORK_INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[cfg(test)]
|
||||
static TEST_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn create_runtime() -> runtime::Runtime {
|
||||
runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
@@ -124,9 +154,68 @@ fn create_runtime() -> runtime::Runtime {
|
||||
.expect("Failed to build tokio runtime")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn create_runtime() -> runtime::Runtime {
|
||||
let mut builder = runtime::Builder::new_multi_thread();
|
||||
builder.enable_all().thread_name("lancedb-tokio-worker");
|
||||
// Fork tests hold two runtimes open at once. Keeping their worker count
|
||||
// small avoids turning an unrelated parallel build on the same host into
|
||||
// an apparent hang when the process thread limit is close to full.
|
||||
let worker_threads = TEST_WORKER_THREADS.load(Ordering::Relaxed);
|
||||
if worker_threads != 0 {
|
||||
builder.worker_threads(worker_threads);
|
||||
}
|
||||
builder.build().expect("Failed to build tokio runtime")
|
||||
}
|
||||
|
||||
/// Register the fork-child handler once, before any generation-scoped state
|
||||
/// is created.
|
||||
///
|
||||
/// The first top-level call deliberately installs the hook before it starts
|
||||
/// counting itself. Otherwise a fork between taking that first counter and
|
||||
/// `get_runtime()` installing the hook would leave the child sharing the
|
||||
/// parent's counter with no generation change to separate them.
|
||||
fn ensure_atfork_installed() {
|
||||
if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) {
|
||||
install_atfork();
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the in-flight counter for the current fork generation, creating it on
|
||||
/// the first top-level call after a fork.
|
||||
fn current_calls() -> Arc<GenerationCalls> {
|
||||
ensure_atfork_installed();
|
||||
let current_gen = GENERATION.load(Ordering::SeqCst);
|
||||
loop {
|
||||
let existing = CALLS.load_full();
|
||||
if let Some(existing) = &existing
|
||||
&& existing.generation == current_gen
|
||||
{
|
||||
return Arc::clone(existing);
|
||||
}
|
||||
let candidate = Arc::new(GenerationCalls {
|
||||
generation: current_gen,
|
||||
outstanding: AtomicUsize::new(0),
|
||||
});
|
||||
let previous = CALLS.compare_and_swap(&existing, Some(Arc::clone(&candidate)));
|
||||
let won = match (&*previous, &existing) {
|
||||
(None, None) => true,
|
||||
(Some(prev), Some(exist)) => Arc::ptr_eq(prev, exist),
|
||||
_ => false,
|
||||
};
|
||||
if won {
|
||||
// A stale counter is only an integer: unlike a runtime it has no
|
||||
// worker threads to join, so letting the slot's old reference go
|
||||
// here is safe even in a forked child.
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a live, owned handle to the shared runtime, rebuilding it if the
|
||||
/// installed one predates the most recent `fork()`.
|
||||
fn get_runtime() -> Arc<Tagged> {
|
||||
ensure_atfork_installed();
|
||||
let current_gen = GENERATION.load(Ordering::SeqCst);
|
||||
loop {
|
||||
let existing = RUNTIME.load_full();
|
||||
@@ -135,9 +224,6 @@ fn get_runtime() -> Arc<Tagged> {
|
||||
{
|
||||
return Arc::clone(existing);
|
||||
}
|
||||
if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) {
|
||||
install_atfork();
|
||||
}
|
||||
// Built optimistically, outside any lock: on the rare race where two
|
||||
// threads both find the slot empty (or stale), one candidate wins
|
||||
// the compare-and-swap below and the other is simply dropped here,
|
||||
@@ -167,23 +253,26 @@ fn get_runtime() -> Arc<Tagged> {
|
||||
}
|
||||
}
|
||||
|
||||
/// RAII token tracked by [`OUTSTANDING`]. Held for the duration of a
|
||||
/// top-level `block_on` call, or moved into a top-level `spawn`/
|
||||
/// `spawn_blocking` task so it decrements only once that task's *entire*
|
||||
/// body -- including anything it nested-spawns and awaits -- has run to
|
||||
/// completion or been dropped without completing.
|
||||
struct OutstandingGuard;
|
||||
/// RAII token tracked by the current [`GenerationCalls`] counter. Held for
|
||||
/// the duration of a top-level `block_on` call, or moved into a top-level
|
||||
/// `spawn`/`spawn_blocking` task so it decrements only once that task's
|
||||
/// *entire* body -- including anything it nested-spawns and awaits -- has run
|
||||
/// to completion or been dropped without completing.
|
||||
struct OutstandingGuard {
|
||||
calls: Arc<GenerationCalls>,
|
||||
}
|
||||
|
||||
impl OutstandingGuard {
|
||||
fn new() -> Self {
|
||||
OUTSTANDING.fetch_add(1, Ordering::SeqCst);
|
||||
Self
|
||||
let calls = current_calls();
|
||||
calls.outstanding.fetch_add(1, Ordering::SeqCst);
|
||||
Self { calls }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OutstandingGuard {
|
||||
fn drop(&mut self) {
|
||||
OUTSTANDING.fetch_sub(1, Ordering::SeqCst);
|
||||
self.calls.outstanding.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +286,111 @@ pub fn block_on<F: std::future::Future>(fut: F) -> F::Output {
|
||||
get_runtime().block_on(fut)
|
||||
}
|
||||
|
||||
/// How often an interruptible wait returns to the Python caller for signal checks.
|
||||
const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25);
|
||||
|
||||
/// Block on `fut` while keeping the Python caller responsive to signals.
|
||||
///
|
||||
/// The query task lives on the shared runtime and carries an [`OutstandingGuard`].
|
||||
/// The caller waits on the result channel without holding the GIL and periodically
|
||||
/// reacquires it to run CPython's signal handlers on the same thread. A signal
|
||||
/// exception aborts the task and drops the result receiver.
|
||||
///
|
||||
/// A synchronous callback already running on a multi-threaded Tokio worker uses
|
||||
/// [`tokio::task::block_in_place`] so the core can be handed off while the callback
|
||||
/// waits. Current-thread runtimes and contexts that reject blocking are returned as
|
||||
/// Python errors instead of falling back to the Python event loop.
|
||||
pub fn block_on_interruptible<F, T>(fut: F) -> PyResult<T>
|
||||
where
|
||||
F: Future<Output = PyResult<T>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals()))
|
||||
}
|
||||
|
||||
fn block_on_interruptible_with<F, T, C>(fut: F, check: C) -> PyResult<T>
|
||||
where
|
||||
F: Future<Output = PyResult<T>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
C: FnMut() -> PyResult<()>,
|
||||
{
|
||||
match runtime::Handle::try_current() {
|
||||
Ok(handle) => match handle.runtime_flavor() {
|
||||
runtime::RuntimeFlavor::MultiThread => {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| {
|
||||
task::block_in_place(|| block_on_interruptible_inner(fut, check))
|
||||
}));
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(payload) => Err(PyRuntimeError::new_err(format!(
|
||||
"synchronous query cannot block in this Tokio context: {}",
|
||||
panic_message(payload.as_ref())
|
||||
))),
|
||||
}
|
||||
}
|
||||
_ => Err(PyRuntimeError::new_err(
|
||||
"synchronous query execution cannot block on a current-thread Tokio runtime; use the async API",
|
||||
)),
|
||||
},
|
||||
Err(_) => block_on_interruptible_inner(fut, check),
|
||||
}
|
||||
}
|
||||
|
||||
fn block_on_interruptible_inner<F, T, C>(fut: F, mut check: C) -> PyResult<T>
|
||||
where
|
||||
F: Future<Output = PyResult<T>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
C: FnMut() -> PyResult<()>,
|
||||
{
|
||||
let guard = OutstandingGuard::new();
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
let task = async move {
|
||||
let _guard = guard;
|
||||
let result = AssertUnwindSafe(fut).catch_unwind().await;
|
||||
// Dropping a completed result is enough when the caller has already
|
||||
// returned on an interrupt; the task's guard is dropped with it.
|
||||
let _ = tx.send(result);
|
||||
};
|
||||
let handle = get_runtime().spawn(task);
|
||||
|
||||
loop {
|
||||
match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) {
|
||||
Ok(Ok(result)) => {
|
||||
check()?;
|
||||
return result;
|
||||
}
|
||||
Ok(Err(payload)) => {
|
||||
check()?;
|
||||
return Err(RustPanic::new_err(format!(
|
||||
"rust future panicked: {}",
|
||||
panic_message(payload.as_ref())
|
||||
)));
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if let Err(error) = check() {
|
||||
handle.abort();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
return Err(PyRuntimeError::new_err(
|
||||
"query task stopped before producing a result",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
|
||||
if let Some(message) = payload.downcast_ref::<&str>() {
|
||||
message
|
||||
} else if let Some(message) = payload.downcast_ref::<String>() {
|
||||
message.as_str()
|
||||
} else {
|
||||
"unknown error"
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a detached task, including when the caller is already on a runtime worker.
|
||||
/// Keep it visible to [`shutdown`] until it finishes.
|
||||
pub fn spawn_background<F>(fut: F)
|
||||
@@ -219,13 +413,15 @@ where
|
||||
|
||||
/// Gracefully quiesce the shared runtime, meant to run at normal process exit.
|
||||
///
|
||||
/// Waits (bounded by `timeout`) for [`OUTSTANDING`] to reach zero -- i.e.
|
||||
/// for every top-level call already under way to actually finish, not just
|
||||
/// for `Arc::strong_count` to look low -- before ever touching the runtime.
|
||||
/// If the bound elapses first, it stops waiting and attempts retirement
|
||||
/// anyway: leaving the runtime and its worker threads untouched would just
|
||||
/// recreate the exact race this function exists to close, for any call
|
||||
/// slower than the grace period.
|
||||
/// Waits (bounded by `timeout`) for the current generation's
|
||||
/// [`GenerationCalls`] counter to reach zero -- i.e. for every top-level call
|
||||
/// already under way in *this* process to actually finish, not just for
|
||||
/// `Arc::strong_count` to look low -- before ever touching the runtime. Work
|
||||
/// inherited from a parent process at `fork()` belongs to an older
|
||||
/// generation and is never waited on. If the bound elapses first, it stops
|
||||
/// waiting and attempts retirement anyway: leaving the runtime and its worker
|
||||
/// threads untouched would just recreate the exact race this function exists
|
||||
/// to close, for any call slower than the grace period.
|
||||
///
|
||||
/// Retirement itself removes the runtime from the slot and calls
|
||||
/// `shutdown_timeout` rather than a bare `drop`: dropping a tokio `Runtime`
|
||||
@@ -238,14 +434,22 @@ where
|
||||
/// the slot and finishing its own call, this abandons the runtime instead
|
||||
/// of forcing the issue -- the same trade `atfork_child` already makes.
|
||||
///
|
||||
/// A runtime tagged with a generation older than the live counter was
|
||||
/// inherited through `fork()` and is never retired here; see the module docs.
|
||||
///
|
||||
/// Neither of the two ways this can fail to cleanly retire the runtime --
|
||||
/// the wait timing out, or `try_unwrap` losing that race -- has any other
|
||||
/// signal to report through (`shutdown_timeout` itself returns nothing),
|
||||
/// so both log a warning instead of failing silently.
|
||||
pub fn shutdown(timeout: Duration) {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let generation = GENERATION.load(Ordering::SeqCst);
|
||||
let calls = CALLS.load_full();
|
||||
let calls = calls
|
||||
.as_ref()
|
||||
.filter(|calls| calls.generation == generation);
|
||||
loop {
|
||||
let outstanding = OUTSTANDING.load(Ordering::SeqCst);
|
||||
let outstanding = calls.map_or(0, |calls| calls.outstanding.load(Ordering::SeqCst));
|
||||
if outstanding == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -260,6 +464,18 @@ pub fn shutdown(timeout: Duration) {
|
||||
let Some(current) = RUNTIME.load_full() else {
|
||||
return;
|
||||
};
|
||||
if current.generation != generation {
|
||||
// The child inherited the parent's installed runtime. Its worker
|
||||
// threads do not exist here, so waiting on its counter or calling
|
||||
// `shutdown_timeout` would wait for work that can never finish and
|
||||
// join threads that can never exit. Remove the slot in ordinary
|
||||
// context and deliberately leak the instance: inherited `Arc` clones
|
||||
// may still be dropped in this process, and the leaked reference
|
||||
// keeps a dropped clone from becoming the final owner.
|
||||
RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None);
|
||||
std::mem::forget(current);
|
||||
return;
|
||||
}
|
||||
RUNTIME.compare_and_swap(&Some(Arc::clone(¤t)), None);
|
||||
match Arc::try_unwrap(current) {
|
||||
Ok(tagged) => {
|
||||
@@ -320,7 +536,7 @@ impl Runtime for LanceRuntime {
|
||||
/// awaits its `JoinHandle`. `Handle::try_current` pins that nested call
|
||||
/// to whatever runtime is already executing it, so only the first,
|
||||
/// outermost call of a chain -- one running on a thread outside any
|
||||
/// runtime -- ever consults [`get_runtime`] or [`OUTSTANDING`].
|
||||
/// runtime -- ever consults [`get_runtime`] or [`OutstandingGuard`].
|
||||
fn spawn<F>(fut: F) -> Self::JoinHandle
|
||||
where
|
||||
F: Future<Output = ()> + Send + 'static,
|
||||
@@ -391,14 +607,14 @@ where
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// RUNTIME, GENERATION, OUTSTANDING, and ATFORK_INSTALLED are process-wide
|
||||
// RUNTIME, CALLS, GENERATION, and ATFORK_INSTALLED are process-wide
|
||||
// statics, and Rust's test harness runs tests in parallel by default,
|
||||
// so separate test functions below would otherwise race each other
|
||||
// through this shared state (this reproduced in CI: one test's
|
||||
// in-flight task got reclaimed by a *different* test's concurrent
|
||||
// `shutdown()` call, and another observed `OUTSTANDING` left non-zero
|
||||
// by a still-running sibling). Every test takes this lock first so
|
||||
// only one of them touches the shared runtime state at a time; a
|
||||
// `shutdown()` call, and another observed the in-flight counter left
|
||||
// non-zero by a still-running sibling). Every test takes this lock first
|
||||
// so only one of them touches the shared runtime state at a time; a
|
||||
// poisoned lock (a previous test's genuine failure) is still honored
|
||||
// rather than cascading into every later test as an unrelated panic.
|
||||
static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
@@ -464,6 +680,95 @@ mod tests {
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_on_interruptible_aborts_and_drops_future() {
|
||||
use std::sync::mpsc;
|
||||
|
||||
Python::initialize();
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (dropped_tx, dropped_rx) = mpsc::channel();
|
||||
|
||||
struct DropNotify(Option<mpsc::Sender<()>>);
|
||||
impl Drop for DropNotify {
|
||||
fn drop(&mut self) {
|
||||
if let Some(tx) = self.0.take() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fut = async move {
|
||||
started_tx.send(()).unwrap();
|
||||
let _notify = DropNotify(Some(dropped_tx));
|
||||
std::future::pending::<()>().await;
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), pyo3::PyErr>(())
|
||||
};
|
||||
let result = block_on_interruptible_with(fut, || {
|
||||
Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted"))
|
||||
});
|
||||
|
||||
assert!(result.is_err());
|
||||
started_rx
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.expect("query task never started");
|
||||
dropped_rx
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.expect("interrupted query future was not dropped");
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_on_interruptible_maps_panic() {
|
||||
Python::initialize();
|
||||
let result = block_on_interruptible(async {
|
||||
panic!("boom");
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), pyo3::PyErr>(())
|
||||
});
|
||||
assert!(
|
||||
result
|
||||
.expect_err("panic must become a Python exception")
|
||||
.to_string()
|
||||
.contains("rust future panicked: boom")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_on_interruptible_rejects_current_thread_runtime() {
|
||||
Python::initialize();
|
||||
let runtime = runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("current-thread runtime");
|
||||
let error = runtime
|
||||
.block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) })
|
||||
.expect_err("current-thread runtime must be rejected");
|
||||
assert!(error.to_string().contains("current-thread"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_block_on_interruptible_from_single_worker_runtime() {
|
||||
Python::initialize();
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let _worker_threads = TestWorkerThreads::new(1);
|
||||
shutdown(Duration::from_secs(5));
|
||||
|
||||
let (done_tx, done_rx) = mpsc::channel();
|
||||
drop(get_runtime().spawn(async move {
|
||||
let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) });
|
||||
let _ = done_tx.send(result.map_err(|error| error.to_string()));
|
||||
}));
|
||||
|
||||
let result = done_rx
|
||||
.recv_timeout(Duration::from_secs(10))
|
||||
.expect("single-worker runtime made no progress");
|
||||
assert_eq!(result.expect("single-worker query failed"), 42);
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
// Adapted from the concurrent reproducer that found the original bug:
|
||||
// many threads hammering the runtime while shutdown races them, not
|
||||
// just the sequential rebuild path above. Before every reader held its
|
||||
@@ -570,7 +875,7 @@ mod tests {
|
||||
use std::sync::mpsc;
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
|
||||
// Clean slate: no runtime installed, OUTSTANDING at zero.
|
||||
// Clean slate: no runtime installed, no in-flight calls.
|
||||
shutdown(Duration::from_secs(5));
|
||||
|
||||
let (installer_ready_tx, installer_ready_rx) = mpsc::channel::<()>();
|
||||
@@ -596,6 +901,312 @@ mod tests {
|
||||
// shutdown must have waited for the install to finish and then
|
||||
// retired it, not returned early and left it stranded.
|
||||
assert!(RUNTIME.load_full().is_none());
|
||||
assert_eq!(OUTSTANDING.load(Ordering::SeqCst), 0);
|
||||
let calls = CALLS
|
||||
.load_full()
|
||||
.expect("install race left no generation counter");
|
||||
assert_eq!(calls.outstanding.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
/// Keep fork-test runtimes small; see [`TEST_WORKER_THREADS`].
|
||||
#[cfg(target_os = "linux")]
|
||||
struct TestWorkerThreads(usize);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl TestWorkerThreads {
|
||||
fn new(worker_threads: usize) -> Self {
|
||||
Self(TEST_WORKER_THREADS.swap(worker_threads, Ordering::SeqCst))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Drop for TestWorkerThreads {
|
||||
fn drop(&mut self) {
|
||||
TEST_WORKER_THREADS.store(self.0, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` in a forked child and return the `i32` it reports, or `None`
|
||||
/// if the child did not report within the bound. The child leaves with
|
||||
/// `_exit` so it never runs destructors inherited from the test process.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn run_in_forked_child<F>(f: F) -> Option<i32>
|
||||
where
|
||||
F: FnOnce() -> i32,
|
||||
{
|
||||
let mut pipe = [0; 2];
|
||||
assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0, "pipe failed");
|
||||
let (read_fd, write_fd) = (pipe[0], pipe[1]);
|
||||
|
||||
let pid = unsafe { libc::fork() };
|
||||
assert!(pid >= 0, "fork failed");
|
||||
if pid == 0 {
|
||||
unsafe { libc::close(read_fd) };
|
||||
let result = f();
|
||||
let bytes = result.to_ne_bytes();
|
||||
let written = unsafe { libc::write(write_fd, bytes.as_ptr().cast(), bytes.len()) };
|
||||
unsafe { libc::close(write_fd) };
|
||||
unsafe {
|
||||
libc::_exit(if written == bytes.len() as isize {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
unsafe { libc::close(write_fd) };
|
||||
let mut poll_fd = libc::pollfd {
|
||||
fd: read_fd,
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
let ready = loop {
|
||||
let ready = unsafe { libc::poll(&mut poll_fd, 1, 10_000) };
|
||||
if ready >= 0 {
|
||||
break ready;
|
||||
}
|
||||
let error = std::io::Error::last_os_error();
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"poll failed: {error}"
|
||||
);
|
||||
};
|
||||
if ready == 0 {
|
||||
unsafe { libc::kill(pid, libc::SIGKILL) };
|
||||
}
|
||||
|
||||
let mut result = None;
|
||||
if ready == 1 {
|
||||
let mut bytes = [0u8; std::mem::size_of::<i32>()];
|
||||
let read = loop {
|
||||
let read = unsafe { libc::read(read_fd, bytes.as_mut_ptr().cast(), bytes.len()) };
|
||||
if read >= 0 {
|
||||
break read;
|
||||
}
|
||||
let error = std::io::Error::last_os_error();
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"read failed: {error}"
|
||||
);
|
||||
};
|
||||
if read == bytes.len() as isize {
|
||||
result = Some(i32::from_ne_bytes(bytes));
|
||||
}
|
||||
}
|
||||
unsafe { libc::close(read_fd) };
|
||||
|
||||
let mut status = 0;
|
||||
loop {
|
||||
let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
|
||||
if waited == pid {
|
||||
break;
|
||||
}
|
||||
let error = std::io::Error::last_os_error();
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"waitpid failed: {error}"
|
||||
);
|
||||
}
|
||||
if ready == 0 {
|
||||
return None;
|
||||
}
|
||||
assert_eq!(status, 0, "forked child did not exit successfully");
|
||||
result
|
||||
}
|
||||
|
||||
// The child inherits the parent's installed runtime and its outstanding
|
||||
// count, but not the worker thread that would ever release that count.
|
||||
// Its exit-time shutdown must therefore ignore both: waiting for parent
|
||||
// work would burn the whole grace period, and retiring the inherited
|
||||
// runtime would try to join worker threads that do not exist here.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_forked_child_shutdown_does_not_wait_for_parent_work() {
|
||||
use std::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let _worker_threads = TestWorkerThreads::new(2);
|
||||
shutdown(Duration::from_secs(5));
|
||||
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel::<()>();
|
||||
let (done_tx, done_rx) = mpsc::channel::<()>();
|
||||
drop(LanceRuntime::spawn(async move {
|
||||
started_tx.send(()).unwrap();
|
||||
let _ = release_rx.await;
|
||||
let _ = done_tx.send(());
|
||||
}));
|
||||
started_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("parent task did not start");
|
||||
|
||||
let child_result = run_in_forked_child(|| {
|
||||
// Much longer than the watchdog: if this waits for inherited
|
||||
// parent work at all, the child fails to report in time instead
|
||||
// of the test comparing two elapsed durations.
|
||||
shutdown(Duration::from_secs(30));
|
||||
i32::from(RUNTIME.load_full().is_some())
|
||||
});
|
||||
assert_eq!(
|
||||
child_result,
|
||||
Some(0),
|
||||
"child shutdown waited for parent work or retired the inherited runtime"
|
||||
);
|
||||
|
||||
release_tx.send(()).unwrap();
|
||||
done_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("parent task was disturbed by the forked child");
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
// A child that builds its own runtime must drain that runtime's own
|
||||
// work, and only that work: the parent's held task is still outstanding
|
||||
// in the inherited copy of the counter but can never finish here.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_forked_child_drains_its_own_runtime_without_waiting_for_parent_work() {
|
||||
use std::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let _worker_threads = TestWorkerThreads::new(2);
|
||||
shutdown(Duration::from_secs(5));
|
||||
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel::<()>();
|
||||
let (done_tx, done_rx) = mpsc::channel::<()>();
|
||||
drop(LanceRuntime::spawn(async move {
|
||||
started_tx.send(()).unwrap();
|
||||
let _ = release_rx.await;
|
||||
let _ = done_tx.send(());
|
||||
}));
|
||||
started_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("parent task did not start");
|
||||
|
||||
let child_result = run_in_forked_child(|| {
|
||||
let child_done = Arc::new(AtomicBool::new(false));
|
||||
let child_done_flag = Arc::clone(&child_done);
|
||||
let (task_started_tx, task_started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
let (child_tx, child_rx) = mpsc::channel();
|
||||
drop(LanceRuntime::spawn(async move {
|
||||
task_started_tx.send(()).unwrap();
|
||||
let _ = release_rx.await;
|
||||
child_done_flag.store(true, Ordering::SeqCst);
|
||||
let _ = child_tx.send(());
|
||||
}));
|
||||
task_started_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("child task did not start");
|
||||
|
||||
// Keep the child's own task outstanding while shutdown starts,
|
||||
// then release it once the shutdown thread is about to enter.
|
||||
let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel();
|
||||
let shutdown_thread = std::thread::spawn(move || {
|
||||
shutdown_ready_tx.send(()).unwrap();
|
||||
shutdown(Duration::from_secs(30));
|
||||
});
|
||||
shutdown_ready_rx.recv().unwrap();
|
||||
release_tx.send(()).unwrap();
|
||||
shutdown_thread.join().unwrap();
|
||||
|
||||
let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok()
|
||||
&& child_done.load(Ordering::SeqCst);
|
||||
let retired = RUNTIME.load_full().is_none();
|
||||
let rebuilt = block_on(async { 40 + 2 }) == 42;
|
||||
shutdown(Duration::from_secs(30));
|
||||
i32::from(!(drained && retired && rebuilt))
|
||||
});
|
||||
assert_eq!(
|
||||
child_result,
|
||||
Some(0),
|
||||
"child did not drain its own runtime or waited for parent work"
|
||||
);
|
||||
|
||||
release_tx.send(()).unwrap();
|
||||
done_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("parent task was disturbed by the forked child");
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
// A guard created before `fork()` belongs to the parent generation. If
|
||||
// the child drops that inherited guard, it must decrement the counter it
|
||||
// was created against, not the child's fresh counter (a naive reset in
|
||||
// the child would underflow here and make shutdown wait forever). The
|
||||
// second parent guard stays held across the fork without being dropped
|
||||
// in the child, so this also proves the child does not wait for work
|
||||
// that can only finish in the parent.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_inherited_guard_does_not_corrupt_child_generation_counter() {
|
||||
use std::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let _worker_threads = TestWorkerThreads::new(2);
|
||||
shutdown(Duration::from_secs(5));
|
||||
|
||||
// This test forks before any runtime exists, so make the hook
|
||||
// initialization explicit through the same path the first top-level
|
||||
// call uses; otherwise this test only works after a preceding test
|
||||
// has installed the process-wide hook.
|
||||
ensure_atfork_installed();
|
||||
// Stands in for a top-level call that was in progress when the
|
||||
// parent forked and is dropped by the child after it starts work.
|
||||
let inherited_guard = OutstandingGuard::new();
|
||||
// Stays outstanding in the parent for the whole fork, as parent work
|
||||
// that no child task can ever complete.
|
||||
let parent_guard = OutstandingGuard::new();
|
||||
|
||||
let child_result = run_in_forked_child(move || {
|
||||
let child_done = Arc::new(AtomicBool::new(false));
|
||||
let child_done_flag = Arc::clone(&child_done);
|
||||
let (task_started_tx, task_started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel::<()>();
|
||||
let (child_tx, child_rx) = mpsc::channel();
|
||||
drop(LanceRuntime::spawn(async move {
|
||||
task_started_tx.send(()).unwrap();
|
||||
let _ = release_rx.await;
|
||||
child_done_flag.store(true, Ordering::SeqCst);
|
||||
let _ = child_tx.send(());
|
||||
}));
|
||||
task_started_rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("child task did not start");
|
||||
|
||||
// Drop the inherited guard while the child has its own task
|
||||
// outstanding, so a shared or reset counter would visibly
|
||||
// perturb the child's accounting.
|
||||
drop(inherited_guard);
|
||||
|
||||
let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel();
|
||||
let shutdown_thread = std::thread::spawn(move || {
|
||||
shutdown_ready_tx.send(()).unwrap();
|
||||
shutdown(Duration::from_secs(30));
|
||||
});
|
||||
shutdown_ready_rx.recv().unwrap();
|
||||
release_tx.send(()).unwrap();
|
||||
shutdown_thread.join().unwrap();
|
||||
|
||||
let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok()
|
||||
&& child_done.load(Ordering::SeqCst);
|
||||
let retired = RUNTIME.load_full().is_none();
|
||||
i32::from(!(drained && retired))
|
||||
});
|
||||
assert_eq!(
|
||||
child_result,
|
||||
Some(0),
|
||||
"inherited guard corrupted the child generation counter"
|
||||
);
|
||||
|
||||
drop(parent_guard);
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
|
||||
+9
-2
@@ -31,6 +31,11 @@ impl Query {
|
||||
self.inner.id()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn job_id(&self) -> Option<String> {
|
||||
self.inner.job_id()
|
||||
}
|
||||
|
||||
pub fn describe(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -63,6 +68,7 @@ impl Query {
|
||||
#[derive(Clone)]
|
||||
pub struct QueryDescription {
|
||||
id: Uuid,
|
||||
job_id: Option<String>,
|
||||
status: String,
|
||||
progress: Option<f64>,
|
||||
expires_at: Option<DateTime<Utc>>,
|
||||
@@ -72,8 +78,8 @@ pub struct QueryDescription {
|
||||
impl QueryDescription {
|
||||
fn __repr__(&self) -> String {
|
||||
format!(
|
||||
"QueryDescription(id={:?}, status={:?}, progress={:?}, expires_at={:?})",
|
||||
self.id, self.status, self.progress, self.expires_at
|
||||
"QueryDescription(id={:?}, job_id={:?}, status={:?}, progress={:?}, expires_at={:?})",
|
||||
self.id, self.job_id, self.status, self.progress, self.expires_at
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +88,7 @@ impl From<lancedb::sql::QueryDescription> for QueryDescription {
|
||||
fn from(description: lancedb::sql::QueryDescription) -> Self {
|
||||
Self {
|
||||
id: description.id,
|
||||
job_id: description.job_id,
|
||||
status: description.status.to_string(),
|
||||
progress: description.progress,
|
||||
expires_at: description.expires_at,
|
||||
|
||||
+928
-43
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@ use pyo3::{
|
||||
exceptions::{PyRuntimeError, PyValueError},
|
||||
pyfunction,
|
||||
};
|
||||
use rattler_conda_types::{MatchSpec, ParseStrictness};
|
||||
|
||||
/// A wrapper around a rust builder
|
||||
///
|
||||
@@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> {
|
||||
.map_err(|e| PyValueError::new_err(e.to_string()))
|
||||
}
|
||||
|
||||
#[pyfunction(name = "_validate_conda_requirement")]
|
||||
pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> {
|
||||
MatchSpec::from_str(requirement, ParseStrictness::Lenient)
|
||||
.map(|_| ())
|
||||
.map_err(|error| PyValueError::new_err(error.to_string()))
|
||||
}
|
||||
|
||||
/// Parse field references with the same identifier syntax as Lance writes.
|
||||
#[pyfunction(name = "_parse_field_path")]
|
||||
pub fn parse_field_path(path: &str) -> PyResult<Vec<String>> {
|
||||
@@ -70,3 +78,14 @@ pub fn parse_field_path(path: &str) -> PyResult<Vec<String>> {
|
||||
/// A wrapper around a LanceDB type to allow it to be used in Python
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PyLanceDB<T>(pub T);
|
||||
/// Validate the Function retry wire contract using the same rules as Rust APIs.
|
||||
#[pyo3::pyfunction]
|
||||
pub fn validate_function_retry_policy(json: &str) -> pyo3::PyResult<()> {
|
||||
let policy: lancedb::function::FunctionRetryPolicy =
|
||||
serde_json::from_str(json).map_err(|error| {
|
||||
pyo3::exceptions::PyValueError::new_err(format!("invalid retry_policy: {error}"))
|
||||
})?;
|
||||
policy
|
||||
.validate()
|
||||
.map_err(|error| pyo3::exceptions::PyValueError::new_err(error.to_string()))
|
||||
}
|
||||
|
||||
Generated
+421
-256
@@ -1,5 +1,5 @@
|
||||
version = 1
|
||||
revision = 3
|
||||
revision = 5
|
||||
requires-python = ">=3.10"
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'win32'",
|
||||
@@ -232,16 +232,16 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "anyio"
|
||||
version = "4.14.1"
|
||||
version = "4.16.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
|
||||
{ name = "idna" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.15'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3b/72/5562aabb8dd7181e8e860622a38bea08d17842b99ecd4c91f84ac95251b0/anyio-4.14.1.tar.gz", hash = "sha256:8d648a3544c1a700e3ff78615cd679e4c5c3f149904287e73687b2596963629e", size = 254831, upload-time = "2026-06-24T20:56:06.017Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b0/7b/90df4a0a816d98d6ea26f559d87836d494a2cf1fcf063be67df50a7bcc30/anyio-4.14.1-py3-none-any.whl", hash = "sha256:4e5533c5b8ff0a24f5d7a176cbe6877129cd183893f66b537f8f227d10527d72", size = 124875, upload-time = "2026-06-24T20:56:04.413Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -740,7 +740,8 @@ dependencies = [
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "peft" },
|
||||
{ name = "pillow" },
|
||||
{ name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "requests" },
|
||||
{ name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
@@ -841,59 +842,72 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "cryptography"
|
||||
version = "49.0.0"
|
||||
version = "50.0.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/1f/99/d1c90d6041656cc6ee229dc99cd67fd0cd5aec3c5f7d72fffc27cc750054/cryptography-49.0.0.tar.gz", hash = "sha256:f89660a348f4f78a92366240a61404e337586ef7f5909a2fef59ca88ef505493", size = 854345, upload-time = "2026-06-12T20:02:30.512Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/22/adf66990e63584a68dfb50c24f48a125c07b1699899381c8151e63ed458c/cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:966fe0e9c67490071f14c0d2b1cb2dfb3023c5ce39457343931415f08382f2db", size = 4032100, upload-time = "2026-06-12T20:02:32.143Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/41/3797cfaf69cae04a13ee78ebd83f0678d9c02b4779d21ce24445326f1a69/cryptography-49.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:36d1709f992593689b45bda411498d62c6e365f2ca00b84657d4dadd24de16db", size = 4692978, upload-time = "2026-06-12T20:01:21.305Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/8b/43011f7ebe515a8aa20d61f290a326cd890c2e738e16e59eaff8d9c3a412/cryptography-49.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e959b578856a3924bc0cbb710fc12c387b9412a951389f3ca61704a9e25f325", size = 4716422, upload-time = "2026-06-12T20:01:48.566Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4a/91/01ce7303a4579e6d3a6abef01bd322848e9ea7a219adcabc5048b9033571/cryptography-49.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:53ecee2e23f7169b6117e99fc8a944e5e50f79e69758a83b52a00cb98ab2b2d2", size = 4700503, upload-time = "2026-06-12T20:02:47.091Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/62/99/a2c95cf8293f07491e9e27c20cc4dcd18176d944e674679adeb1d0173fd6/cryptography-49.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:2eda353d8a27bcbcaa4cbed18994a74ab4d19a2ca897db188ea269ab9b71419b", size = 5309779, upload-time = "2026-06-12T20:02:08.987Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2afe9051da7ae7bd5905da5a949280c7d2bb75682e188f650a9d0f2756b834c6", size = 4749683, upload-time = "2026-06-12T20:02:03.335Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a3/5b/c5246635d5fd3b64e0d45ae10e99fd32fe9676a79915ccfe5a61ba9af1a5/cryptography-49.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:0b82e28ee398a386f0807bba7884d30f25218855690f45115831bcce5d90822c", size = 4337874, upload-time = "2026-06-12T20:02:54.323Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/88/05563c7fe2e914e87d1a536d06fe83e66b4e1d95cb593e05aea375531da8/cryptography-49.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:ccac2bfebc306b862133e3bb71f3f6ee8bb525240089b2d952e4144b3a6d5da7", size = 4700283, upload-time = "2026-06-12T20:01:34.822Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/b6/d7696e4e890d6ae1469935164c9e5215c557671cb78d6e3f458ccceaa632/cryptography-49.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:d0527ce944105f257f605a827d6ebead966c752038b6e8656abb9c5edee6fc68", size = 5265844, upload-time = "2026-06-12T20:01:24.09Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/3c/f3ad17eecc1a57b0ba236dc01f90e783c51f4a2f35f64777cc4f47a184b2/cryptography-49.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:cbc77da8c523d5abd028635ba850a6966fcee2c82e2bf65a41d1d8afe0f98be9", size = 4749290, upload-time = "2026-06-12T20:01:30.848Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/01/339573cf1023163a400b0b5d16f6d507de413b9f60be6fd1b77feeaf6737/cryptography-49.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b87e65d263b3e5d3bb92a57e2a6638e2f31110fa7aa890c7b2dbba42248d0a3f", size = 4834612, upload-time = "2026-06-12T20:01:29.246Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/fd/577302e213a1be9468f92d1afef66fcf1ef83d516819d9992ca547f592bd/cryptography-49.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66ec79c3904820572d7e987abdf304281f141d37ad9a489b8e97066e7b9b6459", size = 4980804, upload-time = "2026-06-12T20:01:42.853Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/09/f42b1d190c5ba75f72062a387f8030d1d75f6ab035788f1d9c4b01de6525/cryptography-49.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:e5dfc1e64de5677cec922ffa8da89c546d0415bf6efdf081842e5d44c84e1f0e", size = 3810026, upload-time = "2026-06-12T20:02:39.262Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/9e/db72b3ae7fc9cfad53e630e56c6ae83b9b6ff0bf3718ffb8012d20b3aabf/cryptography-49.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:73a205dce83953d131a4aa1e0fd917a2fd1c5b1eef251e9d7152efefcbf5caf7", size = 4013892, upload-time = "2026-06-12T20:02:10.735Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/12/c48a424f38db03027be9f7ed5c7dc5de9933dbee992865f98b13727a009d/cryptography-49.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:196ecd6a36e4e9aa10270393bb98d8df88fccee0bf1e5128b91ae4eb4375896d", size = 4678835, upload-time = "2026-06-12T20:02:48.743Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/68/28/8a3ad4653662c93fc44dc4e5d8fd374c25c42e07b34bbfbadf49cf57a5a8/cryptography-49.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7abcee80084cda3f7691f3eb1ce480d8df49cec637b429aa35986c1de71738aa", size = 4697239, upload-time = "2026-06-12T20:02:56.03Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/b2/2193fc74f81aee4f9b62733133b73b5176718932ed8f2e4b03fa040480a6/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:4ae387c9cb68ea569ca17e490d66d8142b81c3cc814bf179974b7d146e490bbb", size = 4685593, upload-time = "2026-06-12T20:02:50.666Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/47/f1/1d3eaa243bfc5de4a187b22aa8c048b3e4980bfbe830ac46e6bac2e66947/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:f37d847238971164fdbc68ade6f6574aecc9c0af714190e2083429ff68f4ce9d", size = 5289961, upload-time = "2026-06-12T20:01:46.468Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/58/39/2d51306721330c486495853eda1c567880ff036de15a14c4b74f399934af/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:c2bc30226390d60ea19d9f82b19db005fe0452154a23c1c410c12ea801e43561", size = 4731145, upload-time = "2026-06-12T20:02:16.832Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/17/50/983e838c7fd0d87fd8c969bcdd328edaf5f756e38df5281637424c155873/cryptography-49.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:07cab27cc7b7e0fd28e5e26bb9eeedde5c135c868b46de4a27845abe94af6122", size = 4321719, upload-time = "2026-06-12T20:02:52.611Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a7/f5/8f571d7e27c55bce9f76f026143bcb1e040a4233149ecca0bea5fa5dd5f7/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:b20133d204d2bb56ba047642199603876c872026ca53e79c35b83772ab2cc505", size = 4685209, upload-time = "2026-06-12T20:02:07.282Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e7/84/0e27016a6fc5a0886f797018b26aa42f40c09a82332bff77822a451deaaa/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:b970c6da94d5bb18629db453d14f2a1300f6bf59b61e9b82377931ef95504866", size = 5246285, upload-time = "2026-06-12T20:01:32.439Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/11/2d/5e1fb307cb5931881516b464c98774b3f2c36b5d4bb9a2830253cf553cad/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d8ecde755e2e91bf773fc94e8c9d730cd7f2007004cb492263a794ec3899a1c8", size = 4730441, upload-time = "2026-06-12T20:02:01.469Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/c0/bff5a02ee731d207d6a1ed51732549d8c53d2bc8da1d10ec6f2844201d68/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e3fb64c420688e5319ae25113a354015abbd8dffbfbc41781a1ea66fc7622ac3", size = 4815869, upload-time = "2026-06-12T20:01:36.574Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b9/26/814681d14248d95d73d5c3eea0c39a94eb8302df966f670a2c60de90974b/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:32703d93296f5c1f4b53349ad3a250c2cae0fdecd3a3dd5d47e616d8d616af27", size = 4960948, upload-time = "2026-06-12T20:02:18.688Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4c/fe/93ecac273d3738939d023612ad12cca9a3740a5345d69fda04134c43fd96/cryptography-49.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:33cd0565932807baddb67b96dbee92f2c374b5c89dee09fd74079aeb8c8dba61", size = 3799153, upload-time = "2026-06-12T20:01:39.059Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/19/2a/5bb823f5bedcf80718cea7fbc95ec5515cca3769633c4b01a32be7f30e7c/cryptography-49.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ec5e529fb80935c94fe7b729f9972b50e351a0e6b50aa294fd5cabb109fcc29a", size = 4025947, upload-time = "2026-06-12T20:01:25.745Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3d/df/40577043ca124e17012f408ddddaeb213b856336ac82ddb3bc915f39e29f/cryptography-49.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f78ff2c9ed8dc2d036b0f4d640e22522213d047c1b14e61205a7e55c80a494d4", size = 4692429, upload-time = "2026-06-12T20:01:53.628Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2c/99/2d13299eb3dd27b02dcfaafcc91d6b5cb3329f7cbd6d8f51921acd566c1a/cryptography-49.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:35b151772baff2c74cba7fa290ceaff4c3b11c0c881eb93eb5dbc05a7cfbba18", size = 4700968, upload-time = "2026-06-12T20:02:45.383Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/4d/9c0cd02f95e2602dd5e563da149ee0830abef3537be8b34dc56281ebe27a/cryptography-49.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0f21641cf4b30fca7aee061ced0ec7ad7b073518088b7c9969a297c0ae796c69", size = 4697758, upload-time = "2026-06-12T20:01:41.13Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/01/186c825898477d77e2324d5360fefe622ff1d8d1963ec0554e2cada8ec77/cryptography-49.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:9e82dcc8e56052715fb18b2429e3bca4823b1629136a2084fc45a9a5cecb9b64", size = 5298863, upload-time = "2026-06-12T20:02:24.579Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b8/7b/62cbbab75d0659865bf0273790031544a0b16c8072d258f9428dcd8190dc/cryptography-49.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6f2debedf9ca60cf1d5bd466475638af5130f89965605cd818484d19987d3a21", size = 4735983, upload-time = "2026-06-12T20:01:50.14Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/72/3e798c064bc39e471008075d0f9bc9daf77a80879c092e4a8e170c585ed4/cryptography-49.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:8c25ceb16df5b9435f3f6a9829204985b0e0cbee3b48aacd432c7d2c850b44d9", size = 4334173, upload-time = "2026-06-12T20:01:44.743Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/ee/6fca21d1ac73e06f8bef71940abfd4d2f6472b4bca284d770f32bd4086f6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:28d8b15e6275f12c8a207dc309dfa957903c927d08d0cc937ee3f63f200693cc", size = 4697298, upload-time = "2026-06-12T20:02:20.918Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/d0/a5fcd3515f0bae49a7b6d0413cc1bdccdcc1fc0047037a0d480642cdc5d6/cryptography-49.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6fc361c34fb6aac015ce19435876635e5c6d21db31998b0920f675f131e043b8", size = 5254338, upload-time = "2026-06-12T20:02:22.737Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/84/84fe36f19caf857d61cb7fc9c63035a47ffabd84ea12d1d393148efa3615/cryptography-49.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2400ef9c9e2299a25614eb1dea3db54a69b1349efd043bfac9c67630d136df36", size = 4735650, upload-time = "2026-06-12T20:02:41.389Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/a0/db537264e234f7273a73ec020873d6d6b39dfd8a53db78b550ca8320440e/cryptography-49.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:67e1d20ad9ef3a563c59ef22e7a8a0b8210bd26604369ea4a30a7c66aefe504e", size = 4834820, upload-time = "2026-06-12T20:01:51.847Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/93/77/8df9eb486495979bccecd1062e2eaf435250e84437040295b57d09048b0b/cryptography-49.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:42b0684e0e40cf26122427802486f6d93aea593612603a94fbf260c7eb1e9c1b", size = 4967968, upload-time = "2026-06-12T20:02:12.524Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c2/e6/f60198ea8d9dfa15fff9ed4ca02ce362f6eadd9ba757dcc50634c4257b63/cryptography-49.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:026ac7423e6fa66872d3bf889be5974507da3944f866f704fa200eadacd00001", size = 3785547, upload-time = "2026-06-12T20:02:26.847Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/63/d3/4a83af35d65e3fad632c926fad684c193ea4398569ccb0bbbc7fe8f5dc9a/cryptography-49.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:fc1e275c2f1d97b1a6450b8b0ea3ebfa6e087a611c2b26cb2404d48588abab7b", size = 3993685, upload-time = "2026-06-12T20:02:14.883Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d6/a7/f9dac0ab7f80368c56993a7bf638ef9935f825c91902798481fac0898138/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c83782480a4a9da4d0feb51950131ba32e12e70813848b3343f6e18c28a66838", size = 4676239, upload-time = "2026-06-12T20:02:28.793Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d7/70/2ba3769dd0ae167e2f33dfa9592d45db6ff9a61d62ca1a5b3d1bdd09068f/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b39efa323140595abd3ecca8529d321ae50f55f3aa3ba9cc81ea56a6011953d5", size = 4715584, upload-time = "2026-06-12T20:01:27.495Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/94/64/2923570ac1c0bd3a737aa366ac3abbbbde273042308b8cde95e2364a6e6a/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:b47db11c2c3525083296069b98ac5221907455e989ae0c2e3008bde851921615", size = 4675885, upload-time = "2026-06-12T20:01:55.49Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/f8/614dc7e051418cfe53d55173c1e24c6b0085e89996fe90508c2fdf769aef/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:084ef1af862eb07ec46d25f68689f2102a9fc0e05ce7b80f14f5fe51e4eef0f6", size = 4715449, upload-time = "2026-06-12T20:02:05.469Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/50/a9caea39ad19c431c1a3f8a31114df65b260cdfe67786b6c7e7c040c4c44/cryptography-49.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be9fcb48a55f023493482827d4f459bd263cc20efde64f204b97c123201850c6", size = 3783731, upload-time = "2026-06-12T20:02:43.319Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -901,7 +915,7 @@ name = "cuda-bindings"
|
||||
version = "13.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-pathfinder", marker = "sys_platform == 'linux'" },
|
||||
{ name = "cuda-pathfinder" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/21/8464d133752951c154feafb3b65c297e7d80f301183d220bec4c830f1441/cuda_bindings-13.3.1-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:120fcc53d57903df529c3486962c56528cba5b7d6c57c99537320ed9922c8b86", size = 6073403, upload-time = "2026-05-29T23:11:36.22Z" },
|
||||
@@ -936,37 +950,37 @@ wheels = [
|
||||
|
||||
[package.optional-dependencies]
|
||||
cublas = [
|
||||
{ name = "nvidia-cublas", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cublas" },
|
||||
]
|
||||
cudart = [
|
||||
{ name = "nvidia-cuda-runtime", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cuda-runtime" },
|
||||
]
|
||||
cufft = [
|
||||
{ name = "nvidia-cufft", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cufft" },
|
||||
]
|
||||
cufile = [
|
||||
{ name = "nvidia-cufile", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cufile" },
|
||||
]
|
||||
cupti = [
|
||||
{ name = "nvidia-cuda-cupti", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cuda-cupti" },
|
||||
]
|
||||
curand = [
|
||||
{ name = "nvidia-curand", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-curand" },
|
||||
]
|
||||
cusolver = [
|
||||
{ name = "nvidia-cusolver", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cusolver" },
|
||||
]
|
||||
cusparse = [
|
||||
{ name = "nvidia-cusparse", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cusparse" },
|
||||
]
|
||||
nvjitlink = [
|
||||
{ name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-nvjitlink" },
|
||||
]
|
||||
nvrtc = [
|
||||
{ name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cuda-nvrtc" },
|
||||
]
|
||||
nvtx = [
|
||||
{ name = "nvidia-nvtx", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-nvtx" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -975,7 +989,8 @@ version = "54.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cloudpickle" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/60/90/886f7e9cf827f07ebd60bd293e54e0a028a50dd49bbaef0ee42aae1981ea/datafusion-54.0.0.tar.gz", hash = "sha256:cfe7e8dfc026efc05824f49b53ad6a72caf5c2d6820759b6212a09e245a427ed", size = 276448, upload-time = "2026-06-29T11:19:34.816Z" }
|
||||
@@ -1125,7 +1140,7 @@ name = "exceptiongroup"
|
||||
version = "1.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
|
||||
wheels = [
|
||||
@@ -1544,16 +1559,16 @@ resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "cachetools", marker = "python_full_version < '3.11'" },
|
||||
{ name = "certifi", marker = "python_full_version < '3.11'" },
|
||||
{ name = "httpx", marker = "python_full_version < '3.11'" },
|
||||
{ name = "ibm-cos-sdk", marker = "python_full_version < '3.11'" },
|
||||
{ name = "lomond", marker = "python_full_version < '3.11'" },
|
||||
{ name = "packaging", marker = "python_full_version < '3.11'" },
|
||||
{ name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "requests", marker = "python_full_version < '3.11'" },
|
||||
{ name = "tabulate", marker = "python_full_version < '3.11'" },
|
||||
{ name = "urllib3", marker = "python_full_version < '3.11'" },
|
||||
{ name = "cachetools" },
|
||||
{ name = "certifi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "ibm-cos-sdk" },
|
||||
{ name = "lomond" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pandas", version = "2.2.3", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "requests" },
|
||||
{ name = "tabulate" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c7/56/2e3df38a1f13062095d7bde23c87a92f3898982993a15186b1bfecbd206f/ibm_watsonx_ai-1.3.42.tar.gz", hash = "sha256:ee5be59009004245d957ce97d1227355516df95a2640189749487614fef674ff", size = 688651, upload-time = "2025-10-01T13:35:41.527Z" }
|
||||
wheels = [
|
||||
@@ -1578,17 +1593,17 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "cachetools", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "certifi", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "httpx", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "ibm-cos-sdk", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "lomond", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "packaging", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
|
||||
{ name = "cachetools" },
|
||||
{ name = "certifi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "ibm-cos-sdk" },
|
||||
{ name = "lomond" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" },
|
||||
{ name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },
|
||||
{ name = "requests", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "tabulate", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "urllib3", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "requests" },
|
||||
{ name = "tabulate" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/29/a3/c756b534696ab2f3f29882fdb7ca7198b7a5c94e10c0a3a327853d6d6b79/ibm_watsonx_ai-1.5.14.tar.gz", hash = "sha256:a756488bd57e87c0fc51be42dcba871143cfe0ac1e805c497c5047e1e4f13e9d", size = 735804, upload-time = "2026-06-22T12:32:43.85Z" }
|
||||
wheels = [
|
||||
@@ -1666,17 +1681,17 @@ resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "python_full_version < '3.11' and sys_platform == 'win32'" },
|
||||
{ name = "decorator", marker = "python_full_version < '3.11'" },
|
||||
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
|
||||
{ name = "jedi", marker = "python_full_version < '3.11'" },
|
||||
{ name = "matplotlib-inline", marker = "python_full_version < '3.11'" },
|
||||
{ name = "pexpect", marker = "python_full_version < '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
||||
{ name = "prompt-toolkit", marker = "python_full_version < '3.11'" },
|
||||
{ name = "pygments", marker = "python_full_version < '3.11'" },
|
||||
{ name = "stack-data", marker = "python_full_version < '3.11'" },
|
||||
{ name = "traitlets", marker = "python_full_version < '3.11'" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "decorator" },
|
||||
{ name = "exceptiongroup" },
|
||||
{ name = "jedi" },
|
||||
{ name = "matplotlib-inline" },
|
||||
{ name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
||||
{ name = "prompt-toolkit" },
|
||||
{ name = "pygments" },
|
||||
{ name = "stack-data" },
|
||||
{ name = "traitlets" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/40/18/f8598d287006885e7136451fdea0755af4ebcbfe342836f24deefaed1164/ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624", size = 5513971, upload-time = "2026-03-27T10:02:13.94Z" }
|
||||
wheels = [
|
||||
@@ -1701,18 +1716,18 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "python_full_version >= '3.11' and sys_platform == 'win32'" },
|
||||
{ name = "decorator", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "ipython-pygments-lexers", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "jedi", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "matplotlib-inline", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "pexpect", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
||||
{ name = "prompt-toolkit", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "psutil", marker = "python_full_version >= '3.11' and sys_platform != 'cygwin' and sys_platform != 'emscripten'" },
|
||||
{ name = "pygments", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "stack-data", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "traitlets", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "typing-extensions", marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "decorator" },
|
||||
{ name = "ipython-pygments-lexers" },
|
||||
{ name = "jedi" },
|
||||
{ name = "matplotlib-inline" },
|
||||
{ name = "pexpect", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
|
||||
{ name = "prompt-toolkit" },
|
||||
{ name = "psutil", marker = "sys_platform != 'cygwin' and sys_platform != 'emscripten'" },
|
||||
{ name = "pygments" },
|
||||
{ name = "stack-data" },
|
||||
{ name = "traitlets" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.12'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/59/165d3b4d75cc34add3122c4417ecb229085140ac573103c223cd01dde96f/ipython-9.15.0.tar.gz", hash = "sha256:da2819ce2aa83135257df830660b1176d986c3d2876db24df01974fa955b2756", size = 4442580, upload-time = "2026-06-26T11:03:35.913Z" }
|
||||
wheels = [
|
||||
@@ -1724,7 +1739,7 @@ name = "ipython-pygments-lexers"
|
||||
version = "1.1.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pygments", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "pygments" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393, upload-time = "2025-01-17T11:24:34.505Z" }
|
||||
wheels = [
|
||||
@@ -2003,7 +2018,8 @@ dependencies = [
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "overrides", marker = "python_full_version < '3.12'" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "tqdm" },
|
||||
]
|
||||
@@ -2014,7 +2030,8 @@ azure = [
|
||||
]
|
||||
clip = [
|
||||
{ name = "open-clip-torch" },
|
||||
{ name = "pillow" },
|
||||
{ name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "torch" },
|
||||
]
|
||||
dev = [
|
||||
@@ -2045,7 +2062,8 @@ embeddings = [
|
||||
{ name = "ollama" },
|
||||
{ name = "open-clip-torch" },
|
||||
{ name = "openai" },
|
||||
{ name = "pillow" },
|
||||
{ name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "requests" },
|
||||
{ name = "sentence-transformers" },
|
||||
{ name = "sentencepiece" },
|
||||
@@ -2055,11 +2073,11 @@ otel = [
|
||||
{ name = "opentelemetry-api" },
|
||||
]
|
||||
pylance = [
|
||||
{ name = "pylance", version = "15.0.0b4", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform == 'darwin'" },
|
||||
{ name = "pylance", version = "15.0.0b9", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform != 'darwin'" },
|
||||
{ name = "pylance" },
|
||||
]
|
||||
siglip = [
|
||||
{ name = "pillow" },
|
||||
{ name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "sentencepiece" },
|
||||
{ name = "torch" },
|
||||
{ name = "transformers" },
|
||||
@@ -2074,10 +2092,10 @@ tests = [
|
||||
{ name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
|
||||
{ name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },
|
||||
{ name = "polars" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "pyarrow-stubs" },
|
||||
{ name = "pylance", version = "15.0.0b4", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform == 'darwin'" },
|
||||
{ name = "pylance", version = "15.0.0b9", source = { registry = "https://pypi.fury.io/lance-format/" }, marker = "sys_platform != 'darwin'" },
|
||||
{ name = "pylance" },
|
||||
{ name = "pytest" },
|
||||
{ name = "pytest-asyncio" },
|
||||
{ name = "pytest-mock" },
|
||||
@@ -2125,12 +2143,11 @@ requires-dist = [
|
||||
{ name = "polars", marker = "extra == 'tests'", specifier = ">=0.19,<=1.32.3" },
|
||||
{ name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3.5.0" },
|
||||
{ name = "pyarrow", specifier = ">=16" },
|
||||
{ name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" },
|
||||
{ name = "pyarrow", marker = "extra == 'tests'", specifier = ">=16" },
|
||||
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
|
||||
{ name = "pydantic", specifier = ">=2.7.4,<3" },
|
||||
{ name = "pylance", marker = "sys_platform == 'darwin' and extra == 'tests'", specifier = "==15.0.0b4" },
|
||||
{ name = "pylance", marker = "sys_platform != 'darwin' and extra == 'tests'", specifier = "==15.0.0b9" },
|
||||
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b25" },
|
||||
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
|
||||
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
|
||||
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
|
||||
@@ -3023,7 +3040,7 @@ name = "nvidia-cudnn-cu13"
|
||||
version = "9.19.0.56"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "nvidia-cublas", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cublas" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f1/84/26025437c1e6b61a707442184fa0c03d083b661adf3a3eecfd6d21677740/nvidia_cudnn_cu13-9.19.0.56-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:6ed29ffaee1176c612daf442e4dd6cfeb6a0caa43ddcbeb59da94953030b1be4", size = 433781201, upload-time = "2026-02-03T20:40:53.805Z" },
|
||||
@@ -3035,7 +3052,7 @@ name = "nvidia-cufft"
|
||||
version = "12.0.0.61"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-nvjitlink" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" },
|
||||
@@ -3065,9 +3082,9 @@ name = "nvidia-cusolver"
|
||||
version = "12.0.4.66"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "nvidia-cublas", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cusparse", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cublas" },
|
||||
{ name = "nvidia-cusparse" },
|
||||
{ name = "nvidia-nvjitlink" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" },
|
||||
@@ -3079,7 +3096,7 @@ name = "nvidia-cusparse"
|
||||
version = "12.6.3.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "nvidia-nvjitlink", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-nvjitlink" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" },
|
||||
@@ -3280,10 +3297,10 @@ resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "python-dateutil", marker = "python_full_version < '3.11'" },
|
||||
{ name = "pytz", marker = "python_full_version < '3.11'" },
|
||||
{ name = "tzdata", marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "pytz" },
|
||||
{ name = "tzdata" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/9c/d6/9f8431bacc2e19dca897724cd097b1bb224a6ad5433784a44b587c7c13af/pandas-2.2.3.tar.gz", hash = "sha256:4f18ba62b61d7e192368b84517265a99b4d7ee8912f8708660fb4a366cc82667", size = 4399213, upload-time = "2024-09-20T13:10:04.827Z" }
|
||||
wheels = [
|
||||
@@ -3336,11 +3353,11 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12' or python_full_version >= '3.14'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and python_full_version < '3.14'" },
|
||||
{ name = "python-dateutil", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
|
||||
{ name = "pytz", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
|
||||
{ name = "tzdata", marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "pytz" },
|
||||
{ name = "tzdata" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" }
|
||||
wheels = [
|
||||
@@ -3405,9 +3422,9 @@ resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },
|
||||
{ name = "python-dateutil", marker = "python_full_version >= '3.14'" },
|
||||
{ name = "tzdata", marker = "(python_full_version >= '3.14' and sys_platform == 'emscripten') or (python_full_version >= '3.14' and sys_platform == 'win32')" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f8/87/4341c6252d1c47b08768c3d25ac487362bf403f0313ddae4a2a26c9b1b4c/pandas-3.0.3.tar.gz", hash = "sha256:696a4a00a2a2a35d4e5deb3fc946641b96c944f02230e4f76137fe35d806c4fc", size = 4651414, upload-time = "2026-05-11T18:54:29.21Z" }
|
||||
wheels = [
|
||||
@@ -3515,7 +3532,7 @@ name = "pexpect"
|
||||
version = "4.9.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "ptyprocess", marker = "(python_full_version < '3.14' and sys_platform == 'emscripten') or (python_full_version < '3.14' and sys_platform == 'win32') or (sys_platform != 'emscripten' and sys_platform != 'win32')" },
|
||||
{ name = "ptyprocess" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }
|
||||
wheels = [
|
||||
@@ -3526,6 +3543,11 @@ wheels = [
|
||||
name = "pillow"
|
||||
version = "12.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'linux'",
|
||||
"python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" },
|
||||
@@ -3616,6 +3638,109 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "13.0.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'win32'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'emscripten'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'linux'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version == '3.11.*' and sys_platform == 'linux'",
|
||||
"python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7a/b8/58d79332229482eb0d27c82973850808c19d37e5bdc14443d3417bd373f5/pillow-13.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79", size = 5568643, upload-time = "2026-10-16T22:15:44.474Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/39/4b/f2ed53d83aa44ac19599ac0a54897f867fafb95f406980d1e24083f8cbe3/pillow-13.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52", size = 4852329, upload-time = "2026-10-16T22:15:46.284Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/bb/9e30e8ed18c20800ee327a12107d5249ad8dc444867b3adfcc21654e3c71/pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d", size = 6519309, upload-time = "2026-10-16T22:15:48.14Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/9b/f38b7c4d8f599537e2d1a6d546cec9beef7536ff8f5c49a3f9c78179d8ac/pillow-13.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620", size = 6618042, upload-time = "2026-10-16T22:15:52.054Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/01/bc/9c2a969cb1b70201d04fa17fd5aedf02a732870b8da86bceaaa30b0ca385/pillow-13.0.0-cp312-cp312-win32.whl", hash = "sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27", size = 6515423, upload-time = "2026-10-16T22:15:56.25Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4a/a3/be5a1236efd085b3984e4305da8f179ae9dab80c991d2ad78f2bd5c4c843/pillow-13.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51", size = 2698943, upload-time = "2026-10-16T22:16:00.637Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/45/fbad9c7f5e2f1745c373a434d46072bc84eddfefaa28b852425ac957fda6/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c", size = 4190721, upload-time = "2026-10-16T22:16:27.524Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a2/bf/2074902a259a90692c5dbf132885d21671644cbbd3f690047516243a55db/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76", size = 4290236, upload-time = "2026-10-16T22:16:29.562Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ff/a5/3d1bb93b8ea38d15d21356c1b8e9f50971ac592aaa248f7fb71739094c0e/pillow-13.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981", size = 3723093, upload-time = "2026-10-16T22:16:31.249Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/84/a1/be060135d85187b25fa8b2573786c0e45c62ae27527fff5257675eb97f4a/pillow-13.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4", size = 5572253, upload-time = "2026-10-16T22:16:33.103Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b5/f4/0bf6f1ac9ba7ee2ffe9914aeb410a1035a0c1a3c42f122388d7fc950bc4b/pillow-13.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d", size = 4852269, upload-time = "2026-10-16T22:16:35.102Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/83/16/b603274617b3e6728da3a0133d4fba1ea8d7fbe0c4ea5fef9cbffa398b8b/pillow-13.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6", size = 6516058, upload-time = "2026-10-16T22:16:37.228Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/f2/1371707ce438ba9a43f9d24089828494ec6f9396e28cd7903aa704dd6306/pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d", size = 7142574, upload-time = "2026-10-16T22:16:39.172Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b9/a9/62cf68587f910bc87c5951bcb6e9430c7643a65076adf5f18b4bf350e2bd/pillow-13.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c", size = 6614295, upload-time = "2026-10-16T22:16:41.117Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/c9/9e9b48178649730299be0bafbf5f810a5b6977538f5a92d47e4ba5f5d608/pillow-13.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0", size = 7224841, upload-time = "2026-10-16T22:16:43.118Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8f/48/c44e91384b1b6c072a714a63d00608acc16a6a968735e478e4be4384e5ac/pillow-13.0.0-cp314-cp314-win32.whl", hash = "sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055", size = 6508694, upload-time = "2026-10-16T22:16:45.883Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/e2/7ad17747517e4c813dca78257d6bb593466f8231baf1384bc98d92745edb/pillow-13.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a", size = 7281830, upload-time = "2026-10-16T22:16:47.725Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/41/9f/e5b51f2ce8ef4563215334035403ce61a244f93a2e65c24a940131618f87/pillow-13.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4", size = 2695468, upload-time = "2026-10-16T22:16:49.515Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/73/a53502f731f6c84805a4ce87a8881e86d07a65aee64728b900d112dc703e/pillow-13.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa", size = 5578196, upload-time = "2026-10-16T22:16:51.291Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/21/50/7e949959a56b5559c78ef172b70fc6025706acb289f3f648a15329e4fa6f/pillow-13.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f", size = 4857276, upload-time = "2026-10-16T22:16:53.399Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/52/43ded0ac08e77e39d17bd6d894162572201b5e8fdc4a022b14c55a1960a4/pillow-13.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1", size = 6607008, upload-time = "2026-10-16T22:16:55.525Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/2e/4a57ed216d5bf877387cba4d44c02aa87abe51ad2e06404aa6b597c4da39/pillow-13.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683", size = 7224281, upload-time = "2026-10-16T22:16:57.738Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/3d/2929b248e135752d63aaeabf53f6de797e905b7b6263f9c1e2adade20aba/pillow-13.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058", size = 6695600, upload-time = "2026-10-16T22:16:59.842Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/33/fb0da992cf084ed1ee6ee05e96b6191e35c351eb707ca2df874feb24ce47/pillow-13.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e", size = 7300589, upload-time = "2026-10-16T22:17:01.686Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bb/af/c30dd9ef6a3dce84ecb1b2393cac629047a32e66279056c6cb46c3ffd65c/pillow-13.0.0-cp314-cp314t-win32.whl", hash = "sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15", size = 6517204, upload-time = "2026-10-16T22:17:03.722Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/85/d5/ef3a8ae7609c8ab26570abf18194882534b480d245a9148b895a2262c004/pillow-13.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0", size = 7286695, upload-time = "2026-10-16T22:17:05.543Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/84/3c/0861db0c69a03689ebe3e7599d35668a414deb5aaafd8255215e4e62e3d3/pillow-13.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692", size = 2698098, upload-time = "2026-10-16T22:17:07.674Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/eb/e86a41962a3a31ad495a3d6a912d9002b01bba4a6fa71c28703abdca7f69/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521", size = 4191213, upload-time = "2026-10-16T22:17:09.449Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/dd/04/7e7445e706afec84ef06dc25b2c77f9cecff242c23730c62928ad1089d4a/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc", size = 4290650, upload-time = "2026-10-16T22:17:11.196Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/46/85/d534089068ac40c0f61f650389a296c812eab745a8a733f81feec39ae955/pillow-13.0.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac", size = 3723078, upload-time = "2026-10-16T22:17:12.772Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/2b/00b5c3b401df538b5dbe311d3899730fae5ba1e21cb8b80a128887ac6747/pillow-13.0.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d", size = 5572292, upload-time = "2026-10-16T22:17:14.539Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/f5/a6b0610f946e9b54ae888ba7ad29d6e2f8d9b11f69e212d70416b7186c09/pillow-13.0.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782", size = 4852222, upload-time = "2026-10-16T22:17:16.521Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1e/d0/c0ff25bb0427ec70f32aac995453321fc3c4494a46c7292ff02d9d260b04/pillow-13.0.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071", size = 6527349, upload-time = "2026-10-16T22:17:18.534Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/85/11/e46fa0bcc0fc117f1eacc206b3d51f04d583fab328b4b740672d0438d83f/pillow-13.0.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf", size = 7152873, upload-time = "2026-10-16T22:17:20.415Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/53/2bdeca705f3a58679fa9201233193c86a30238340ca29b3a152c3fcc719b/pillow-13.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3", size = 6626871, upload-time = "2026-10-16T22:17:22.361Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/14/de/3829030f209722ade3753bb456b805a0e7f885cf885b483407365c82e9ca/pillow-13.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932", size = 7236439, upload-time = "2026-10-16T22:17:24.352Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/b1/67fc37388382bc036a74f04da5bb6fcbf90ec3ac1f45893e06176c373fd3/pillow-13.0.0-cp315-cp315-win32.whl", hash = "sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81", size = 6508688, upload-time = "2026-10-16T22:17:26.314Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/05/fdb6a79aee10861165526b41b7b440e36ee1ff58613b2fbefe3acbf06d4f/pillow-13.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6", size = 7281107, upload-time = "2026-10-16T22:17:28.198Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/9c/6c6f7dc2a566467baf121394e83de25ac287cffe34cc030726beb4be0224/pillow-13.0.0-cp315-cp315-win_arm64.whl", hash = "sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0", size = 2695513, upload-time = "2026-10-16T22:17:30.013Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/23/16/e9120defdb8bff693b582d035312acc6f530cdc2bc5238a87f410efccd82/pillow-13.0.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f", size = 5578129, upload-time = "2026-10-16T22:17:31.642Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/47/22/76faf2bb2448f48a84cf894c1e2bb1090d7d2b1aa521ece131cb2f05d631/pillow-13.0.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88", size = 4857428, upload-time = "2026-10-16T22:17:33.43Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/64/0861ea4e03c50b14af9ed9dd8b9f388ab42f445c623a9fcbab19aef7aa55/pillow-13.0.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb", size = 6612582, upload-time = "2026-10-16T22:17:35.415Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/20/cd1e9b3f60a9f3d5ebe46da36955c26004092a501f7f2c42f9fcc26611bc/pillow-13.0.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe", size = 7230176, upload-time = "2026-10-16T22:17:37.362Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/ef/ffb0a2fc85690714fb7ac662956949645d57f15bf4426f520da361e7b6e3/pillow-13.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22", size = 6703640, upload-time = "2026-10-16T22:17:39.313Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/c2/6402ee3ccb3363aeed8fdb3f9fe56703ac5377a539f0b81b53999d7e121f/pillow-13.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630", size = 7309231, upload-time = "2026-10-16T22:17:41.021Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/96/d6b82e8b8c06ad143b66b12e0b31051e4bf489b4fabca1f390a14fe1ebde/pillow-13.0.0-cp315-cp315t-win32.whl", hash = "sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2", size = 6517200, upload-time = "2026-10-16T22:17:42.886Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/d4/0062e6005e9b270b165015aafd343364ac378ec5a685431ea42baad33357/pillow-13.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43", size = 7287488, upload-time = "2026-10-16T22:17:45.56Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/81/b8eb349746be7bce47dd95337c6634e84910af91b59aaa9159c034c614fa/pillow-13.0.0-cp315-cp315t-win_arm64.whl", hash = "sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8", size = 2698073, upload-time = "2026-10-16T22:17:47.556Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/da/f6d644e631c5b370c5d0b899f3ccadd2780aab070b29a110527cf4e1fd2c/pillow-13.0.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463", size = 5523188, upload-time = "2026-10-16T22:17:59.334Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/b0/2594f202d743a35d4fe80682bfd96f277e5ca7aecb27cf64ef5bfc1d000b/pillow-13.0.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e", size = 4806808, upload-time = "2026-10-16T22:18:01.188Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/ed/d504165ef79af6fafe25c76726cf30f544cc236002f7ed054f1d51adc4ff/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63", size = 5464358, upload-time = "2026-10-16T22:18:02.779Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "platformdirs"
|
||||
version = "4.10.0"
|
||||
@@ -3851,59 +3976,127 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "pyarrow"
|
||||
version = "24.0.0"
|
||||
version = "25.0.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/91/13/13e1069b351bdc3881266e11147ffccf687505dbb0ea74036237f5d454a5/pyarrow-24.0.0.tar.gz", hash = "sha256:85fe721a14dd823aca09127acbb06c3ca723efbd436c004f16bca601b04dcc83", size = 1180261, upload-time = "2026-04-21T10:51:25.837Z" }
|
||||
resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'linux'",
|
||||
"python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3d/e3/27f57f80141379d60defe6703eb50a707325706f07fedfd1312c7a751995/pyarrow-25.0.1.tar.gz", hash = "sha256:9150a83248bfed9813ea3c3af74c3856c1984d444aa28e58bf7733b9750ddf6a", size = 1201653, upload-time = "2026-08-10T12:40:53.904Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/bf/a34fee1d624152124fa8355c42f34195ad5fe5233ce5bb87946432047d52/pyarrow-24.0.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:7c2b98645d576a0b9616892ead22b64a83a5f043c5e2ca15ebcefcb5b70c80cb", size = 35076681, upload-time = "2026-04-21T08:51:46.845Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/41/64180033d7027afce12dc96d0fe1f504c6fa112190582b458acea2399530/pyarrow-24.0.0-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:644a246325b8c69c595ad1dd4b463eba4b0cdb731370e4a86137d433208d6147", size = 36684260, upload-time = "2026-04-21T08:51:53.642Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/57/02/9b9320e673dd8a99411fac78690f3df92f6dd6f59754c750110bca66d64e/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:3a577bd840ca83f646f0a625dbc571dba7044c43c2d1503afc378b570954345c", size = 45698566, upload-time = "2026-04-21T10:46:02.133Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/33/f75e91b9a64c3f33c787e263c93b871ad91b8a4a68c1d5cebddd9840e835/pyarrow-24.0.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:e3268e43984d0b1a185c89b4cfff282a7ead12fc93f56cfd7088bdbcbe727041", size = 48835562, upload-time = "2026-04-21T10:46:10.278Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/63/097510448e47e4091faa41c43ba92f97cecaab8f4535b56a3d149578f634/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2392d954fcb920f42d230284b677605e4e2fbb11f2821e823e642abd67fbb491", size = 49394997, upload-time = "2026-04-21T10:46:18.08Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/6b/c047d6222ab279024a062742d1807e2fbaf27bba88a98637299ff47b9236/pyarrow-24.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bec9373df11544592b0ba7ec2af0e35059e5f0e7647c6183a854dedd193298f1", size = 51911424, upload-time = "2026-04-21T10:46:25.347Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/ba/464cc70761c2a525d97ebd84e21c31ebd47f3ef4bdcee117009f51c46f24/pyarrow-24.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:c42ab9439498270139cc63e18847a02afe5c8b3ed9c931266533cfe378bd3591", size = 27251730, upload-time = "2026-04-21T10:46:30.913Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/62/c9/a47ab7ece0d86cbe6678418a0fbd1ac4bb493b9184a3891dfa0e7f287ae0/pyarrow-24.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:b0e131f880cda8d04e076cee175a46fc0e8bc8b65c99c6c09dff6669335fde74", size = 35068898, upload-time = "2026-04-21T10:46:36.599Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/bc/8db86617a9a58008acf8913d6fed68ea2a46acb6de928db28d724c891a68/pyarrow-24.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:1b2fe7f9a5566401a0ef2571f197eb92358925c1f0c8dba305d6e43ea0871bb3", size = 36679915, upload-time = "2026-04-21T10:46:42.602Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/8e/fb178720400ef69db251eb4a9c3ccf4af269bc1feb5055529b8fc87170d1/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:0b3537c00fb8d384f15ac1e79b6eb6db04a16514c8c1d22e59a9b95c8ba42868", size = 45697931, upload-time = "2026-04-21T10:46:48.403Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f3/27/99c42abe8e21b44f4917f62631f3aa31404882a2c41d8a4cd5c110e13d52/pyarrow-24.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:14e31a3c9e35f1ab6356c6378f6f72830e6d2d5f1791df3774a7b097d18a6a1e", size = 48837449, upload-time = "2026-04-21T10:46:55.329Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/b6/333749e2666e9032891125bf9c691146e92901bece62030ac1430e2e7c88/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b7d9a514e73bc42711e6a35aaccf3587c520024fe0a25d830a1a8a27c15f4f57", size = 49395949, upload-time = "2026-04-21T10:47:01.869Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/17/25/c5201706a2dd374e8ba6ee3fd7a8c89fb7ffc16eed5217a91fd2bd7f7626/pyarrow-24.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b196eb3f931862af3fa84c2a253514d859c08e0d8fe020e07be12e75a5a9780c", size = 51912986, upload-time = "2026-04-21T10:47:09.872Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/d2/4d1bbba65320b21a49678d6fbdc6ff7c649251359fdcfc03568c4136231d/pyarrow-24.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:35405aecb474e683fb36af650618fd5340ee5471fc65a21b36076a18bbc6c981", size = 27255371, upload-time = "2026-04-21T10:47:15.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b4/a9/9686d9f07837f91f775e8932659192e02c74f9d8920524b480b85212cc68/pyarrow-24.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:6233c9ed9ab9d1db47de57d9753256d9dcffbf42db341576099f0fd9f6bf4810", size = 34981559, upload-time = "2026-04-21T10:47:22.17Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/80/b6/0ddf0e9b6ead3474ab087ae598c76b031fc45532bf6a63f3a553440fb258/pyarrow-24.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:f7616236ec1bc2b15bfdec22a71ab38851c86f8f05ff64f379e1278cf20c634a", size = 36663654, upload-time = "2026-04-21T10:47:28.315Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7c/3b/926382efe8ce27ba729071d3566ade6dfb86bdf112f366000196b2f5780a/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:1617043b99bd33e5318ae18eb2919af09c71322ef1ca46566cdafc6e6712fb66", size = 45679394, upload-time = "2026-04-21T10:47:34.821Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/7a/829f7d9dfd37c207206081d6dad474d81dde29952401f07f2ba507814818/pyarrow-24.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:6165461f55ef6314f026de6638d661188e3455d3ec49834556a0ebbdbace18bb", size = 48863122, upload-time = "2026-04-21T10:47:42.056Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/e8/f88ce625fe8babaae64e8db2d417c7653adb3019b08aae85c5ed787dc816/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b13dedfe76a0ad2d1d859b0811b53827a4e9d93a0bcb05cf59333ab4980cc7e", size = 49376032, upload-time = "2026-04-21T10:47:48.967Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/7a/82c363caa145fff88fb475da50d3bf52bb024f61917be5424c3392eaf878/pyarrow-24.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:25ea65d868eb04015cd18e6df2fbe98f07e5bda2abefabcb88fce39a947716f6", size = 51929490, upload-time = "2026-04-21T10:47:55.981Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/66/1c/e3e72c8014ad2743ca64a701652c733cc5cbcee15c0463a32a8c55518d9e/pyarrow-24.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:295f0a7f2e242dabd513737cf076007dc5b2d59237e3eca37b05c0c6446f3826", size = 27355660, upload-time = "2026-04-21T10:48:01.718Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6f/d3/a1abf004482026ddc17f4503db227787fa3cfe41ec5091ff20e4fea55e57/pyarrow-24.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:02b001b3ed4723caa44f6cd1af2d5c86aa2cf9971dacc2ffa55b21237713dfba", size = 34976759, upload-time = "2026-04-21T10:48:07.258Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/4a/34f0a36d28a2dd32225301b79daad44e243dc1a2bb77d43b60749be255c4/pyarrow-24.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:04920d6a71aabd08a0417709efce97d45ea8e6fb733d9ca9ecffb13c67839f68", size = 36658471, upload-time = "2026-04-21T10:48:13.347Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/78/543b94712ae8bb1a6023bcc1acf1a740fbff8286747c289cd9468fced2a5/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a964266397740257f16f7bb2e4f08a0c81454004beab8ff59dd531b73610e9f2", size = 45675981, upload-time = "2026-04-21T10:48:20.201Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/84/9f/8fb7c222b100d314137fa40ec050de56cd8c6d957d1cfff685ce72f15b17/pyarrow-24.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:6f066b179d68c413374294bc1735f68475457c933258df594443bb9d88ddc2a0", size = 48859172, upload-time = "2026-04-21T10:48:27.541Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a7/d3/1ea72538e6c8b3b475ed78d1049a2c518e655761ea50fe1171fc855fcab7/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1183baeb14c5f587b1ec52831e665718ce632caab84b7cd6b85fd44f96114495", size = 49385733, upload-time = "2026-04-21T10:48:34.7Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c3/be/c3d8b06a1ba35f2260f8e1f771abbee7d5e345c0937aab90675706b1690a/pyarrow-24.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:806f24b4085453c197a5078218d1ee08783ebbba271badd153d1ae22a3ee804f", size = 51934335, upload-time = "2026-04-21T10:48:42.099Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9c/62/89e07a1e7329d2cde3e3c6994ba0839a24977a2beda8be6005ea3d860b99/pyarrow-24.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:e4505fc6583f7b05ab854934896bcac8253b04ac1171a77dfb73efef92076d91", size = 27271748, upload-time = "2026-04-21T10:49:42.532Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/17/1a/cff3a59f80b5b1658549d46611b67163f65e0664431c076ad728bf9d5af4/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:1a4e45017efbf115032e4475ee876d525e0e36c742214fbe405332480ecd6275", size = 35238554, upload-time = "2026-04-21T10:48:48.526Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/99/cce0f42a327bfef2c420fb6078a3eb834826e5d6697bf3009fe11d2ad051/pyarrow-24.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:7986f1fa71cee060ad00758bcc79d3a93bab8559bf978fab9e53472a2e25a17b", size = 36782301, upload-time = "2026-04-21T10:48:55.181Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/66/8e560d5ff6793ca29aca213c53eec0dd482dd46cb93b2819e5aab52e4252/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:d3e0b61e8efb24ed38898e5cdc5fffa9124be480008d401a1f8071500494ae42", size = 45721929, upload-time = "2026-04-21T10:49:03.676Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/27/0c/a26e25505d030716e078d9f16eb74973cbf0b33b672884e9f9da1c83b871/pyarrow-24.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:55a3bc1e3df3b5567b7d27ef551b2283f0c68a5e86f1cd56abc569da4f31335b", size = 48825365, upload-time = "2026-04-21T10:49:11.714Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/eb/771f9ecb0c65e73fe9dccdd1717901b9594f08c4515d000c7c62df573811/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:641f795b361874ac9da5294f8f443dfdbee355cf2bd9e3b8d97aaac2306b9b37", size = 49451819, upload-time = "2026-04-21T10:49:21.474Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/da/61ae89a88732f5a785646f3ec6125dbb640fa98a540eb2b9889caa561403/pyarrow-24.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8adc8e6ce5fccf5dc707046ae4914fd537def529709cc0d285d37a7f9cd442ca", size = 51909252, upload-time = "2026-04-21T10:49:31.164Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/1a/8dd5cafab7b66573fa91c03d06d213356ad4edd71813aa75e08ce2b3a844/pyarrow-24.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:9b18371ad2f44044b81a8d23bc2d8a9b6a6226dca775e8e16cfee640473d6c5d", size = 27388127, upload-time = "2026-04-21T10:49:37.334Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/80/d022a34ff05d2cbedd8ccf841fc1f532ecfa9eb5ed1711b56d0e0ea71fc9/pyarrow-24.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:1cc9057f0319e26333b357e17f3c2c022f1a83739b48a88b25bfd5fa2dc18838", size = 35007997, upload-time = "2026-04-21T10:49:48.796Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/ff/f01485fda6f4e5d441afb8dd5e7681e4db18826c1e271852f5d3957d6a80/pyarrow-24.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:e6f1278ee4785b6db21229374a1c9e54ec7c549de5d1efc9630b6207de7e170b", size = 36678720, upload-time = "2026-04-21T10:49:55.858Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/c2/2d2d5fea814237923f71b36495211f20b43a1576f9a4d6da7e751a64ec6f/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:adbbedc55506cbdabb830890444fb856bfb0060c46c6f8026c6c2f2cf86ae795", size = 45741852, upload-time = "2026-04-21T10:50:04.624Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/3a/28ba9c1c1ebdbb5f1b94dfebb46f207e52e6a554b7fe4132540fde29a3a0/pyarrow-24.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:ae8a1145af31d903fa9bb166824d7abe9b4681a000b0159c9fb99c11bc11ad26", size = 48889852, upload-time = "2026-04-21T10:50:12.293Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/51/4a389acfd31dca009f8fb82d7f510bb4130f2b3a8e18cf00194d0687d8ac/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:d7027eba1df3b2069e2e8d80f644fa0918b68c46432af3d088ddd390d063ecde", size = 49445207, upload-time = "2026-04-21T10:50:20.677Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/19/4b/0bab2b23d2ae901b1b9a03c0efd4b2d070256f8ce3fc43f6e58c167b2081/pyarrow-24.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e56a1ffe9bf7b727432b89104cc0849c21582949dd7bdcb34f17b2001a351a76", size = 51954117, upload-time = "2026-04-21T10:50:29.14Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/29/88/f4e9145da0417b3d2c12035a8492b35ff4a3dbc653e614fcfb51d9dedb38/pyarrow-24.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:38be1808cdd068605b787e6ca9119b27eb275a0234e50212c3492331680c3b1e", size = 28001155, upload-time = "2026-04-21T10:51:22.337Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/79/4f/46a49a63f43526da895b1a45bbb51d5baf8e4d77159f8528fc3e5490007f/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:418e48ce50a45a6a6c73c454677203a9c75c966cb1e92ca3370959185f197a05", size = 35250387, upload-time = "2026-04-21T10:50:35.552Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/da/d5e0cd5ef00796922404806d5f00325cdadc3441ce2c13fe7115f2df9a64/pyarrow-24.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:2f16197705a230a78270cdd4ea8a1d57e86b2fdcbc34a1f6aebc72e65c986f9a", size = 36797102, upload-time = "2026-04-21T10:50:42.417Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/34/c7/5904145b0a593a05236c882933d439b5720f0a145381179063722fbfc123/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:fb24ac194bfc5e86839d7dcd52092ee31e5fe6733fe11f5e3b06ef0812b20072", size = 45745118, upload-time = "2026-04-21T10:50:49.324Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/13/d3/cca42fe166d1c6e4d5b80e530b7949104d10e17508a90ae202dac205ce2a/pyarrow-24.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:9700ebd9a51f5895ce75ff4ac4b3c47a7d4b42bc618be8e713e5d56bacf5f931", size = 48844765, upload-time = "2026-04-21T10:50:55.579Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b0/49/942c3b79878ba928324d1e17c274ed84581db8c0a749b24bcf4cbdf15bd3/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d8ddd2768da81d3ee08cfea9b597f4abb4e8e1dc8ae7e204b608d23a0d3ab699", size = 49471890, upload-time = "2026-04-21T10:51:02.439Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/76/97/ff71431000a75d84135a1ace5ca4ba11726a231a8007bbb320a4c54075d5/pyarrow-24.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:61a3d7eaa97a14768b542f3d284dc6400dd2470d9f080708b13cd46b6ae18136", size = 51932250, upload-time = "2026-04-21T10:51:10.576Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/51/be/6f79d55816d5c22557cf27533543d5d70dfe692adfbee4b99f2760674f38/pyarrow-24.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:c91d00057f23b8d353039520dc3a6c09d8608164c692e9f59a175a42b2ae0c19", size = 28131282, upload-time = "2026-04-21T10:51:16.815Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/3e/5cd70becb51e1d044c54ba5e627424a6e87df5b98008cbd22cc6abd409ca/pyarrow-25.0.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:0b1edbb2f385a6a65e9711b62ba86ac54a7816a3f8d17bb3e8a5929d65fb2485", size = 35954271, upload-time = "2026-08-10T12:36:33.857Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/64/be/17599e086df264ea7dc221d1101e3131e181e00da428a2f9bd0358f0d06b/pyarrow-25.0.1-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:a4dd8bf99a8fac133efc0ed6a92f5fddbe2adba0d0f6dd720e39ba9855cea85c", size = 37647543, upload-time = "2026-08-10T12:36:39.486Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/34/e138b451fd3970a6eda4599f68ae3b2b32b661bc958de3239d54a0bf6575/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:bddd0c4f7630c2a3ddf6347c1bdaa79d97bcf6bd445f9e60c816b7d77c85a5ae", size = 46837120, upload-time = "2026-08-10T12:36:46.58Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/57/5c/f8fc0eb2de03464a557d5a4d0c15e972d73362414696618833b771f7eddd/pyarrow-25.0.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a4d6d5e9a3d1879a97c08ded0c797579b7965eafd0f0c26c30b45ccc06db939b", size = 50066460, upload-time = "2026-08-10T12:36:53.702Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3f/d1/0dd64fd06de0333b808a02f60981635f067b71aad3a30698a9a104fae778/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:514ddb60285631af068875550c90eddc181db3e8e63a032b1559be189e82f056", size = 49937892, upload-time = "2026-08-10T12:37:00.349Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/3c/f89d1bd76d5f3284c2a44d7d7ebbd8204535e5ae2b41f4077069b4ff2ec6/pyarrow-25.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cab40b1edfef0262e0e5251aa2c58d75630f24d06dd7794480243acc001a1d7d", size = 53107240, upload-time = "2026-08-10T12:37:07.205Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/67/b554a8e09f3f3decccf405eb8fbe86696321cbcb5b62d18b4a5057a4c113/pyarrow-25.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:60e89d8f13861a1f7f8d950fa54aebb8023b30734d0ac51ffa80beabe2df4bba", size = 27848683, upload-time = "2026-08-10T12:37:12.058Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ee/8b/0d23b47702fcfe8b3618d5292035099675c5a1c48258932350c08020f7b5/pyarrow-25.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:51093dd9e10325fbdb3c10a2ae7c4806e5c822d94e74ae4938b26524a3323fee", size = 35946180, upload-time = "2026-08-10T12:37:18.934Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d8/17/707d17a5476c55a9541fde0db8213ac30979a792864d72415f176ba50c45/pyarrow-25.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:eb6203482ff3746a5632303a7279ae0b5a304c46985b49ed1378cb350ea6728d", size = 37644787, upload-time = "2026-08-10T12:37:25.795Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/b2/cdc98ecf1a6408280bc3a6a07054cdd99a3f4670acc0545d383ce113e87d/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:880523be3d29efcf83d3998835d206118ccf35e3871dbd2fb60408cf6b007a80", size = 46834633, upload-time = "2026-08-10T12:37:33.604Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/6e/d3fafc41f378b2c65be43b827798c0fae42049a641c8526633ed3eb573e2/pyarrow-25.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:25f8720bf6387d5dc2ebd2622112de630760419e4b66134405dd24110d15f37e", size = 50065507, upload-time = "2026-08-10T12:37:40.565Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d5/12/8d0698954b8c3001844a898e0a6900bebe83d7ee40c11195174c5122f324/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4facd65742a024a4a366328a1d2292062d72d6e023c1b7dda8d4c37544933a25", size = 49955690, upload-time = "2026-08-10T12:37:46.644Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/0b/1ecb936ac6409e90a34d58eea1c7cec09a9ae6d2141b9e49ad01a2b1ea47/pyarrow-25.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:aa0559502e1cd6254d6814614085dd9c5a3dd0419362978a936a3f68a9e5c3df", size = 53128198, upload-time = "2026-08-10T12:37:52.531Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/1c/5236033550633c9b7377b2a53660b2bbb06cb06dc09c4356332d67643ca1/pyarrow-25.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:62cd0d785b8aa6675ee355f9fc02252a340f4441257c42674937826fd7594325", size = 27857263, upload-time = "2026-08-10T12:37:56.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/e2/9ab15b88cbfac28e16419ce5439ec29234c5172cb8259301b4ba639bdec0/pyarrow-25.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:df961f2e7ae9cf496459259d798652c70625f6c080650d6952f8c04053c58ee9", size = 35861559, upload-time = "2026-08-10T12:38:02.567Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/58/79/a0036dbe1eabe1f73127427342f1d99982584c4a2cde2651d6c93499c6f6/pyarrow-25.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:cc4aa407fde9fc660be3939e49ea31f50f3e9fec17c0ec63159f7711edd3efc9", size = 37628383, upload-time = "2026-08-10T12:38:09.083Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/13/49/d93a57d375f4bf0cf82913dd6bb54acafde83dd993be2282c81ac5616cad/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4340f0ba6c1d2e13f21658de1d7c662ca2545018568d0030a1e9afca159d87e3", size = 46820190, upload-time = "2026-08-10T12:38:15.458Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/c9/711ca85d79f1ec98f29a5eae2b051e25b4ecec5de3e3c0e2d5c5dcb15664/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5389cdf79447ed1515c9e31620e6e1e2302249564d603f2ad727d4f6d313e4c3", size = 50102437, upload-time = "2026-08-10T12:38:22.487Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/80/53/8fb8359ff17cfb6263a1cf3ebf7caec9fe197de118719e84fcb1d0618026/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d51592cb7561e87877c506113e7adbf1342ab579e6c21f0ef44b8ba41cb74c80", size = 49942424, upload-time = "2026-08-10T12:38:28.755Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/83/4e5ae02a9341571b18a6fca380ac7a58ce6ddae7ab3c060208c0a1e79f02/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6109c94d8b9f3b17a041daca16cacb2f651ad8f1ef70a4232c2c0f37a23da2a8", size = 53144206, upload-time = "2026-08-10T12:38:34.862Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/65/ee/197cbf47e49f83e6ebeb946a5259a48a638dea27ac774db42fe78022179d/pyarrow-25.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:8858d7bfc22e3f51529aeaa4077225029724623e4595dc9eff8c793935c34140", size = 27953934, upload-time = "2026-08-10T12:38:39.808Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cc/8d/8f271a7a034c834910ec925d56fa4b29733b1380f5289419f5aaa3b02777/pyarrow-25.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c7c534ec03c358a76ea3e505e74c1b6aef290af90c444dfd092dbfe23e755b85", size = 35855328, upload-time = "2026-08-10T12:38:45.489Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d2/cd/5bac242f4e841b9971d5eb94fdfe2577e2b70be983e27401e72055786037/pyarrow-25.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dda9470024204d7bbf2042b47c6e8a0e47a3eeb8e34405882dfaea6577e0c153", size = 37622415, upload-time = "2026-08-10T12:38:51.107Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/63/1f/96d03b4e1506524f7087adb0fd6b2f69f0c9c7aaff1ec36d8030082e15a5/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:44a9120ce5bd81936b8ab9a88076e3fd47c2c6838e0e43630fed83626aca81d9", size = 46813813, upload-time = "2026-08-10T12:38:57.773Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/98/d6/33a411115b61dbfc16ad6ad73e71730f6fea654ee3667673bc53ab0e2fe7/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0befcf816e45a1af33ac775a9970b749e4868a230c7372f0ae5e932bee27039f", size = 50104452, upload-time = "2026-08-10T12:39:04.579Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/33/ae/b1b97c9ca87f9f9ddbb5230c798df94eccce61bd79b9b45458c69a478588/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f89685964f46e4216103c75483aac0c0692a5f72212d7ca835adba5ede56ce3", size = 49951343, upload-time = "2026-08-10T12:39:11.8Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/98/9e/a112df5cfd5a68cb1d9fc31cfe38c28d5aec9f10865ce37ecef2e4450873/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6943e2fe7954d29d84de45d29d34c8dc36ce96570e67d89aa9976e650a4a9138", size = 53144784, upload-time = "2026-08-10T12:39:20.503Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/31/24/97e8bd98f1e3b07e2ba08bcdff690674fbe16d69a7d2712cc3884665e615/pyarrow-25.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:31e49a7888fcdf3a835da33ae777f6bb9a866334e5a789282fc26dcf426f7f15", size = 27870159, upload-time = "2026-08-10T12:39:26.161Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/4c/b525824ad3094076919273cd97db61fb3d78252dee76fa3b8dc8f76774aa/pyarrow-25.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bf0b672390cdcb640d7288f96b826d71ff4e9abb254a86c89890baf51a29cee6", size = 35885255, upload-time = "2026-08-10T12:39:32.366Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/62/448bb0e940de41aec31d1a956e63ad9c54afdf122a103cc3ab20c2a3ce33/pyarrow-25.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:38a9a4b4b9613380e200641891495a56c3d5a98a092db4a870af9975e220471d", size = 37644461, upload-time = "2026-08-10T12:39:38.142Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/9a/13587e38bd4806fd218f50fd13b8903fab60588a699ff0c406372e5b4043/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b726ad7e7b669be982b0c71c07fe4b037d654354130da79a7902a669e93a66b", size = 46877146, upload-time = "2026-08-10T12:39:43.722Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8d/61/1c5d1229fa21da4cff5365e41e57177aaac57c563c727f35419b8513d1c1/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:9171748cdf796972d85a4b60157c279913e242992e350c90c7450182a9838b2a", size = 50131616, upload-time = "2026-08-10T12:39:49.304Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/20/291e1d65cc0b09aa19f03cf25cf51a2f5fa94b5db315178f2d254ed5cad4/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b7a296aac7a71fa0886c08e155ddb6c636a50013f801f6178daafa0f9e726188", size = 50008879, upload-time = "2026-08-10T12:39:56.891Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8b/7c/1b7c9ec28e76576337e4f97b31141c9a181b89b6d1d6221e9d8205621a58/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fe7c8b6c03969b49c8c66182e4a18e3819ab92d07cfab5d8370c531b9369ef0", size = 53170864, upload-time = "2026-08-10T12:40:04.918Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/75/f3d789dc06011a765d14d86bda799cf72ac1d715b6a6edecaa0d73d95062/pyarrow-25.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:f729cfdbd36fd99d543b67a914d2de044c84ebe45be8b34902b299b608c15c8f", size = 28620729, upload-time = "2026-08-10T12:40:51.41Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fc/05/647a8ee6f7c2662feb6921315617bc04dcd6034763fb61b1199720bf6162/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:59a2de54c0cbd954da861eee4d1d330f8e909c45b53455baef696380f2c55033", size = 36130288, upload-time = "2026-08-10T12:40:11.014Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/93/f8/c9ee997554d7bea94520667dd1933f109ac1da3ee3556d2b49381e023484/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:35935cd5de130aa5cf4dea052a63e6bf2e17006c35c3a468194242b9b2bf5956", size = 37762187, upload-time = "2026-08-10T12:40:16.592Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a2/08/a28c01c7fe9e96e8233ce2d13df1d402f4f999f848f51d2daacd6bb4c036/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:f3831aaa25c67a99f99dc8b05873cb9d64560390372e2aa197ce9dd4a3f06a44", size = 46888003, upload-time = "2026-08-10T12:40:23.242Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1b/b9/58612e977d28dc58c878448866838369ee8da2f1e7cc8ed2c84b952aafee/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6a1fdfc6659b6b19022f2e50627fb5cf7156a66c46bf4299379955cbe742382a", size = 50079036, upload-time = "2026-08-10T12:40:29.169Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/13/66e1402dcc860e1dc2760b1e0292c9a569b62b3bccab69def1b3e907d006/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:169d3429d5be7c752125890620f75a60776d38b0035eddae939651640822332e", size = 50040226, upload-time = "2026-08-10T12:40:35.186Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/10/3f1a5497a7ef732ab0f03ecca3e66d89d9c0f57fdc61b4794c456b781f01/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:119297a6dc197e45d9c6d4415f7814a67ffa36c180d26f68c154c58067ae782d", size = 53149035, upload-time = "2026-08-10T12:40:41.454Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/93/c0/37d4a7e8e2f7a6076283673d5298018ca26478b934c6ee369e10505ab32c/pyarrow-25.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:4288f27577352d608ca08553b0865e4a9b3aa14820c5d95b53337218d609835b", size = 28753071, upload-time = "2026-08-10T12:40:46.623Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyarrow"
|
||||
version = "26.0.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'win32'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'emscripten'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'linux'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version == '3.11.*' and sys_platform == 'linux'",
|
||||
"python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/fd/aa/459f3f5adebf6427a8bf1e976168f55793a3732ec1c6c6fe9e05a060b63b/pyarrow-26.0.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:9a62748f6b1f9f438706f0307acbb26e6a15010ea58f202c9d2725bc6eac0871", size = 37327168, upload-time = "2026-11-03T09:54:01.046Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/ed/29218597cb38aa9058dffda7906749df9e9da02b4c4da4e88dd8bcfa85eb/pyarrow-26.0.1-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:0187cbe6558cb158e148dd7b779f59cab6104163d148d808d04f293dc897b7ec", size = 39778863, upload-time = "2026-11-03T09:57:58.046Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/f9/44489f525c73cc469f23fd02c0a3009882a8dcf45d0d9fb6ca1bb84a53e2/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:22a96a225de107eb9acd1ad9a818198ca832df2a4c0952412f754a7ed2105a98", size = 51836882, upload-time = "2026-11-03T10:48:50.544Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e6/87/6bf528898ef82dc3e8d762cbec7b42ae127a543895cc78c5df26a1f497f5/pyarrow-26.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:39cb0f2418282c24bea6ceda77b03e5a8f0a5766b63a8bf194d4e2a2c423548c", size = 55016622, upload-time = "2026-11-03T10:48:58.916Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/97/e8/3b4898693744efb5aa60a859774ee3874a2635b288f309f1afb78a698f38/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:24350194bc83f1fde74aa321b6b43cd78bfdbfe613a795a6b9145fd4beaf4827", size = 55452257, upload-time = "2026-11-03T10:49:05.872Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/96/bbeb5152a27406c65b80b72ecba4451fea18d549a5aea1fbb2c097d86b08/pyarrow-26.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ed1e19bfaf79565b74e3b0a45a0ba6d05620e68d5a5b48a8193c2bbee7cf5484", size = 58605344, upload-time = "2026-11-03T10:49:14.145Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/aa/afb7321eaed5f65332aa691fcd892bf67d0289e2ba884c8ce592d3188a26/pyarrow-26.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:5f681458e4fb81aefef50d3a8a432fe92f8480a87693616f9d95e95ceac8844c", size = 29034160, upload-time = "2026-11-03T10:49:19.45Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/61/81/dc5814d61f8c956363e81bcaba61b4712a5d227324d40c766b3858160711/pyarrow-26.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:217497a51fd41abb74502ba2f4900872e0944c226945c02ee8a1cb4f81df3392", size = 37290209, upload-time = "2026-11-03T10:49:25.185Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/c8/dcc42b1cceb69ff032fa16430bd82c086b933e35ef05ab521e56313b76be/pyarrow-26.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:a2c5e9cec45b318917b630dc040cf197aef624d94866ab2c8e709708057123d2", size = 39757493, upload-time = "2026-11-03T10:49:30.886Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ab/7e/da9831bfcaaa908ae6d5d049c04c2233a5a7e216d6b961e22861056ef3fd/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6c18167774fb599d42444b7ac558a893d49e750fb14232b538955e6f0d1d51ea", size = 51818506, upload-time = "2026-11-03T10:49:37.89Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/79/e2fc9b1317b7a21e7bcd57eb035cac3fe72f47af3efe2ec3b4dea9a08a04/pyarrow-26.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9", size = 55043763, upload-time = "2026-11-03T10:49:45.732Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e3/66/dbe72f5fa21a92b645d56410bacac605defe63e5d3e9794b2fd8c7d77030/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:40aea57ab8bd3cf35a11e604cd7d0c7436dc90d1ce9b88b6711ef2f1a232968e", size = 55438656, upload-time = "2026-11-03T10:49:53.74Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/b1/c91322fc4c1800c1f7dd78f911b1dd74187acaeb246d86478a0f064f6af5/pyarrow-26.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:73534fbda7f73cab0791b569b93112d4c9e1546cedd0f309d1f69889beb6a08f", size = 58625736, upload-time = "2026-11-03T10:50:01.442Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/30/61/d94decccacb4dd40a4ebeed0ff3b2cea8f0b680f50184ea7eb0264db779b/pyarrow-26.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:9379f0d1056cad6866c4697aec83a15830202ec7e0bd52f8bd508b316260fa61", size = 29078866, upload-time = "2026-11-03T10:50:06.854Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/15/b8/c31c51fbe7df901817d88c73eeec25079d0da5f7c7b67fc0bf071f6a2df5/pyarrow-26.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:4cb739ccb87292c673e1f69819b68432a73bb8bb456e8599641bba9183a8a1dd", size = 37292947, upload-time = "2026-11-03T10:50:12.333Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fd/63/0c2559ae33ce59d2ca5ce74117676f8ff8da4cf102729a158ea46415eb50/pyarrow-26.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:50b40aea92f43b2b6da3427548a5337741b4b93b92e8015a8a3eefc0e75acca2", size = 39767535, upload-time = "2026-11-03T10:50:18.254Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/31/02/d9462d1ae4e54c3964af38316a802b29c28970b7d375722ef190af736640/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a3a79661404ba3d41b7c9a45cb56113246a244b38cb1393fadae289bc66b91b4", size = 51815955, upload-time = "2026-11-03T10:50:25.332Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/96/54/33c2df56948d88a4d83a52999a4a81a4871b2de481ff25ccd6f5ccd2589a/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f71221bbc7707e3fad920d0478db9350791d4714ec445299ee0d56559fbc156c", size = 55038406, upload-time = "2026-11-03T10:50:32.551Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/99/57/8e1f886ee96c7edab89ab6f15fbb00c85c2bb2173f3cb504925731d00564/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8ccfb9958bcd09f34678c64fb42a0e270b47cd092ae79578da51e0d7bb144296", size = 55437362, upload-time = "2026-11-03T10:50:39.89Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8c/c3/d87939a5f6cd30bb406bad6c20926fcedafc52ec5629f6eb27e4cd5db709/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:029e881af986375a2731da79c999fe734a72547fabb16503d65fc079d4bc7eb2", size = 58618865, upload-time = "2026-11-03T10:50:48.029Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/9e/b6c8afec2ffc06bbd00a88326826f9d66e4bbca752c0837ee8e2dbf2238f/pyarrow-26.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:8196f36a2f4cb8d2d6ef3651941b80e5ccf125d7653657d99af5bb298e7a7026", size = 28989592, upload-time = "2026-11-03T10:50:53.384Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/de/48/999f6e30323e2e95a4439180b62f6308023970e4a37d31497080ea2a1a78/pyarrow-26.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:15435b595c14583f6ac8495c3ef89ac3fed6bc94f168467bfd3b6ba53ad3a643", size = 37334639, upload-time = "2026-11-03T10:50:59.462Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/3a/4458972c69ead95af5d3b701c80885133c351075895382499df49ed92d36/pyarrow-26.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:a44a244867cac106cd326dd0a04be0850d2b8af3b1418ed7aeb8146d13aba360", size = 39802150, upload-time = "2026-11-03T10:51:05.743Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/d0/fa4bc5d66f78cbc4ec8482b210c2fc3b8cb59564efe171f3ca9be416f8ee/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0044cb9303c3ae082cc52a2493312109c955bcfa84e87be768736f7d6d8f6257", size = 51880097, upload-time = "2026-11-03T10:51:12.75Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f3/57/755a1b54d37c2a9e2c283d8bc648a50aa4ce57f977ce6a4b1d65eba29f51/pyarrow-26.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:7ae48ab53610b85e004b03bccff593fbdf22186d0ab48ed42c90797915dac814", size = 55063542, upload-time = "2026-11-03T10:51:20.417Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/45/ba/7cd1d78c2ef5a36b1f8d137d1790179875639f197ed90702268084a2470a/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a97df0c52c966ae8970ac0899ae75d81083c5400eca267de2608ca0f13e6e118", size = 55490507, upload-time = "2026-11-03T10:51:28.295Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9f/02/39e18c5381ad908d7161cc16a02dce03b3db236d3c3ac99fc020878287fb/pyarrow-26.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5f665e73790222779613ae3d23d2a1d72f0f13a4646862277e9784bb46e14fca", size = 58648328, upload-time = "2026-11-03T10:51:36.303Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1c/18/2cd453cc2e282d465e9c9b60834d6ca17601dc08e2d402751cb40af92356/pyarrow-26.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:492dc499097968e51cac46e03e0054c68dd3c5f39d75098343f5ad05ec79f7df", size = 29757743, upload-time = "2026-11-03T10:52:35.061Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/db/46/b97f117adb46f93620aa94bf13747a81ccc5e099be534cc195c94b281ba7/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:ec196b35270263eda71fc3f43bd31a89b778c6787f19872df5abb9d4264057ff", size = 37452099, upload-time = "2026-11-03T10:51:42.419Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/40/ac1796654fc8591049d200f6bcd646a2319509010784f47c1cf6b09d1000/pyarrow-26.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:8af2b4e004dc18da8dc77bce27d97c675d2f71348e3ade2741cecac85c3f0c21", size = 39888805, upload-time = "2026-11-03T10:51:48.766Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/93/bcff79148416896738a707992570c4ae8e3bb087bc9e0dca8df7dbf6e983/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:c2bf4444a7e86f109dc03e28b2c98eb6671e2eb95e6057c25043d25684e337e9", size = 51884587, upload-time = "2026-11-03T10:51:56.701Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/62/cb05e81d31cd1dc97c2e16151425e61fe3a19274ccd1254cafab3a173f96/pyarrow-26.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b121de63e2f92704b6b9881fbe69cb3eeca786ea882379b59ce80b8012c1bd8c", size = 55018252, upload-time = "2026-11-03T10:52:05.813Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f8/f5/e8dbbb803bb28a32411491d502679e272c569af7f590816327e84725c748/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:40b9c1a5841559030ba8d1b8c15d6160bccb702ff2596b4ce296e1efd7665781", size = 55522075, upload-time = "2026-11-03T10:52:14.577Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9b/7a/5000d6082b116359d3db3ee6073a8f708f41cb4bb7d6414f94cd40a90fe7/pyarrow-26.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9519f70bd847f7628a2d16324d1ea8827e2ec1da347ee0bf96cc7c248195e923", size = 58625604, upload-time = "2026-11-03T10:52:23.045Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/41/70/74a5a07eeee1a84cd51e81813b7fd2d5ffc90192a95981a51e97a8ced99e/pyarrow-26.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:6d9b558e1bce3270f1f422c61fd682615cfb34ffd320a51e765e868e8c155a72", size = 29925653, upload-time = "2026-11-03T10:52:29.188Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/77/09/4e9461479930e3f4367cc0b4f4356d4444a23be9cb350272b159cd0c7fa9/pyarrow-26.0.1-cp315-cp315-macosx_12_0_arm64.whl", hash = "sha256:2c118754a0abe0bf20ef17432f95534ebb0ded37a48b6e8690cdd02625a86d97", size = 37329458, upload-time = "2026-11-03T10:52:41.622Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/40/5a/9e44840924b0939defacc2561e54dc9aba10eff1fc5dadcf41921202d99f/pyarrow-26.0.1-cp315-cp315-macosx_12_0_x86_64.whl", hash = "sha256:99574d8eabad06cc4bb3fed327b298c8a44a3596abd2d575738fa019df7ac59e", size = 39799948, upload-time = "2026-11-03T10:52:47.507Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/70/3a/5fe40369653a082d86fdb6ce2b7c40a4ef435d90a68da60c05dda0c554fc/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:12c5edbdf9b8a0f121a0a222be150c3a711149bc4322736d6a04693fbfd8c723", size = 51875337, upload-time = "2026-11-03T10:52:54.59Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/87/f768a458cf975c17c73912fb25a1e0693ceef8d76d78cf83ffdf1f63ec70/pyarrow-26.0.1-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:8cb5bcfe627ee6b910fbec27871d38cf4f28f331ea6328902ce6a6272851ac70", size = 55060370, upload-time = "2026-11-03T10:53:02.19Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/30/280c24a7da9085b782cd6960ccae6763b0170f51385b9122385c12226ff2/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e2ee5f01f84996109405759cba8bb92a16455c50deb6526a535ab3b8d5f4e326", size = 55488705, upload-time = "2026-11-03T10:53:09.8Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/e7/8e7b7f7bd58c88fd8da93db0d0869c69175c3ddccf365afbcc13fbd691da/pyarrow-26.0.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e25d4a886868c5ce136d194f308bd690e1335aebf6b8bcae3511b0becdb3a65a", size = 58646822, upload-time = "2026-11-03T10:53:17.902Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/c7/6094fa2c0b5602d81b1177ac7f5b2de8a386862d08e57a75931da774f3e0/pyarrow-26.0.1-cp315-cp315-win_amd64.whl", hash = "sha256:6cdad5f67a30bbcea54c3c2a27ea45bd5a170377bf45f80f4d7e3a726e8e3283", size = 29755706, upload-time = "2026-11-03T10:54:14.582Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/41/0f/86747650c8218bcea7443884e7c8ba9d3fe9a13fb5a4be99acdd5c2b9144/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_arm64.whl", hash = "sha256:12dc85cec96aa62d429d7c43749c072e9330c373b67d6ee458edeef444c8941f", size = 37445268, upload-time = "2026-11-03T10:53:25.531Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b9/ec/4159b2362267009b754a7c2f138f16bdfd6623b308005678eb7cf1b65863/pyarrow-26.0.1-cp315-cp315t-macosx_12_0_x86_64.whl", hash = "sha256:52e4daba8f1b4316b7b9ba7e84903a339cbc52998ebddc9a7c78b5ea37c23bbb", size = 39877540, upload-time = "2026-11-03T10:53:33.046Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/0e/df0501e93eef78402f94f33f948aba996181b3d3c54f97a3f16544916d05/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:322f6fc80c6db1ec87c9d905df3ce259cd22e922f47fbad3c58d0dd6f63bc7a9", size = 51874165, upload-time = "2026-11-03T10:53:41.281Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/30/0d43bf6a49fca51142a96c73d693ec34d229c902a46e007c25f3b9798b52/pyarrow-26.0.1-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:68b91f34e3424d55564e9d4d4f7491aaebd6db3998039cc33ba795a63167f04e", size = 55012741, upload-time = "2026-11-03T10:53:49.153Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ae/ff/0e6cd73832d97c3852284eda9bee2428c53a92bcf6f6aa4bda1e15314a59/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b801300d65859adaf611c9c0a4cb39bd3cb1713b60b974ad20650a8a0f8af2fd", size = 55512474, upload-time = "2026-11-03T10:53:56.512Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/1e/43cdcf9719169f0228b3e516e5004ed0acfc3a4c70ce35e3f2a80a485baf/pyarrow-26.0.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:2623b6c20637c0e2c40be96bda3d127dde49d6e6734ad6e71df91a013e40a3c4", size = 58616300, upload-time = "2026-11-03T10:54:04.472Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/bf/8e29b47c61fc961e92e96db129d5dc7b716c2091dfe05359e70f20d712b9/pyarrow-26.0.1-cp315-cp315t-win_amd64.whl", hash = "sha256:55b1d871f21c8ed249c93f7375a35c35aa9b7b3af6896405cb8a6b67ad9bc7f9", size = 29909417, upload-time = "2026-11-03T10:54:09.613Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3911,7 +4104,8 @@ name = "pyarrow-stubs"
|
||||
version = "20.0.0.20260625"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ff/7d/a3eadf94131428ec61b44bc40a52acca2b093bf0f6a90a0596c44aa9fe62/pyarrow_stubs-20.0.0.20260625.tar.gz", hash = "sha256:cae81ae0900d0710e5b8a6271fef34ccfacb08663bb5f805d94f129baf13130e", size = 237707, upload-time = "2026-06-25T07:27:47.496Z" }
|
||||
wheels = [
|
||||
@@ -4090,14 +4284,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "pyjwt"
|
||||
version = "2.13.0"
|
||||
version = "2.15.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515, upload-time = "2026-05-21T19:54:36.618Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274, upload-time = "2026-05-21T19:54:35.362Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -4107,54 +4301,24 @@ crypto = [
|
||||
|
||||
[[package]]
|
||||
name = "pylance"
|
||||
version = "15.0.0b4"
|
||||
version = "15.0.0b25"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "lance-namespace", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform == 'darwin'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*' and sys_platform == 'darwin'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and sys_platform == 'darwin'" },
|
||||
{ name = "pyarrow", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "lance-namespace" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "pyarrow", version = "25.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1Bbzay/pylance-15.0.0b4-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c948ac22105a0bd9f8314edb883edac421a64b059d992ea6d614773cd2fa2e65" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pylance"
|
||||
version = "15.0.0b9"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'win32'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'emscripten'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'linux'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin' and sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'linux'",
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version == '3.11.*' and sys_platform == 'linux'",
|
||||
"python_full_version == '3.11.*' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
"python_full_version < '3.11' and sys_platform == 'linux'",
|
||||
"python_full_version < '3.11' and sys_platform != 'darwin' and sys_platform != 'linux'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "lance-namespace", marker = "sys_platform != 'darwin'" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform != 'darwin'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*' and sys_platform != 'darwin'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12' and sys_platform != 'darwin'" },
|
||||
{ name = "pyarrow", marker = "sys_platform != 'darwin'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_11uz9g/pylance-15.0.0b9-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:749d4da73a22f5d33f6926387109dfaf814413d3bd1c36b974edf81ca040eb04" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_Zl1Qd/pylance-15.0.0b9-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c49523c68122f4cb42fd310155af6f420f90559752f0735d1503c06f7f45629" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_23GhEu/pylance-15.0.0b9-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:78ff23c91b1b4113bae7715fd143af1fec732cdc0fd2429db6d3149de16d565a" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1IKCVE/pylance-15.0.0b9-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ee8f71b7bdf16bb44305f961b6a2cf4a75f47f1db7d217955e2aca0020acdf05" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_10hNTp/pylance-15.0.0b9-cp310-abi3-win_amd64.whl", hash = "sha256:28f1f92c8af8072a7fdc6f4eca5a8814a54e457843e2ac7e0f00554da5152d90" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2hpc2R/pylance-15.0.0b25-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2a0bb8d6b0c55b7a821989759fc0f8f62cb4da621f89eae232cef49bb7ef341e" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_4LUKQ/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9b73e6e9373c4d5af3fea51e63c3e55873f470aa1a6d0412c22916f88ff5df88" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_11CcHk/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8090d403b2a38cd4ac8eb09de0327bc404cb3bc965d905f2b6a8479891273fae" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1S87Ih/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7f0a20e8ed41d3e49cd5e0bbba97d18ad684cf337e053641321404c9db34f1a1" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_13KmLJ/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:079385a6816a10d42f57bc467d9c822c7207cd31d9a6f768bbf522c0a3007229" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1bTDlQ/pylance-15.0.0b25-cp310-abi3-win_amd64.whl", hash = "sha256:d9b1d713b0d03043a3f5596e909405787f85219f54c427b14437367f0ea7acb9" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_j7adN/pylance-15.0.0b25-cp310-abi3-win_arm64.whl", hash = "sha256:4a1c18176ffd6a860c6e66b0deb39fcc9ac1434dba57ee66559b7638ad4a200a" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4974,10 +5138,10 @@ resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "joblib", marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "threadpoolctl", marker = "python_full_version < '3.11'" },
|
||||
{ name = "joblib" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "threadpoolctl" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" }
|
||||
wheels = [
|
||||
@@ -5031,13 +5195,13 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "joblib", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "narwhals", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "joblib" },
|
||||
{ name = "narwhals" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
|
||||
{ name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "threadpoolctl", marker = "python_full_version >= '3.11'" },
|
||||
{ name = "threadpoolctl" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fa/6f/37092bdb25f712817231799fc5674d8e704066a8a70c1d2d40517e18b4ab/scikit_learn-1.9.0.tar.gz", hash = "sha256:8833266989d3a5110178a9fae30783675460724d0e1efb13b14901d2c660c557", size = 7750767, upload-time = "2026-06-02T11:54:32.706Z" }
|
||||
wheels = [
|
||||
@@ -5083,7 +5247,7 @@ resolution-markers = [
|
||||
"python_full_version < '3.11' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" }
|
||||
wheels = [
|
||||
@@ -5144,7 +5308,7 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" }
|
||||
wheels = [
|
||||
@@ -5225,7 +5389,7 @@ resolution-markers = [
|
||||
"python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" } },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" }
|
||||
wheels = [
|
||||
@@ -5629,7 +5793,8 @@ dependencies = [
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
{ name = "pillow" },
|
||||
{ name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "pillow", version = "13.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "torch" },
|
||||
]
|
||||
wheels = [
|
||||
@@ -5803,11 +5968,11 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "2.7.0"
|
||||
version = "2.8.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user