mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main and align cosine fix with Lance beta.26
This commit is contained in:
+2
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.18"
|
||||
version = "0.42.0-beta.22"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
@@ -53,7 +53,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
@@ -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",
|
||||
@@ -64,7 +64,7 @@ tests = [
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b25",
|
||||
"pylance==15.0.0b26",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
|
||||
@@ -29,7 +29,6 @@ from ._lancedb import (
|
||||
)
|
||||
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
|
||||
@@ -39,13 +38,18 @@ 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 .job import AsyncJob, Job, JobState
|
||||
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,
|
||||
@@ -75,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 (
|
||||
@@ -678,6 +683,11 @@ __all__ = [
|
||||
"FunctionColumnLastRefreshJob",
|
||||
"FunctionColumnStatus",
|
||||
"FunctionColumnVersionStatus",
|
||||
"FunctionErrors",
|
||||
"AsyncFunctionErrors",
|
||||
"FunctionErrorGroup",
|
||||
"FunctionProvenance",
|
||||
"FunctionValueProvenance",
|
||||
"col",
|
||||
"Expr",
|
||||
"func",
|
||||
@@ -686,9 +696,12 @@ __all__ = [
|
||||
"sanitize_uri",
|
||||
"blob",
|
||||
"BlobType",
|
||||
"BasePath",
|
||||
"blob_uri_array",
|
||||
"vector",
|
||||
"DBConnection",
|
||||
"Job",
|
||||
"JobState",
|
||||
"QueryDescription",
|
||||
"SqlQuery",
|
||||
"LanceDBConnection",
|
||||
|
||||
@@ -7,7 +7,9 @@ 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
|
||||
@@ -30,10 +32,47 @@ 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:
|
||||
@@ -376,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}"
|
||||
)
|
||||
|
||||
|
||||
@@ -417,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}"
|
||||
)
|
||||
|
||||
|
||||
@@ -638,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(
|
||||
@@ -662,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]]:
|
||||
|
||||
@@ -26,6 +26,7 @@ from .index import (
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -323,6 +324,9 @@ class Connection(object):
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[pa.RecordBatch] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> SqlQuery: ...
|
||||
async def describe_query(self, query_id: UUID) -> QueryDescription: ...
|
||||
async def create_table(
|
||||
@@ -333,6 +337,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,
|
||||
@@ -342,6 +349,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,
|
||||
@@ -379,6 +388,11 @@ class Connection(object):
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
@@ -393,6 +407,11 @@ class Connection(object):
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
@@ -433,6 +452,20 @@ class BlobFile:
|
||||
def read_up_to(self, length: int) -> bytes: ...
|
||||
|
||||
class Job:
|
||||
@property
|
||||
def job_id(self) -> Optional[str]: ...
|
||||
@property
|
||||
def operation_id(self) -> Optional[str]: ...
|
||||
@property
|
||||
def attempt(self) -> Optional[int]: ...
|
||||
@property
|
||||
def retry_of(self) -> Optional[str]: ...
|
||||
@property
|
||||
def lifecycle_state(self) -> Optional[str]: ...
|
||||
@property
|
||||
def source_table_version(self) -> Optional[int]: ...
|
||||
@property
|
||||
def execution_epoch(self) -> Optional[int]: ...
|
||||
@property
|
||||
def id(self) -> Optional[str]: ...
|
||||
@property
|
||||
@@ -447,14 +480,34 @@ class Job:
|
||||
progress: Optional[Callable[[dict[str, Any]], None]] = None,
|
||||
) -> Optional[str]: ...
|
||||
async def cancel(self) -> None: ...
|
||||
async def retry(self) -> Job: ...
|
||||
async def refresh(self) -> None: ...
|
||||
async def timeline(self) -> str: ...
|
||||
async def stack(self, worker_id: str) -> str: ...
|
||||
async def capture_profile(
|
||||
self,
|
||||
worker_id: str,
|
||||
*,
|
||||
kind: str = "cpu",
|
||||
duration_seconds: Optional[float] = None,
|
||||
session_slot: int = 0,
|
||||
) -> str: ...
|
||||
async def profile_status(self, profile_id: str) -> str: ...
|
||||
async def wait_for_profile(
|
||||
self,
|
||||
profile_id: str,
|
||||
*,
|
||||
timeout_seconds: Optional[float] = None,
|
||||
poll_interval_seconds: Optional[float] = None,
|
||||
) -> str: ...
|
||||
async def profile_artifact(self, profile_id: str) -> str: ...
|
||||
async def stats(self) -> Optional[str]: ...
|
||||
async def events(
|
||||
self,
|
||||
*,
|
||||
limit: Optional[int] = None,
|
||||
filter: Optional[str] = None,
|
||||
page_token: Optional[str] = None,
|
||||
) -> pa.Table: ...
|
||||
|
||||
class JobInfo:
|
||||
@@ -469,6 +522,18 @@ class JobInfo:
|
||||
@property
|
||||
def created_at_millis(self) -> int: ...
|
||||
@property
|
||||
def completed_at_millis(self) -> Optional[int]: ...
|
||||
@property
|
||||
def duration_millis(self) -> Optional[int]: ...
|
||||
@property
|
||||
def columns(self) -> list[str]: ...
|
||||
@property
|
||||
def function_name(self) -> Optional[str]: ...
|
||||
@property
|
||||
def function_version(self) -> Optional[str]: ...
|
||||
@property
|
||||
def failure(self) -> Optional[JobFailureInfo]: ...
|
||||
@property
|
||||
def progress(self) -> Optional[dict[str, Any]]: ...
|
||||
@property
|
||||
def paused(self) -> bool: ...
|
||||
@@ -519,6 +584,18 @@ class JobFailureInfo:
|
||||
def sql_job_id(self) -> Optional[str]: ...
|
||||
|
||||
class JobDescription:
|
||||
@property
|
||||
def operation_id(self) -> Optional[str]: ...
|
||||
@property
|
||||
def attempt(self) -> Optional[int]: ...
|
||||
@property
|
||||
def retry_of(self) -> Optional[str]: ...
|
||||
@property
|
||||
def lifecycle_state(self) -> Optional[str]: ...
|
||||
@property
|
||||
def source_table_version(self) -> Optional[int]: ...
|
||||
@property
|
||||
def execution_epoch(self) -> Optional[int]: ...
|
||||
@property
|
||||
def job_id(self) -> str: ...
|
||||
@property
|
||||
@@ -568,6 +645,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,
|
||||
@@ -603,6 +681,7 @@ class Table:
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -628,6 +707,7 @@ class Table:
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -639,11 +719,33 @@ class Table:
|
||||
) -> Job: ...
|
||||
async def list_versions(self) -> List[Dict[str, Any]]: ...
|
||||
async def version(self) -> int: ...
|
||||
async def delta(
|
||||
self,
|
||||
from_version: Union[int, str],
|
||||
to_version: Optional[Union[int, str]] = None,
|
||||
) -> TableDelta: ...
|
||||
async def checkout(self, version: Union[int, str]): ...
|
||||
async def checkout_latest(self): ...
|
||||
async def _checkout_current(self) -> 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,
|
||||
@@ -662,7 +764,11 @@ 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,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> AddColumnsResult: ...
|
||||
async def add_function_columns(
|
||||
self,
|
||||
@@ -670,7 +776,11 @@ 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,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> AddColumnsResult: ...
|
||||
async def refresh_column(
|
||||
self,
|
||||
@@ -680,11 +790,13 @@ class Table:
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[dict[str, int]] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[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,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[str] = None,
|
||||
error_policy: Optional[str] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
@@ -692,7 +804,14 @@ class Table:
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_job_attempts: 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,
|
||||
@@ -702,11 +821,13 @@ class Table:
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[dict[str, int]] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[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,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[str] = None,
|
||||
error_policy: Optional[str] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
@@ -714,14 +835,40 @@ class Table:
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_job_attempts: 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 resume_refresh(self, job_id: str) -> Job: ...
|
||||
async def function_errors(
|
||||
self,
|
||||
job_id: Optional[str] = None,
|
||||
column: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
history: bool = False,
|
||||
page_token: Optional[str] = None,
|
||||
) -> 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]: ...
|
||||
@@ -734,20 +881,22 @@ class Table:
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> RefreshMaterializedViewResult: ...
|
||||
async def refresh_materialized_view_async(
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> Job: ...
|
||||
async def materialized_view_definition(self) -> str: ...
|
||||
async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ...
|
||||
@@ -757,6 +906,11 @@ class Table:
|
||||
async def update_field_metadata(
|
||||
self, updates: list[dict[str, Any]]
|
||||
) -> UpdateFieldMetadataResult: ...
|
||||
async def cleanup_async(self, min_age_seconds: Optional[int] = None) -> Job: ...
|
||||
async def explain_cleanup(self, min_age_seconds: Optional[int] = None) -> str: ...
|
||||
async def compact_async(
|
||||
self, compaction_options: Optional[Dict[str, Any]] = None
|
||||
) -> Job: ...
|
||||
async def optimize(
|
||||
self,
|
||||
*,
|
||||
@@ -805,7 +959,13 @@ class Table:
|
||||
requests: Sequence[Sequence[int]],
|
||||
) -> pa.LargeBinaryArray: ...
|
||||
async def fetch_blob_files(
|
||||
self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
|
||||
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, buffer_size: Optional[int] = None
|
||||
@@ -815,7 +975,7 @@ class Table:
|
||||
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): ...
|
||||
|
||||
@@ -826,6 +986,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: ...
|
||||
@@ -886,11 +1048,26 @@ class RecordBatchStream:
|
||||
def __aiter__(self) -> "RecordBatchStream": ...
|
||||
async def __anext__(self) -> pa.RecordBatch: ...
|
||||
|
||||
class SyncRecordBatchStream:
|
||||
@property
|
||||
def schema(self) -> pa.Schema: ...
|
||||
def __iter__(self) -> "SyncRecordBatchStream": ...
|
||||
def __next__(self) -> pa.RecordBatch: ...
|
||||
|
||||
class ColumnOrdering(TypedDict):
|
||||
column_name: str
|
||||
ascending: bool
|
||||
nulls_first: bool
|
||||
|
||||
class TableDelta:
|
||||
def begin_version(self) -> int: ...
|
||||
def end_version(self) -> int: ...
|
||||
async def inserted_rows(self) -> RecordBatchStream: ...
|
||||
async def updated_rows(self) -> RecordBatchStream: ...
|
||||
async def upserted_rows(self) -> RecordBatchStream: ...
|
||||
async def deleted_row_ids(self) -> RecordBatchStream: ...
|
||||
async def list_transactions(self) -> List[Dict[str, Any]]: ...
|
||||
|
||||
class Query:
|
||||
def where(self, filter: str): ...
|
||||
def where_expr(self, expr: PyExpr): ...
|
||||
@@ -906,10 +1083,20 @@ 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: ...
|
||||
def execute_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> SyncRecordBatchStream: ...
|
||||
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
|
||||
@@ -919,9 +1106,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
|
||||
@@ -948,6 +1139,12 @@ class FTSQuery:
|
||||
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
|
||||
@@ -957,6 +1154,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]]): ...
|
||||
@@ -1017,6 +1220,7 @@ class PyQueryRequest:
|
||||
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]]]
|
||||
@@ -1040,6 +1244,7 @@ class PyQueryRequest:
|
||||
postfilter: Optional[bool]
|
||||
norm: Optional[str]
|
||||
order_by: Optional[List[ColumnOrdering]]
|
||||
scan_in_order: Optional[bool]
|
||||
|
||||
class CompactionStats:
|
||||
fragments_removed: int
|
||||
@@ -1127,8 +1332,13 @@ 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
|
||||
attempt_job_id: Optional[str]
|
||||
fragment_id: int
|
||||
row_offset: Optional[int]
|
||||
row_id: Optional[int]
|
||||
@@ -1150,6 +1360,10 @@ class FunctionErrorFragment:
|
||||
rows_recorded: int
|
||||
|
||||
class FunctionErrors:
|
||||
workflow_version: Optional[int]
|
||||
error_groups_json: str
|
||||
@property
|
||||
def page_token(self) -> Optional[str]: ...
|
||||
records: list[FunctionErrorRecord]
|
||||
fragments: list[FunctionErrorFragment]
|
||||
truncated: bool
|
||||
@@ -1222,7 +1436,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,
|
||||
@@ -1245,6 +1464,14 @@ class AsyncPermutationBuilder:
|
||||
self, seed: Optional[int], clump_size: Optional[int]
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
def filter(self, filter: str) -> "AsyncPermutationBuilder": ...
|
||||
def persist(
|
||||
self,
|
||||
db: Connection,
|
||||
table_name: str,
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
mode: str = "create",
|
||||
) -> "AsyncPermutationBuilder": ...
|
||||
async def execute(self) -> Table: ...
|
||||
|
||||
def async_permutation_builder(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Results of durable remote version cleanup."""
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CleanupResult:
|
||||
"""Version-deletion outcome, excluding best-effort auxiliary sweeps.
|
||||
|
||||
Unknown totals after retry/recovery are None, never fabricated zeroes.
|
||||
Completion does not guarantee that every orphaned file was reclaimed.
|
||||
"""
|
||||
|
||||
format_version: int
|
||||
min_age_seconds: int
|
||||
statistics_complete: bool
|
||||
old_versions: Optional[int] = None
|
||||
bytes_removed: Optional[int] = None
|
||||
failed_deletes: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CleanupResult":
|
||||
"""Decode the versioned contract, preserving unknown measurements."""
|
||||
value = json.loads(raw)
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or type(value.get("format_version")) is not int
|
||||
or value["format_version"] != 1
|
||||
):
|
||||
raise ValueError("unsupported cleanup result format")
|
||||
if type(value.get("statistics_complete")) is not bool:
|
||||
raise ValueError("invalid cleanup result statistics_complete")
|
||||
for key in (
|
||||
"min_age_seconds",
|
||||
"old_versions",
|
||||
"bytes_removed",
|
||||
"failed_deletes",
|
||||
):
|
||||
count = value.get(key)
|
||||
if count is None and key != "min_age_seconds":
|
||||
continue
|
||||
if type(count) is not int or count < 0:
|
||||
raise ValueError(f"invalid cleanup result {key}")
|
||||
counts = [value.get("old_versions"), value.get("bytes_removed")]
|
||||
if not value["statistics_complete"] and value.get("failed_deletes") is not None:
|
||||
raise ValueError("inconsistent cleanup failed-deletion measurement")
|
||||
if (
|
||||
value["statistics_complete"] and any(count is None for count in counts)
|
||||
) or (
|
||||
not value["statistics_complete"]
|
||||
and any(count is not None for count in counts)
|
||||
):
|
||||
raise ValueError("inconsistent cleanup result statistics")
|
||||
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 CleanupPlan:
|
||||
"""Read-only version-deletion estimates, excluding auxiliary sweeps.
|
||||
|
||||
No job or deletion snapshot is reserved. Execution plans current state again.
|
||||
"""
|
||||
|
||||
format_version: int
|
||||
source_version: int
|
||||
min_age_seconds: int
|
||||
cutoff_millis: int
|
||||
versions_to_remove: int
|
||||
bytes_to_remove: int
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, raw: str) -> "CleanupPlan":
|
||||
value = json.loads(raw)
|
||||
if not isinstance(value, dict) or value.get("format_version") != 1:
|
||||
raise ValueError("unsupported cleanup preview format")
|
||||
names = {field.name for field in fields(cls)}
|
||||
for name in names:
|
||||
item = value.get(name)
|
||||
if type(item) is not int or (name != "cutoff_millis" and item < 0):
|
||||
raise ValueError(f"invalid cleanup preview {name}")
|
||||
return cls(**{key: item for key, item in value.items() if key in names})
|
||||
|
||||
|
||||
def _validate_min_age_seconds(value: Optional[int]) -> None:
|
||||
if value is not None and (type(value) is not int or value < 0):
|
||||
raise ValueError("min_age_seconds must be a nonnegative integer or None")
|
||||
@@ -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})
|
||||
+247
-7
@@ -118,6 +118,7 @@ from .namespace_utils import (
|
||||
_normalize_drop_namespace_mode,
|
||||
_normalize_drop_namespace_behavior,
|
||||
)
|
||||
from .resources import _resource_options
|
||||
|
||||
|
||||
def _view_description(
|
||||
@@ -507,6 +508,8 @@ class DBConnection(EnforceOverrides):
|
||||
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.
|
||||
|
||||
@@ -570,6 +573,23 @@ class DBConnection(EnforceOverrides):
|
||||
enable_v2_manifest_paths: optional, bool, default False
|
||||
Deprecated. Set `storage_options` when connecting to the database and set
|
||||
`new_table_enable_v2_manifest_paths` in the options.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it, so a create with data stays atomic. Each
|
||||
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
|
||||
`path`, `name`, `is_dataset_root`, and `id` keys, or a
|
||||
`lance.DatasetBasePath`. Blob URIs that fall under a registered
|
||||
base are stored relative to it; other URIs need
|
||||
`allow_external_blob_outside_bases=True`. `None` and an empty
|
||||
list are equivalent. When supplying IDs for multiple bases, use
|
||||
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
|
||||
describes the pinned-Lance limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. Set
|
||||
`initial_bases` instead when the URIs share a registered prefix.
|
||||
Defaults to rejecting such URIs. The opt-in applies only to the
|
||||
initial data; a later `add()` must enable it again.
|
||||
Returns
|
||||
-------
|
||||
LanceTable
|
||||
@@ -745,6 +765,11 @@ class DBConnection(EnforceOverrides):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> MaterializedView:
|
||||
"""Define a materialized view named ``name`` over the table ``source``.
|
||||
|
||||
@@ -788,6 +813,14 @@ class DBConnection(EnforceOverrides):
|
||||
Positive, finite refresh interval in seconds in LanceDB Enterprise.
|
||||
When omitted, the server determines when to refresh.
|
||||
|
||||
total_cpu_millis: int, optional
|
||||
Default total CPU budget in millicores for initial population and
|
||||
refreshes. Overrides Function defaults. LanceDB Enterprise only.
|
||||
total_memory_bytes: int, optional
|
||||
Default total memory budget in bytes. LanceDB Enterprise only.
|
||||
total_gpu_count: int, optional
|
||||
Default total GPU budget across workers. LanceDB Enterprise only.
|
||||
|
||||
Returns
|
||||
-------
|
||||
MaterializedView
|
||||
@@ -799,6 +832,13 @@ class DBConnection(EnforceOverrides):
|
||||
... query="SELECT kind, count(*) AS n FROM events GROUP BY kind",
|
||||
... )
|
||||
"""
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
raise NotImplementedError(
|
||||
_append_doc_url(
|
||||
"materialized views are not supported on this connection type",
|
||||
@@ -819,6 +859,11 @@ class DBConnection(EnforceOverrides):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> Job[None]:
|
||||
"""Submit materialized-view creation and return its job.
|
||||
|
||||
@@ -835,6 +880,13 @@ class DBConnection(EnforceOverrides):
|
||||
Servers without early registry-handle support return a connection-scoped
|
||||
query job instead. Its ID cannot be reopened with :meth:`open_job`.
|
||||
"""
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
raise NotImplementedError(
|
||||
_append_doc_url(
|
||||
"materialized views are not supported on this connection type",
|
||||
@@ -1562,7 +1614,7 @@ class DBConnection(EnforceOverrides):
|
||||
[RefreshColumnResult][lancedb.functions.RefreshColumnResult], including
|
||||
when the refresh was started through SQL. Other job types return
|
||||
``None`` from ``wait()``; their persisted result is available through
|
||||
``job.result`` after ``job.refresh()``.
|
||||
``job.result()`` after ``job.checkout_latest()``.
|
||||
|
||||
Raises `JobNotFoundError` when the server has no such job, the way
|
||||
`open_table` does for a missing table.
|
||||
@@ -1698,6 +1750,9 @@ class DBConnection(EnforceOverrides):
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> pa.RecordBatchReader:
|
||||
"""Execute SQL and return a blocking Arrow reader.
|
||||
|
||||
@@ -1712,6 +1767,9 @@ class DBConnection(EnforceOverrides):
|
||||
query,
|
||||
default_namespace_path=default_namespace_path,
|
||||
parameters=parameters,
|
||||
timeout=timeout,
|
||||
read_timeout=read_timeout,
|
||||
cancel_on_drop=cancel_on_drop,
|
||||
).reader()
|
||||
|
||||
def execute_query_async(
|
||||
@@ -1720,6 +1778,9 @@ class DBConnection(EnforceOverrides):
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> SqlQuery:
|
||||
"""Start executing SQL and return its query handle.
|
||||
|
||||
@@ -1738,17 +1799,31 @@ class DBConnection(EnforceOverrides):
|
||||
parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10],
|
||||
)
|
||||
|
||||
Parameters are supported in queries, not in DDL or DML. With or
|
||||
without parameters, the server chooses whether to stream rows on the
|
||||
Parameters are supported in queries and, on compatible Enterprise servers,
|
||||
scalar filter values in ``PREWARM`` and ``EXPLAIN PREWARM``. Support for
|
||||
other statement types depends on the server.
|
||||
|
||||
With or without parameters, the server chooses whether to stream rows on the
|
||||
initial call or return a polling continuation. The reader follows
|
||||
either path transparently. Dropping an unread handle or its reader
|
||||
stops a directly streamed query; deferred execution requires explicit
|
||||
cancellation. Open ``reader()`` directly: a streamed query needs its
|
||||
reader to make progress and reports ``running`` until the stream ends.
|
||||
stops a directly streamed query. Set ``cancel_on_drop=True`` to also
|
||||
attempt cancellation of deferred Flight execution when its unread handle
|
||||
or reader is dropped. By default, deferred queries can be detached.
|
||||
Open ``reader()`` directly: a streamed query needs its reader to make
|
||||
progress and reports ``running`` until the stream ends.
|
||||
Once a server-side SQL job exists, ``describe().job_id`` exposes its
|
||||
durable Job Registry id while the query is still running. This is
|
||||
separate from the connection-scoped query ``id``.
|
||||
|
||||
``timeout`` limits submission and result consumption together, starting
|
||||
when the query is submitted. It also applies before a reader is opened.
|
||||
``read_timeout`` overrides the connection's limit for each server read.
|
||||
Both accept ``datetime.timedelta``. On expiry or a failed result read,
|
||||
the SDK stops reading and attempts to cancel Flight execution.
|
||||
Cancellation on drop is best effort and requires the connection's runtime
|
||||
to remain alive. Durable server-side jobs require explicit
|
||||
``cancel_job(query.job_id)`` regardless of these options.
|
||||
|
||||
LanceDB Embedded connections do not support SQL.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
@@ -1933,11 +2008,40 @@ class LanceDBConnection(DBConnection):
|
||||
"manifest_enabled": self._manifest_enabled,
|
||||
"namespace_client_properties": self._namespace_client_properties,
|
||||
"read_consistency_interval_seconds": (
|
||||
rci.total_seconds() if rci else None
|
||||
rci.total_seconds() if rci is not None else None
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def _pickle_state(self) -> str:
|
||||
"""Serialize this connection for pickle-based workers."""
|
||||
if self._session is not None:
|
||||
raise TypeError(
|
||||
"Cannot pickle a LanceDBConnection created with a Session; "
|
||||
"Session objects are not serializable. Create the Session in "
|
||||
"each worker process instead."
|
||||
)
|
||||
if self.uri.startswith("memory://"):
|
||||
raise TypeError(
|
||||
"Cannot pickle an in-memory LanceDBConnection because its tables "
|
||||
"exist only in this process. Pickle a LanceTable instead to "
|
||||
"export its data, or connect to a persistent URI."
|
||||
)
|
||||
return self.serialize()
|
||||
|
||||
def __getstate__(self) -> dict[str, str]:
|
||||
return {"serialized": self._pickle_state()}
|
||||
|
||||
def __setstate__(self, state: dict[str, str]) -> None:
|
||||
from . import deserialize_conn
|
||||
|
||||
connection = deserialize_conn(state["serialized"], for_worker=True)
|
||||
if not isinstance(connection, LanceDBConnection):
|
||||
raise TypeError(
|
||||
"Serialized connection did not reconstruct a LanceDBConnection"
|
||||
)
|
||||
self.__dict__.update(connection.__dict__)
|
||||
|
||||
async def _async_get_table_names(self, start_after: Optional[str], limit: int):
|
||||
conn = AsyncConnection(await lancedb_connect(self.uri))
|
||||
return await conn.table_names(start_after=start_after, limit=limit)
|
||||
@@ -2124,6 +2228,8 @@ class LanceDBConnection(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,
|
||||
) -> LanceTable:
|
||||
"""Create a table in the database.
|
||||
|
||||
@@ -2154,6 +2260,8 @@ class LanceDBConnection(DBConnection):
|
||||
storage_options=storage_options,
|
||||
data_storage_version=data_storage_version,
|
||||
enable_v2_manifest_paths=enable_v2_manifest_paths,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
return tbl
|
||||
|
||||
@@ -2165,6 +2273,7 @@ class LanceDBConnection(DBConnection):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
index_cache_size: Optional[int] = None,
|
||||
location: Optional[str] = None,
|
||||
branch: Optional[str] = None,
|
||||
version: Optional[int] = None,
|
||||
) -> LanceTable:
|
||||
@@ -2177,6 +2286,10 @@ class LanceDBConnection(DBConnection):
|
||||
namespace_path: List[str], optional
|
||||
The namespace to open the table from. When non-empty, the
|
||||
table is resolved through the directory namespace client.
|
||||
location: str, optional
|
||||
The explicit location (URI) of the table. If provided, the table will be
|
||||
opened from this location instead of deriving it from the database URI
|
||||
and table name.
|
||||
branch: str, optional
|
||||
If provided, open a handle scoped to this branch instead of the
|
||||
default branch. Reads and writes operate in the branch's context.
|
||||
@@ -2210,6 +2323,7 @@ class LanceDBConnection(DBConnection):
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
index_cache_size=index_cache_size,
|
||||
location=location,
|
||||
)
|
||||
except (RuntimeError, ValueError) as e:
|
||||
if namespace_path and (
|
||||
@@ -2241,6 +2355,11 @@ class LanceDBConnection(DBConnection):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> MaterializedView:
|
||||
"""Define a materialized view named ``name`` over the table ``source``.
|
||||
|
||||
@@ -2268,6 +2387,13 @@ class LanceDBConnection(DBConnection):
|
||||
>>> view.table.count_rows() # doctest: +SKIP
|
||||
1
|
||||
"""
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
LOOP.run(
|
||||
self._conn.create_materialized_view(
|
||||
name,
|
||||
@@ -2280,6 +2406,11 @@ class LanceDBConnection(DBConnection):
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
)
|
||||
return MaterializedView(self.open_table(name))
|
||||
@@ -2298,7 +2429,19 @@ class LanceDBConnection(DBConnection):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> Job[None]:
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
job = LOOP.run(
|
||||
self._conn.create_materialized_view_async(
|
||||
name,
|
||||
@@ -2311,6 +2454,11 @@ class LanceDBConnection(DBConnection):
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -3258,6 +3406,8 @@ class AsyncConnection(object):
|
||||
embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Create an [AsyncTable][lancedb.table.AsyncTable] in the database.
|
||||
|
||||
@@ -3315,6 +3465,23 @@ class AsyncConnection(object):
|
||||
To enable stable row IDs (row IDs remain stable after compaction,
|
||||
update, delete, and merges), set `new_table_enable_stable_row_ids`
|
||||
to `"true"` in storage_options when connecting to the database.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it, so a create with data stays atomic. Each
|
||||
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
|
||||
`path`, `name`, `is_dataset_root`, and `id` keys, or a
|
||||
`lance.DatasetBasePath`. Blob URIs that fall under a registered
|
||||
base are stored relative to it; other URIs need
|
||||
`allow_external_blob_outside_bases=True`. `None` and an empty
|
||||
list are equivalent. When supplying IDs for multiple bases, use
|
||||
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
|
||||
describes the pinned-Lance limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. Requires
|
||||
initial `data`; the opt-in applies only to that initial write, and
|
||||
a later `add()` must enable it again. Defaults to rejecting such
|
||||
URIs.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -3426,6 +3593,25 @@ class AsyncConnection(object):
|
||||
"""
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
if get_uri_scheme(self.uri) == "db":
|
||||
# The Enterprise create endpoint has no way to express either
|
||||
# option. Reject before sanitizing or reading `data`, and do not
|
||||
# point at a local-only or remote `add` path.
|
||||
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 data is None and allow_external_blob_outside_bases:
|
||||
raise ValueError(
|
||||
"allow_external_blob_outside_bases requires initial data; "
|
||||
"pass it to add() for later writes"
|
||||
)
|
||||
metadata = None
|
||||
|
||||
if embedding_functions is not None:
|
||||
@@ -3472,6 +3658,7 @@ class AsyncConnection(object):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
)
|
||||
else:
|
||||
data = data_to_reader(data, schema)
|
||||
@@ -3483,6 +3670,8 @@ class AsyncConnection(object):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
|
||||
return AsyncTable(new_table)
|
||||
@@ -3589,6 +3778,11 @@ class AsyncConnection(object):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> AsyncMaterializedView:
|
||||
"""Define a materialized view named ``name`` over the table ``source``.
|
||||
|
||||
@@ -3601,6 +3795,13 @@ class AsyncConnection(object):
|
||||
See
|
||||
[DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
|
||||
"""
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
_validate_create_materialized_view(source, query, select, where, limit)
|
||||
if source is not None:
|
||||
source, native_options = await self._materialized_view_source(
|
||||
@@ -3620,7 +3821,12 @@ class AsyncConnection(object):
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
**native_options,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
return AsyncMaterializedView(AsyncTable(inner))
|
||||
|
||||
@@ -3637,6 +3843,11 @@ class AsyncConnection(object):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> AsyncJob[None]:
|
||||
"""Submit materialized-view creation and return its job.
|
||||
|
||||
@@ -3647,6 +3858,13 @@ class AsyncConnection(object):
|
||||
Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
|
||||
identifies that query on this connection.
|
||||
"""
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
_validate_create_materialized_view(source, query, select, where, limit)
|
||||
if source is not None:
|
||||
source, native_options = await self._materialized_view_source(
|
||||
@@ -3666,7 +3884,12 @@ class AsyncConnection(object):
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
**native_options,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
return AsyncJob(inner)
|
||||
|
||||
@@ -4528,6 +4751,9 @@ class AsyncConnection(object):
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> AsyncRecordBatchReader:
|
||||
"""Execute SQL and return an asynchronous Arrow reader.
|
||||
|
||||
@@ -4542,6 +4768,9 @@ class AsyncConnection(object):
|
||||
query,
|
||||
default_namespace_path=default_namespace_path,
|
||||
parameters=parameters,
|
||||
timeout=timeout,
|
||||
read_timeout=read_timeout,
|
||||
cancel_on_drop=cancel_on_drop,
|
||||
)
|
||||
return await submitted.reader()
|
||||
|
||||
@@ -4551,6 +4780,9 @@ class AsyncConnection(object):
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> AsyncSqlQuery:
|
||||
"""Start executing SQL and return its query handle.
|
||||
|
||||
@@ -4558,6 +4790,11 @@ class AsyncConnection(object):
|
||||
references. The namespace defaults to ``["public"]``. ``parameters``
|
||||
binds values to ``$1`` / ``$name`` placeholders; see
|
||||
[DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async].
|
||||
``timeout`` covers submission through result consumption, including
|
||||
time before opening a reader. ``read_timeout`` limits each server read.
|
||||
``cancel_on_drop=True`` also attempts to cancel deferred Flight execution
|
||||
when its unread handle or reader is dropped. See the synchronous method
|
||||
above for cancellation and durable-job behavior.
|
||||
LanceDB Embedded connections raise ``NotImplementedError``.
|
||||
"""
|
||||
return AsyncSqlQuery(
|
||||
@@ -4565,6 +4802,9 @@ class AsyncConnection(object):
|
||||
query,
|
||||
default_namespace_path=default_namespace_path,
|
||||
parameters=to_parameter_batch(parameters),
|
||||
timeout=timeout,
|
||||
read_timeout=read_timeout,
|
||||
cancel_on_drop=cancel_on_drop,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import builtins
|
||||
import base64
|
||||
import functools
|
||||
import hashlib
|
||||
import importlib.metadata
|
||||
import importlib.util
|
||||
import inspect
|
||||
import symtable
|
||||
@@ -64,15 +65,13 @@ from .schema import is_blob_v2_field as _is_blob_v2_field
|
||||
from ._blob_reader import BlobReader
|
||||
from ._lancedb import _validate_conda_requirement
|
||||
from .secrets import EnvVarSecret
|
||||
from .resources import _validate_gpu_class_name
|
||||
|
||||
_Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1)
|
||||
_UInt32 = conint(strict=True, ge=0, le=2**32 - 1)
|
||||
_PositiveUInt32 = conint(strict=True, ge=1, le=2**32 - 1)
|
||||
_UInt64 = conint(strict=True, ge=0, le=2**64 - 1)
|
||||
_GPU_CLASS_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
|
||||
_GPU_CLASS_ERROR = (
|
||||
"gpu_class must be a lowercase name of at most 63 letters, digits, or "
|
||||
"hyphens, and cannot start or end with a hyphen"
|
||||
)
|
||||
_PositiveUInt64 = conint(strict=True, ge=1, le=2**64 - 1)
|
||||
|
||||
|
||||
def _validate_gpu_wire_marker(value: Any) -> bool:
|
||||
@@ -81,16 +80,24 @@ def _validate_gpu_wire_marker(value: Any) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _normalize_gpu_marker(value: bool) -> Optional[bool]:
|
||||
if not isinstance(value, bool):
|
||||
def _normalize_gpu_request(
|
||||
gpu: Optional[bool], gpu_class: Optional[str], gpu_count: Optional[int]
|
||||
) -> tuple[Optional[bool], Optional[str], Optional[int]]:
|
||||
if gpu is not None and not isinstance(gpu, bool):
|
||||
raise ValueError("gpu must be a boolean")
|
||||
return True if value else None
|
||||
|
||||
|
||||
def _validate_gpu_class_name(value: Any) -> str:
|
||||
if not isinstance(value, str) or not _GPU_CLASS_NAME.fullmatch(value):
|
||||
raise ValueError(_GPU_CLASS_ERROR)
|
||||
return value
|
||||
if gpu is not True:
|
||||
if gpu_class is not None or gpu_count is not None:
|
||||
raise ValueError("gpu_class and gpu_count require gpu=True")
|
||||
return None, None, None
|
||||
if gpu_class is not None:
|
||||
gpu_class = _validate_gpu_class_name(gpu_class)
|
||||
if gpu_count is None:
|
||||
gpu_count = 1
|
||||
if isinstance(gpu_count, bool) or not isinstance(gpu_count, int):
|
||||
raise ValueError("gpu_count must be a positive integer")
|
||||
if not 1 <= gpu_count <= 2**32 - 1:
|
||||
raise ValueError("gpu_count must be between 1 and 4294967295")
|
||||
return True, gpu_class, gpu_count
|
||||
|
||||
|
||||
def _validate_batch_size(value: Any) -> Optional[int]:
|
||||
@@ -451,8 +458,10 @@ class PythonRuntimeSpec(_RemoteValue):
|
||||
|
||||
V1 supports ``kind="python"``. Newer runtime kinds remain readable, while
|
||||
their unknown payload fields are intentionally not retained by the client.
|
||||
``kind="python_v2"`` requires ``gpu=True`` and may name an operator-defined
|
||||
``gpu_class``.
|
||||
``kind="python_v2"`` requires ``gpu=True``. Its ``gpu_class`` records the
|
||||
requested operator-defined class or ``"any"`` for any eligible class;
|
||||
omitting it also accepts any eligible class. It does not identify the
|
||||
hardware selected for execution.
|
||||
"""
|
||||
|
||||
kind: str
|
||||
@@ -461,6 +470,7 @@ class PythonRuntimeSpec(_RemoteValue):
|
||||
env: Optional[Mapping[str, str]] = None
|
||||
gpu: Optional[bool] = None
|
||||
gpu_class: Optional[str] = None
|
||||
gpus_per_worker: Optional[_PositiveUInt32] = None
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -498,6 +508,8 @@ class PythonRuntimeSpec(_RemoteValue):
|
||||
raise ValueError(
|
||||
"python runtime with gpu_class requires kind='python_v2'"
|
||||
)
|
||||
if self.gpus_per_worker is not None:
|
||||
raise ValueError("gpus_per_worker requires kind='python_v2'")
|
||||
elif self.kind == "python_v2":
|
||||
if self.python_version is None:
|
||||
raise ValueError("python_v2 runtime requires python_version")
|
||||
@@ -511,6 +523,7 @@ class PythonRuntimeSpec(_RemoteValue):
|
||||
object.__setattr__(self, "env", None)
|
||||
object.__setattr__(self, "gpu", None)
|
||||
object.__setattr__(self, "gpu_class", None)
|
||||
object.__setattr__(self, "gpus_per_worker", None)
|
||||
return self
|
||||
|
||||
@property
|
||||
@@ -712,8 +725,9 @@ class FunctionVersion(_RemoteValue):
|
||||
version also requires matching the source and all other registration inputs,
|
||||
including signature, Secret bindings, models, and execution controls.
|
||||
|
||||
``gpu_class`` is the operator-defined GPU pool fixed into this Function
|
||||
version, or ``None`` when registration used the deployment default.
|
||||
``gpu_class`` records the default GPU pool for this Function version.
|
||||
Column/MV creation and refresh can override it independently of the
|
||||
per-worker ``gpu_count`` in the requested runtime.
|
||||
|
||||
``batch_size``, ``max_concurrency``, ``row_timeout_seconds``, and
|
||||
``result_stability`` retain the execution controls reported by the
|
||||
@@ -748,6 +762,9 @@ class FunctionVersion(_RemoteValue):
|
||||
gpu_class: Optional[str] = None
|
||||
batch_size: Optional[int] = None
|
||||
max_concurrency: Optional[int] = None
|
||||
total_cpu_millis: Optional[_PositiveUInt64] = None
|
||||
total_memory_bytes: Optional[_PositiveUInt64] = None
|
||||
total_gpu_count: Optional[_UInt32] = None
|
||||
row_timeout_seconds: Optional[float] = None
|
||||
result_stability: Optional[str] = None
|
||||
runtime: Optional[PythonRuntimeSpec] = None
|
||||
@@ -940,6 +957,9 @@ class FunctionRegistrationRequest(_RemoteValue):
|
||||
runtime: PythonRuntimeSpec
|
||||
batch_size: Optional[int] = None
|
||||
max_concurrency: Optional[int] = None
|
||||
total_cpu_millis: Optional[_PositiveUInt64] = None
|
||||
total_memory_bytes: Optional[_PositiveUInt64] = None
|
||||
total_gpu_count: Optional[_UInt32] = None
|
||||
row_timeout_seconds: Optional[float] = None
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None
|
||||
secret_bindings: tuple[SecretBinding, ...] = ()
|
||||
@@ -1132,6 +1152,221 @@ class FunctionBinding(_RemoteValue):
|
||||
return reader.read_all().to_pylist()[0]
|
||||
|
||||
|
||||
class FunctionErrorGroup(_RemoteValue):
|
||||
"""A grouped cause among returned Function failures."""
|
||||
|
||||
column: str
|
||||
error_type: str
|
||||
error_message: str
|
||||
rows_failed: _UInt64
|
||||
|
||||
|
||||
class FunctionValueProvenance(_RemoteValue):
|
||||
"""The Function version and job that produced one stored value."""
|
||||
|
||||
column: str
|
||||
job_id: str
|
||||
function_name: str
|
||||
function_version: str
|
||||
row_id: Optional[_UInt64] = None
|
||||
row_address: Optional[_UInt64] = None
|
||||
source_version: _UInt64
|
||||
published_version: _UInt64
|
||||
|
||||
|
||||
class FunctionProvenance(_RemoteValue):
|
||||
"""A bounded per-row producing-version listing for a table snapshot."""
|
||||
|
||||
records: tuple[FunctionValueProvenance, ...]
|
||||
truncated: bool = False
|
||||
|
||||
|
||||
class _FunctionErrors:
|
||||
"""Current Function failures, with grouped causes and source-row lookup.
|
||||
|
||||
Check ``truncated`` and ``fragments`` before treating a listing as complete.
|
||||
``history=True`` on ``table.function_errors`` returns retained past records.
|
||||
"""
|
||||
|
||||
def __init__(self, raw: Any, table: Any, *, history: bool = False):
|
||||
self._raw = raw
|
||||
self._table = table
|
||||
self._history = history
|
||||
self.records = raw.records
|
||||
self.fragments = raw.fragments
|
||||
self.truncated = raw.truncated
|
||||
self.page_token = getattr(raw, "page_token", None)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return repr(self._raw)
|
||||
|
||||
def as_sync(self, table: Any) -> FunctionErrors:
|
||||
return FunctionErrors(self._raw, table, history=self._history)
|
||||
|
||||
def summary(self) -> list[FunctionErrorGroup]:
|
||||
"""Group returned failures by column, exception class, and message.
|
||||
|
||||
Raises when records are incomplete, so sampled counts cannot be mistaken
|
||||
for totals. Narrow the request by column or job, or raise its limit.
|
||||
"""
|
||||
if (getattr(self._raw, "workflow_version", None) or 0) < 1:
|
||||
raise NotImplementedError(
|
||||
"The server does not support the current Function failure workflow"
|
||||
)
|
||||
if (
|
||||
self.truncated
|
||||
or self.fragments
|
||||
or any(
|
||||
record.row_offset is None and record.input is None
|
||||
for record in self.records
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
"Function errors are incomplete; narrow the request or raise limit"
|
||||
)
|
||||
groups: dict[tuple[str, str, str], int] = {}
|
||||
for record in self.records:
|
||||
if record.row_offset is None and record.input is None:
|
||||
continue
|
||||
message = record.error_message
|
||||
if record.input is not None:
|
||||
message = message.split("\nSource input: ", 1)[0].split(
|
||||
"\nFunction input ", 1
|
||||
)[0]
|
||||
key = (record.column, record.error_type, message)
|
||||
groups[key] = groups.get(key, 0) + 1
|
||||
return [
|
||||
FunctionErrorGroup(
|
||||
column=column, error_type=kind, error_message=message, rows_failed=count
|
||||
)
|
||||
for (column, kind, message), count in sorted(groups.items())
|
||||
]
|
||||
|
||||
def _identities(self) -> dict[tuple[str, int], list[Any]]:
|
||||
if (getattr(self._raw, "workflow_version", None) or 0) < 1:
|
||||
raise NotImplementedError(
|
||||
"The server does not support the current Function failure workflow"
|
||||
)
|
||||
if self._history:
|
||||
raise ValueError(
|
||||
"Source-row lookup requires current failures; "
|
||||
"read retained history through records"
|
||||
)
|
||||
if self.truncated or self.fragments:
|
||||
raise ValueError(
|
||||
"Function errors are incomplete; narrow the request or raise limit"
|
||||
)
|
||||
result = {}
|
||||
for record in self.records:
|
||||
if record.input is not None or record.row_offset is None:
|
||||
raise ValueError(
|
||||
"This error names a Function invocation; "
|
||||
"inspect its input source identities"
|
||||
)
|
||||
identity = (
|
||||
record.row_id if record.row_id is not None else record.row_address
|
||||
)
|
||||
if identity is None:
|
||||
raise ValueError("This error has no source row identity")
|
||||
key = ("_rowid" if record.row_id is not None else "_rowaddr", identity)
|
||||
result.setdefault(key, []).append(record)
|
||||
return result
|
||||
|
||||
def _predicate(self, identities: dict[tuple[str, int], list[Any]]) -> str:
|
||||
clauses = []
|
||||
for field in ("_rowid", "_rowaddr"):
|
||||
selected = [identity for (kind, identity) in identities if kind == field]
|
||||
if selected:
|
||||
clauses.append(field + " IN (" + ",".join(map(str, selected)) + ")")
|
||||
return " OR ".join(clauses) if clauses else "false"
|
||||
|
||||
def _join_rows(
|
||||
self, rows: pa.Table, identities: dict[tuple[str, int], list[Any]]
|
||||
) -> pa.Table:
|
||||
matches = []
|
||||
indices = []
|
||||
found = set()
|
||||
for index, (row_id, address) in enumerate(
|
||||
zip(rows.column("_rowid").to_pylist(), rows.column("_rowaddr").to_pylist())
|
||||
):
|
||||
for key in (("_rowid", row_id), ("_rowaddr", address)):
|
||||
for record in identities.get(key, []):
|
||||
found.add(key)
|
||||
indices.append(index)
|
||||
matches.append(record)
|
||||
if found != identities.keys():
|
||||
raise ValueError(
|
||||
"Some failed inputs are no longer addressable in this snapshot; "
|
||||
"refresh the error listing or use a historical snapshot"
|
||||
)
|
||||
rows = rows.take(pa.array(indices, type=pa.int64()))
|
||||
fields = [
|
||||
"column",
|
||||
"error_type",
|
||||
"error_message",
|
||||
"attempts",
|
||||
"function_version",
|
||||
"job_id",
|
||||
"first_seen_at_millis",
|
||||
"last_seen_at_millis",
|
||||
"quarantined",
|
||||
]
|
||||
arrays = [
|
||||
pa.array([getattr(record, field) for record in matches]) for field in fields
|
||||
]
|
||||
if "__function_error" in rows.column_names:
|
||||
raise ValueError("Source columns already contain __function_error")
|
||||
return rows.append_column(
|
||||
"__function_error", pa.StructArray.from_arrays(arrays, names=fields)
|
||||
)
|
||||
|
||||
|
||||
class FunctionErrors(_FunctionErrors):
|
||||
"""Current failures with grouped causes and synchronous source-row lookup."""
|
||||
|
||||
def rows(self, columns: Optional[list[str]] = None) -> pa.Table:
|
||||
"""Return current failing inputs with a ``__function_error`` struct.
|
||||
|
||||
Row IDs come from the error records. The server joins stable identities
|
||||
correctly after compaction; callers need no physical-address arithmetic.
|
||||
"""
|
||||
identities = self._identities()
|
||||
predicate = self._predicate(identities)
|
||||
query = (
|
||||
self._table.search()
|
||||
.where(predicate)
|
||||
.with_row_id(True)
|
||||
.with_row_address()
|
||||
.limit(max(1, len(identities)))
|
||||
)
|
||||
selected = list(self._table.schema.names if columns is None else columns)
|
||||
selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected)
|
||||
query = query.select(selected)
|
||||
return self._join_rows(query.to_arrow(), identities)
|
||||
|
||||
|
||||
class AsyncFunctionErrors(_FunctionErrors):
|
||||
"""Current Function failures returned by an asynchronous table."""
|
||||
|
||||
async def rows(self, columns: Optional[list[str]] = None) -> pa.Table:
|
||||
"""Return current failing inputs with their ``__function_error`` metadata."""
|
||||
identities = self._identities()
|
||||
predicate = self._predicate(identities)
|
||||
query = (
|
||||
self._table.query()
|
||||
.where(predicate)
|
||||
.with_row_id()
|
||||
.with_row_address()
|
||||
.limit(max(1, len(identities)))
|
||||
)
|
||||
selected = list(
|
||||
(await self._table.schema()).names if columns is None else columns
|
||||
)
|
||||
selected.extend(name for name in ("_rowid", "_rowaddr") if name not in selected)
|
||||
query = query.select(selected)
|
||||
return self._join_rows(await query.to_arrow(), identities)
|
||||
|
||||
|
||||
class RefreshColumnResult(_RemoteValue):
|
||||
"""Terminal result of an expression-backed or Function-backed refresh Job.
|
||||
|
||||
@@ -1169,6 +1404,8 @@ class RefreshColumnResult(_RemoteValue):
|
||||
"""Exact table version the refresh read."""
|
||||
|
||||
published_version: Optional[_UInt64] = None
|
||||
error_groups: tuple[FunctionErrorGroup, ...] = ()
|
||||
error_groups_truncated: bool = False
|
||||
"""Table version made visible by the refresh, when one was published."""
|
||||
|
||||
@property
|
||||
@@ -1898,6 +2135,17 @@ def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType]
|
||||
_DYNAMIC_NAMESPACE_ACCESS = frozenset(
|
||||
{"globals", "locals", "vars", "eval", "exec", "compile", "__import__"}
|
||||
)
|
||||
# Static diagnostic operations the packager can reconstruct. Anything else that
|
||||
# reaches through a namespace-access module remains unrepresentable.
|
||||
_APPROVED_NAMESPACE_ATTRIBUTES = {
|
||||
"sys": frozenset({"stderr", "version_info"}),
|
||||
"importlib.metadata": frozenset({"version"}),
|
||||
}
|
||||
_APPROVED_NAMESPACE_OPERATIONS = (
|
||||
"sys.stderr",
|
||||
"sys.version_info",
|
||||
"importlib.metadata.version",
|
||||
)
|
||||
# Modules that hand out namespaces (`sys.modules`, `builtins`, importers,
|
||||
# introspection). The artifact's module namespace holds only the names it was
|
||||
# packaged with, so reaching around it cannot be represented.
|
||||
@@ -1912,28 +2160,170 @@ _NAMESPACE_HELPER_HINT = (
|
||||
)
|
||||
|
||||
|
||||
_APPROVED_NAMESPACE_HINT = (
|
||||
"The supported diagnostic operations are "
|
||||
+ ", ".join(_APPROVED_NAMESPACE_OPERATIONS)
|
||||
+ ". "
|
||||
)
|
||||
|
||||
|
||||
def _namespace_operation_error(operations: Sequence[str]) -> ValueError:
|
||||
label = operations[0] if len(operations) == 1 else list(operations)
|
||||
return ValueError(
|
||||
f"@function cannot package namespace operation {label!r}. "
|
||||
"The artifact's module namespace holds only the names it was packaged "
|
||||
"with, so references that reach around it cannot be represented. "
|
||||
+ _APPROVED_NAMESPACE_HINT
|
||||
+ _NAMESPACE_HELPER_HINT
|
||||
)
|
||||
|
||||
|
||||
def _namespace_import_error(modules: Sequence[str]) -> ValueError:
|
||||
return ValueError(
|
||||
f"@function cannot package imports from namespace-access modules: {modules!r}. "
|
||||
f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) "
|
||||
"are blocked because they can access names outside the packaged "
|
||||
"Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT
|
||||
"Function's reconstructed module namespace. "
|
||||
+ _APPROVED_NAMESPACE_HINT
|
||||
+ _NAMESPACE_HELPER_HINT
|
||||
)
|
||||
|
||||
|
||||
def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]:
|
||||
found: set[str] = set()
|
||||
def _namespace_import_bindings(
|
||||
definition: Union[ast.FunctionDef, ast.ClassDef],
|
||||
) -> tuple[dict[str, frozenset[str]], list[str], list[str]]:
|
||||
"""Return approved diagnostic bindings and rejected imports.
|
||||
|
||||
A binding maps the local name an import creates to the attribute paths
|
||||
that may be read through it. Rejected modules and operations are kept
|
||||
separate so each error names the relevant rule.
|
||||
"""
|
||||
bindings: dict[str, frozenset[str]] = {}
|
||||
blocked_modules: set[str] = set()
|
||||
blocked_operations: set[str] = set()
|
||||
for node in ast.walk(definition):
|
||||
if isinstance(node, ast.Import):
|
||||
found.update(
|
||||
alias.name
|
||||
for alias in node.names
|
||||
if alias.name.split(".")[0] in _NAMESPACE_MODULES
|
||||
)
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
if node.module.split(".")[0] in _NAMESPACE_MODULES:
|
||||
found.add(node.module)
|
||||
return sorted(found)
|
||||
for alias in node.names:
|
||||
root = alias.name.split(".")[0]
|
||||
if root not in _NAMESPACE_MODULES:
|
||||
continue
|
||||
attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(alias.name)
|
||||
if attributes is None:
|
||||
blocked_modules.add(alias.name)
|
||||
continue
|
||||
if alias.asname:
|
||||
name = alias.asname
|
||||
bases = frozenset(f"{name}.{attribute}" for attribute in attributes)
|
||||
else:
|
||||
name = root
|
||||
module = alias.name if "." in alias.name else name
|
||||
bases = frozenset(
|
||||
f"{module}.{attribute}" for attribute in attributes
|
||||
)
|
||||
bindings[name] = bindings.get(name, frozenset()) | bases
|
||||
elif (
|
||||
isinstance(node, ast.ImportFrom)
|
||||
and node.level == 0
|
||||
and node.module
|
||||
and node.module.split(".")[0] in _NAMESPACE_MODULES
|
||||
):
|
||||
if node.module == "importlib":
|
||||
for alias in node.names:
|
||||
if alias.name == "metadata":
|
||||
name = alias.asname or "metadata"
|
||||
bindings[name] = bindings.get(name, frozenset()) | frozenset(
|
||||
{f"{name}.version"}
|
||||
)
|
||||
else:
|
||||
blocked_modules.add("importlib")
|
||||
continue
|
||||
attributes = _APPROVED_NAMESPACE_ATTRIBUTES.get(node.module)
|
||||
if attributes is None:
|
||||
blocked_modules.add(node.module)
|
||||
continue
|
||||
for alias in node.names:
|
||||
if alias.name in attributes:
|
||||
name = alias.asname or alias.name
|
||||
bindings[name] = bindings.get(name, frozenset()) | frozenset({name})
|
||||
else:
|
||||
blocked_operations.add(f"{node.module}.{alias.name}")
|
||||
return bindings, sorted(blocked_modules), sorted(blocked_operations)
|
||||
|
||||
|
||||
def _namespace_binding_errors(
|
||||
definition: Union[ast.FunctionDef, ast.ClassDef],
|
||||
bindings: Mapping[str, frozenset[str]],
|
||||
) -> list[str]:
|
||||
"""Operations that read a diagnostic binding outside its approved paths."""
|
||||
if not bindings:
|
||||
return []
|
||||
parents: dict[ast.AST, ast.AST] = {}
|
||||
for node in ast.walk(definition):
|
||||
for child in ast.iter_child_nodes(node):
|
||||
parents[child] = node
|
||||
invalid: set[str] = set()
|
||||
for node in ast.walk(definition):
|
||||
if not isinstance(node, ast.Name):
|
||||
continue
|
||||
allowed = bindings.get(node.id)
|
||||
if allowed is None:
|
||||
continue
|
||||
if not isinstance(node.ctx, ast.Load):
|
||||
invalid.add(node.id)
|
||||
continue
|
||||
path = node.id
|
||||
current: ast.AST = node
|
||||
while True:
|
||||
parent = parents.get(current)
|
||||
if isinstance(parent, ast.Attribute) and parent.value is current:
|
||||
path = f"{path}.{parent.attr}"
|
||||
current = parent
|
||||
continue
|
||||
break
|
||||
if not any(path == base or path.startswith(f"{base}.") for base in allowed):
|
||||
invalid.add(path)
|
||||
continue
|
||||
if any(part.startswith("__") for part in path.split(".")[1:]):
|
||||
invalid.add(path)
|
||||
return sorted(invalid)
|
||||
|
||||
|
||||
def _approved_global_namespace_binding(
|
||||
definition: Optional[Union[ast.FunctionDef, ast.ClassDef]],
|
||||
name: str,
|
||||
value: Any,
|
||||
) -> Optional[str]:
|
||||
"""The artifact import for an approved diagnostic global, if any."""
|
||||
if definition is None:
|
||||
return None
|
||||
if isinstance(value, types.ModuleType):
|
||||
if value is sys:
|
||||
bases = frozenset({f"{name}.stderr", f"{name}.version_info"})
|
||||
line = f"import sys as {name}"
|
||||
elif value is importlib.metadata:
|
||||
bases = frozenset({f"{name}.version"})
|
||||
line = f"import importlib.metadata as {name}"
|
||||
elif value is importlib and name == "importlib":
|
||||
# ``import importlib.metadata`` binds the top-level package name.
|
||||
bases = frozenset({"importlib.metadata.version"})
|
||||
line = "import importlib.metadata"
|
||||
else:
|
||||
return None
|
||||
elif value is sys.stderr:
|
||||
bases = frozenset({name})
|
||||
line = f"from sys import stderr as {name}"
|
||||
elif value is sys.version_info:
|
||||
bases = frozenset({name})
|
||||
line = f"from sys import version_info as {name}"
|
||||
elif value is importlib.metadata.version:
|
||||
bases = frozenset({name})
|
||||
line = f"from importlib.metadata import version as {name}"
|
||||
else:
|
||||
return None
|
||||
invalid = _namespace_binding_errors(definition, {name: bases})
|
||||
if invalid:
|
||||
raise _namespace_operation_error(invalid)
|
||||
return line
|
||||
|
||||
|
||||
def _module_references(module_source: str) -> set[str]:
|
||||
@@ -2246,14 +2636,21 @@ class _SourcePackager:
|
||||
"Function's reconstructed module namespace. Reference dependencies "
|
||||
"explicitly. " + _NAMESPACE_HELPER_HINT
|
||||
)
|
||||
namespace_imports = _namespace_imports(definition)
|
||||
if namespace_imports:
|
||||
raise _namespace_import_error(namespace_imports)
|
||||
namespace_bindings, blocked_modules, blocked_operations = (
|
||||
_namespace_import_bindings(definition)
|
||||
)
|
||||
if blocked_modules:
|
||||
raise _namespace_import_error(blocked_modules)
|
||||
if blocked_operations:
|
||||
raise _namespace_operation_error(blocked_operations)
|
||||
invalid_operations = _namespace_binding_errors(definition, namespace_bindings)
|
||||
if invalid_operations:
|
||||
raise _namespace_operation_error(invalid_operations)
|
||||
self._warn_unshipped_direct_imports(definition)
|
||||
self._packaged.add(id(target))
|
||||
self._claim(target.__name__, ("definition", id(target)))
|
||||
if reader_name is not None:
|
||||
self._bind(reader_name, BlobReader)
|
||||
self._bind(reader_name, BlobReader, definition=definition)
|
||||
unresolved = []
|
||||
for name in sorted(references):
|
||||
if name == target.__name__:
|
||||
@@ -2265,7 +2662,7 @@ class _SourcePackager:
|
||||
)
|
||||
continue
|
||||
if name in namespace:
|
||||
self._bind(name, namespace[name])
|
||||
self._bind(name, namespace[name], definition=definition)
|
||||
elif not hasattr(builtins, name):
|
||||
unresolved.append(name)
|
||||
if unresolved:
|
||||
@@ -2320,7 +2717,13 @@ class _SourcePackager:
|
||||
"name to different values"
|
||||
)
|
||||
|
||||
def _bind(self, name: str, value: Any) -> None:
|
||||
def _bind(
|
||||
self,
|
||||
name: str,
|
||||
value: Any,
|
||||
*,
|
||||
definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None,
|
||||
) -> None:
|
||||
if _packaged_by_source(value):
|
||||
if value.__name__ != name:
|
||||
raise ValueError(
|
||||
@@ -2331,14 +2734,23 @@ class _SourcePackager:
|
||||
self._definitions.append(self._definition(value, entry=False))
|
||||
self._claim(name, ("definition", id(value)))
|
||||
return
|
||||
line = self._global_source(name, value)
|
||||
line = self._global_source(name, value, definition=definition)
|
||||
self._claim(name, line)
|
||||
self._imports[name] = line
|
||||
|
||||
def _global_source(self, name: str, value: Any) -> str:
|
||||
def _global_source(
|
||||
self,
|
||||
name: str,
|
||||
value: Any,
|
||||
*,
|
||||
definition: Optional[Union[ast.FunctionDef, ast.ClassDef]] = None,
|
||||
) -> str:
|
||||
"""One module-level line that rebinds `name` to `value` in the artifact:
|
||||
an import for modules and importable classes/functions, a captured
|
||||
copy otherwise."""
|
||||
approved = _approved_global_namespace_binding(definition, name, value)
|
||||
if approved is not None:
|
||||
return approved
|
||||
if value is BlobReader:
|
||||
return f"from lance_blob import BlobReader as {name}"
|
||||
if isinstance(value, types.ModuleType):
|
||||
@@ -2790,6 +3202,12 @@ class FunctionDefinition:
|
||||
remote application or build the declared remote runtime, and it does not
|
||||
need the private implementation attribute.
|
||||
|
||||
Arguments to this call are Python and Arrow values. An
|
||||
[Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column
|
||||
binding that only a registered
|
||||
[FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this
|
||||
call rejects it with ``TypeError`` instead of running the callable.
|
||||
|
||||
Remote execution adapts the callable to the internal Arrow batch ABI
|
||||
described by the registration artifact. By default it invokes the callable
|
||||
once per row. A callable whose parameters are all annotated as
|
||||
@@ -2814,8 +3232,12 @@ class FunctionDefinition:
|
||||
max_concurrency: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
gpu: bool = False,
|
||||
gpu: Optional[bool] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
conda: tuple[str, ...] = (),
|
||||
conda_channels: tuple[str, ...] = (),
|
||||
apt: tuple[str, ...] = (),
|
||||
@@ -2836,11 +3258,9 @@ class FunctionDefinition:
|
||||
if conda_channels and not conda:
|
||||
raise ValueError("conda_channels requires conda packages")
|
||||
_validate_package_requirements("conda" if conda else "pip", conda or pip)
|
||||
gpu_marker = _normalize_gpu_marker(gpu)
|
||||
if gpu_class is not None:
|
||||
_validate_gpu_class_name(gpu_class)
|
||||
if gpu_marker is None:
|
||||
raise ValueError("gpu_class requires gpu=True")
|
||||
gpu_marker, gpu_class, gpus_per_worker = _normalize_gpu_request(
|
||||
gpu, gpu_class, gpu_count
|
||||
)
|
||||
packages = tuple(sorted(set(conda if conda else pip)))
|
||||
system_packages = tuple(sorted(set(apt)))
|
||||
if any(
|
||||
@@ -2958,6 +3378,7 @@ class FunctionDefinition:
|
||||
env=environment,
|
||||
gpu=gpu_marker,
|
||||
gpu_class=gpu_class,
|
||||
gpus_per_worker=gpus_per_worker,
|
||||
)
|
||||
self._function = function
|
||||
self._request = FunctionRegistrationRequest(
|
||||
@@ -2979,6 +3400,9 @@ class FunctionDefinition:
|
||||
runtime=runtime,
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
retry_policy=retry_policy,
|
||||
models=models,
|
||||
@@ -3059,6 +3483,16 @@ class FunctionDefinition:
|
||||
return self._request._copy(update={"secret_bindings": resolved})
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
from lancedb.expr import Expr
|
||||
|
||||
if any(isinstance(value, Expr) for value in (*args, *kwargs.values())):
|
||||
raise TypeError(
|
||||
"a FunctionDefinition runs locally on Python and Arrow values; "
|
||||
"an Expr input binds only on a registered FunctionVersion. "
|
||||
"Register the definition with create_function or "
|
||||
"create_function_async, then bind col(...) on the returned "
|
||||
"version."
|
||||
)
|
||||
return self._function(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -3080,8 +3514,12 @@ def function(
|
||||
max_concurrency: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
gpu: bool = False,
|
||||
gpu: Optional[bool] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
conda: tuple[str, ...] | list[str] = (),
|
||||
conda_channels: tuple[str, ...] | list[str] = (),
|
||||
apt: tuple[str, ...] | list[str] = (),
|
||||
@@ -3104,8 +3542,12 @@ def function(
|
||||
max_concurrency: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
gpu: bool = False,
|
||||
gpu: Optional[bool] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
conda: tuple[str, ...] | list[str] = (),
|
||||
conda_channels: tuple[str, ...] | list[str] = (),
|
||||
apt: tuple[str, ...] | list[str] = (),
|
||||
@@ -3149,7 +3591,12 @@ def function(
|
||||
it takes one ``pyarrow.RecordBatch``. These batch annotations require both
|
||||
``input_schema`` and ``output_schema`` explicitly: the annotations do not
|
||||
specify Arrow element types or fields. This also applies to a class's
|
||||
``__call__`` method. A decorated class is the same callable with state:
|
||||
``__call__`` method. Each ``input_schema`` field names one parameter, so
|
||||
several input columns take one ``pyarrow.Array`` parameter each, while a
|
||||
single ``pyarrow.RecordBatch`` parameter binds one input column and
|
||||
receives it as a batch. The
|
||||
[Function authoring guide](https://lancedb.com/docs/curation/create-function#batch)
|
||||
has the worked examples. A decorated class is the same callable with state:
|
||||
each remote instance calls ``__init__`` once, calls
|
||||
``__call__`` for every row or batch of every input it processes, and calls
|
||||
``close()``, if defined, once when it retires. Load models, open clients,
|
||||
@@ -3224,20 +3671,25 @@ def function(
|
||||
values, such as instances of your own classes, inside the function or
|
||||
class body as well.
|
||||
|
||||
**Namespace restrictions.** The packaged source cannot import ``sys``,
|
||||
**Namespace restrictions.** The packaged source may use three static
|
||||
diagnostic operations: ``sys.stderr``, ``sys.version_info``, and
|
||||
``importlib.metadata.version``. Direct imports, ``from`` imports, and
|
||||
aliases are treated the same way, whether the import appears inside the
|
||||
function or class body or at module level. Any other import of ``sys``,
|
||||
``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``,
|
||||
including submodules such as ``ctypes.util`` and ``importlib.metadata``.
|
||||
Referencing a module-level alias for one of these modules is also rejected.
|
||||
References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``,
|
||||
``compile``, or ``__import__`` are rejected as dynamic namespace access.
|
||||
These restrictions are conservative: even ordinary uses such as
|
||||
``ctypes.util.find_library`` or ``sys.version`` are blocked because these
|
||||
modules can reach names outside the reconstructed Function namespace.
|
||||
Move such code into an importable helper module supplied with ``code=``,
|
||||
``pip=``, or ``conda=``, then import and call the helper from the Function.
|
||||
Helpers imported normally keep their own module namespace; these checks do
|
||||
not scan their bodies. A helper defined in ``__main__`` is packaged by source
|
||||
and is subject to the same checks.
|
||||
including submodules such as ``ctypes.util``, ``importlib.resources``, and
|
||||
``importlib.import_module``, is rejected. Referencing a module-level alias
|
||||
for an unapproved module or operation is also rejected. References to
|
||||
``globals``, ``locals``, ``vars``, ``eval``, ``exec``, ``compile``, or
|
||||
``__import__`` are rejected as dynamic namespace access. These
|
||||
restrictions are conservative: even ordinary uses such as
|
||||
``ctypes.util.find_library`` or ``sys.version`` remain blocked because
|
||||
these modules can reach names outside the reconstructed Function
|
||||
namespace. Move such code into an importable helper module supplied with
|
||||
``code=``, ``pip=``, or ``conda=``, then import and call the helper from
|
||||
the Function. Helpers imported normally keep their own module namespace;
|
||||
these checks do not scan their bodies. A helper defined in ``__main__`` is
|
||||
packaged by source and is subject to the same checks.
|
||||
|
||||
Changing any packaged source, including a module in ``code``, produces a
|
||||
new Function version; the environment built from ``pip`` or ``conda`` is
|
||||
@@ -3306,22 +3758,37 @@ def function(
|
||||
Positive, finite deadline in seconds for each Python call: one row for
|
||||
scalar Functions and one batch for vectorized Functions. This does not
|
||||
govern class initialization. When omitted, the service applies its
|
||||
default per-call budget.
|
||||
default per-call budget, currently 300 seconds on Enterprise builds.
|
||||
Set it for a GPU Function whose longest call can exceed that budget.
|
||||
Enterprise builds that require an explicit GPU deadline reject a
|
||||
refresh when neither the definition nor the refresh request sets one;
|
||||
a refresh value overrides the definition.
|
||||
retry_policy : FunctionRetryPolicy, optional
|
||||
Retry selected failed calls inside the Function, with bounded attempts
|
||||
and backoff. A refresh may override this default. Retrying a partial
|
||||
call must be safe; completed calls are not repeated. For batch Functions,
|
||||
skip after exhaustion applies to the whole failed call.
|
||||
gpu : bool, default False
|
||||
Whether every remote execution requires a GPU. The execution platform
|
||||
selects one compatible GPU for each worker. The requirement is part of
|
||||
the immutable Function version.
|
||||
gpu : bool, optional
|
||||
Enable GPU execution. Defaults to CPU execution.
|
||||
gpu_class : str, optional
|
||||
Operator-defined GPU class for every execution of this Function, such
|
||||
as ``"a10g"`` or ``"h100"``. Requires ``gpu=True`` and follows the
|
||||
lowercase 63-character DNS-label rule. The class is part of the
|
||||
immutable Function version; per-refresh aggregate GPU budgets are
|
||||
selected through ``refresh_column`` instead of registration.
|
||||
Select an operator-configured GPU pool, such as ``"h100"``.
|
||||
Requires ``gpu=True``. Omitting it is equivalent to ``"any"`` and accepts
|
||||
any eligible configured GPU class. Use ``"default"`` to select the
|
||||
deployment's default pool explicitly.
|
||||
gpu_count : int, optional
|
||||
Default GPUs allocated together to each Function worker. Requires ``gpu=True``
|
||||
and defaults to one. Column/MV creation and refresh can override it.
|
||||
Must be a positive integer. Refresh
|
||||
``total_gpu_count`` limits the total GPUs across the worker fleet.
|
||||
total_cpu_millis : int, optional
|
||||
Default total CPU budget for an execution, in millicores (1000 = one
|
||||
core). A column/MV declaration or refresh may override this value.
|
||||
total_memory_bytes : int, optional
|
||||
Default total memory budget for an execution, in bytes.
|
||||
total_gpu_count : int, optional
|
||||
Default total GPU budget across an execution's workers. This is
|
||||
separate from ``gpu_count``, which allocates GPUs to each worker.
|
||||
MVs add the defaults of their distinct pinned Function versions.
|
||||
code : sequence of module, optional
|
||||
Top-level modules or packages shipped with the Function and importable
|
||||
by their own names. Package resources, including binary data and
|
||||
@@ -3365,13 +3832,13 @@ def function(
|
||||
... return value
|
||||
>>> batch_identity(pa.array([1, 2, 3])).to_pylist()
|
||||
[1, 2, 3]
|
||||
>>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
|
||||
>>> @function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2)
|
||||
... def gpu_score(value: int) -> int:
|
||||
... return value * 2
|
||||
>>> gpu_score.registration_request.runtime.gpu
|
||||
True
|
||||
>>> gpu_score.registration_request.runtime.gpu_class
|
||||
'a10g'
|
||||
>>> gpu_score.registration_request.runtime.gpus_per_worker
|
||||
2
|
||||
>>> @function
|
||||
... class scale:
|
||||
... def __init__(self, factor: float, offset: float = 0.0):
|
||||
@@ -3406,7 +3873,10 @@ def function(
|
||||
remote environment, resolve Secrets, or run the remote Arrow adapter or
|
||||
sandbox. A registered ``FunctionVersion`` call is different: it binds
|
||||
``col(...)`` inputs and returns a remote
|
||||
[FunctionApplication][lancedb.functions.FunctionApplication].
|
||||
[FunctionApplication][lancedb.functions.FunctionApplication]. Passing an
|
||||
[Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the
|
||||
callable runs, because a column reference binds only on a registered
|
||||
version.
|
||||
|
||||
```python
|
||||
scaled = scale(factor=2.0)
|
||||
@@ -3445,6 +3915,10 @@ def function(
|
||||
retry_policy=retry_policy,
|
||||
gpu=gpu,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
conda=tuple(conda),
|
||||
conda_channels=tuple(conda_channels),
|
||||
apt=tuple(apt),
|
||||
@@ -3487,12 +3961,21 @@ __all__ = [
|
||||
"ResolvedEnvironmentProvenance",
|
||||
"ResolvedPackage",
|
||||
"RefreshColumnResult",
|
||||
"FunctionErrors",
|
||||
"AsyncFunctionErrors",
|
||||
"FunctionErrorGroup",
|
||||
"FunctionProvenance",
|
||||
"FunctionValueProvenance",
|
||||
"FunctionDefinition",
|
||||
]
|
||||
|
||||
|
||||
def udf(*args: Any, **kwargs: Any) -> Any:
|
||||
"""Deprecated alias of :func:`function`."""
|
||||
"""Deprecated alias of :func:`function`.
|
||||
|
||||
Accepts the same options, including ``row_timeout_seconds``. See
|
||||
:func:`function` for GPU deadline guidance.
|
||||
"""
|
||||
warnings.warn(
|
||||
"lancedb.udf is deprecated; use lancedb.function",
|
||||
DeprecationWarning,
|
||||
|
||||
@@ -147,6 +147,45 @@ class ZoneMap:
|
||||
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.
|
||||
@@ -1001,4 +1040,5 @@ __all__ = [
|
||||
"LabelList",
|
||||
"Fm",
|
||||
"NGram",
|
||||
"RTree",
|
||||
]
|
||||
|
||||
+684
-72
File diff suppressed because it is too large
Load Diff
@@ -17,9 +17,9 @@ 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
|
||||
from .resources import _resource_options
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pyarrow as pa
|
||||
@@ -167,31 +167,16 @@ 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")
|
||||
def _refresh_execution_options(
|
||||
total_cpu_millis, total_memory_bytes, total_gpu_count, gpu_class, gpu_count=None
|
||||
):
|
||||
values = _resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
return {name: value for name, value in values.items() if value is not None}
|
||||
|
||||
|
||||
@@ -228,10 +213,11 @@ class AsyncMaterializedView:
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> "RefreshMaterializedViewResult":
|
||||
"""Recompute the view from its source.
|
||||
|
||||
@@ -240,11 +226,14 @@ 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.
|
||||
``total_cpu_millis`` (1000 = one core), ``total_memory_bytes``, and
|
||||
``total_gpu_count`` cap aggregate resources for this execution,
|
||||
including its Function processes. Each resource may be overridden
|
||||
independently. Unset values inherit the view defaults, then the sum
|
||||
across distinct pinned Functions, then deployment defaults. 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.
|
||||
|
||||
@@ -256,7 +245,11 @@ class AsyncMaterializedView:
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -265,10 +258,11 @@ class AsyncMaterializedView:
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> "AsyncJob[RefreshMaterializedViewResult]":
|
||||
"""Submit a refresh and return its job without waiting.
|
||||
|
||||
@@ -289,7 +283,11 @@ class AsyncMaterializedView:
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
),
|
||||
RefreshMaterializedViewResult.from_json,
|
||||
@@ -326,10 +324,11 @@ class MaterializedView:
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> "RefreshMaterializedViewResult":
|
||||
"""Recompute the view from its source. See
|
||||
[AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]."""
|
||||
@@ -338,7 +337,11 @@ class MaterializedView:
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -348,10 +351,11 @@ class MaterializedView:
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> "Job[RefreshMaterializedViewResult]":
|
||||
"""Submit a refresh and return its job without waiting.
|
||||
|
||||
@@ -364,7 +368,11 @@ class MaterializedView:
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -509,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.
|
||||
|
||||
@@ -584,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
|
||||
),
|
||||
}
|
||||
@@ -640,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 = []
|
||||
@@ -661,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,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -668,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,
|
||||
@@ -706,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,
|
||||
@@ -730,6 +738,11 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> "MaterializedView":
|
||||
"""Define a materialized view over a table in the root namespace.
|
||||
@@ -749,7 +762,12 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
exist_ok=exist_ok,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
).name
|
||||
)
|
||||
@@ -768,6 +786,11 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> Job[None]:
|
||||
job = LOOP.run(
|
||||
@@ -781,7 +804,12 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
exist_ok=exist_ok,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -1132,6 +1160,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,
|
||||
@@ -1205,7 +1234,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.
|
||||
|
||||
@@ -1302,6 +1333,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:
|
||||
@@ -1323,6 +1356,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,
|
||||
@@ -1381,6 +1416,11 @@ class AsyncLanceNamespaceDBConnection:
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> "AsyncMaterializedView":
|
||||
"""Define a materialized view over a table in the root namespace."""
|
||||
@@ -1394,7 +1434,12 @@ class AsyncLanceNamespaceDBConnection:
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
exist_ok=exist_ok,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
# Reopen through the namespace so the view's table carries the
|
||||
# namespace client and pushdown configuration a bare inner table lacks.
|
||||
@@ -1412,6 +1457,11 @@ class AsyncLanceNamespaceDBConnection:
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
exist_ok: bool = False,
|
||||
) -> AsyncJob[None]:
|
||||
"""Submit materialized-view creation and return its job."""
|
||||
@@ -1425,7 +1475,12 @@ class AsyncLanceNamespaceDBConnection:
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
exist_ok=exist_ok,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
|
||||
async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
|
||||
@@ -1717,12 +1772,18 @@ class AsyncLanceNamespaceDBConnection:
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> AsyncRecordBatchReader:
|
||||
"""Execute SQL when supported by the underlying connection."""
|
||||
return await self._inner.execute_query(
|
||||
query,
|
||||
default_namespace_path=default_namespace_path,
|
||||
parameters=parameters,
|
||||
timeout=timeout,
|
||||
read_timeout=read_timeout,
|
||||
cancel_on_drop=cancel_on_drop,
|
||||
)
|
||||
|
||||
async def execute_query_async(
|
||||
@@ -1731,6 +1792,9 @@ class AsyncLanceNamespaceDBConnection:
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> AsyncSqlQuery:
|
||||
"""Start executing SQL when supported by the underlying connection.
|
||||
|
||||
@@ -1740,6 +1804,9 @@ class AsyncLanceNamespaceDBConnection:
|
||||
query,
|
||||
default_namespace_path=default_namespace_path,
|
||||
parameters=parameters,
|
||||
timeout=timeout,
|
||||
read_timeout=read_timeout,
|
||||
cancel_on_drop=cancel_on_drop,
|
||||
)
|
||||
|
||||
async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription:
|
||||
@@ -1808,7 +1875,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.
|
||||
|
||||
@@ -1899,7 +1968,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.
|
||||
|
||||
|
||||
@@ -8,14 +8,35 @@ import os
|
||||
from deprecation import deprecated
|
||||
import pyarrow as pa
|
||||
|
||||
from ._lancedb import Connection as NativeConnection
|
||||
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,
|
||||
get_uri_scheme,
|
||||
)
|
||||
from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lancedb.dependencies import pandas as pd, numpy as np, polars as pl
|
||||
from .db import DBConnection
|
||||
|
||||
|
||||
def _native_connection(db: Any) -> Any:
|
||||
"""Return the native connection wrapped by a sync or async connection."""
|
||||
async_connection = getattr(db, "_conn", None)
|
||||
if async_connection is not None:
|
||||
return _native_connection(async_connection)
|
||||
inner = getattr(db, "_inner", None)
|
||||
if inner is not None:
|
||||
return _native_connection(inner)
|
||||
if isinstance(db, NativeConnection):
|
||||
return db
|
||||
raise TypeError("db must be a LanceDB connection")
|
||||
|
||||
|
||||
class PermutationBuilder:
|
||||
@@ -38,7 +59,9 @@ class PermutationBuilder:
|
||||
be referenced by name in the future. If names are not provided then they can only
|
||||
be referenced by their ordinal index. There is no requirement to name every split.
|
||||
|
||||
The permutation is stored in memory and will be lost when the program exits.
|
||||
The permutation is stored in memory and will be lost when the program exits,
|
||||
unless [persist][lancedb.permutation.PermutationBuilder.persist] is called before
|
||||
[execute][lancedb.permutation.PermutationBuilder.execute].
|
||||
"""
|
||||
|
||||
def __init__(self, table: Table):
|
||||
@@ -51,6 +74,9 @@ class PermutationBuilder:
|
||||
Tables with an RTE write spec are rejected: unflushed rows have no row id.
|
||||
"""
|
||||
self._async = async_permutation_builder(table)
|
||||
self._persist_connection: Optional[Any] = None
|
||||
self._persist_table_name: Optional[str] = None
|
||||
self._persist_namespace_path: list[str] = []
|
||||
|
||||
def split_random(
|
||||
self,
|
||||
@@ -257,6 +283,80 @@ class PermutationBuilder:
|
||||
self._async.filter(filter)
|
||||
return self
|
||||
|
||||
def persist(
|
||||
self,
|
||||
db: "DBConnection",
|
||||
table_name: str,
|
||||
*,
|
||||
namespace_path: Optional[list[str]] = None,
|
||||
mode: Literal["create", "overwrite"] = "create",
|
||||
) -> "PermutationBuilder":
|
||||
"""
|
||||
Store the permutation table in an embedded database.
|
||||
|
||||
The base table can be Embedded or Enterprise; this connection is only the
|
||||
plan destination. Persisting a plan makes the same split available to
|
||||
another process or another machine with access to the destination storage.
|
||||
The plan is an ordinary LanceDB table containing row ids and split ids; it
|
||||
can be opened with [open_table][lancedb.db.DBConnection.open_table] and
|
||||
passed to
|
||||
[Permutation.from_tables][lancedb.permutation.Permutation.from_tables].
|
||||
The table returned by ``execute`` keeps the destination connection and
|
||||
namespace context, so it can be pickled and reopened directly.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
db: DBConnection
|
||||
An embedded LanceDB connection for the plan destination. Local files
|
||||
and object storage are supported. The base table may be Embedded or
|
||||
Enterprise; persisting the plan itself to Enterprise is not supported
|
||||
yet.
|
||||
table_name: str
|
||||
The name of the permutation table to create.
|
||||
namespace_path: list[str], optional
|
||||
The namespace to create the table in. The default is the root
|
||||
namespace.
|
||||
mode: {"create", "overwrite"}, default "create"
|
||||
``create`` fails if the destination table already exists.
|
||||
``overwrite`` writes a new version of the table. Readers that already
|
||||
opened the previous version keep reading that snapshot.
|
||||
|
||||
Returns
|
||||
-------
|
||||
PermutationBuilder
|
||||
This builder, so ``persist`` can be chained with the split, filter,
|
||||
and execute methods.
|
||||
"""
|
||||
if mode not in ("create", "overwrite"):
|
||||
raise ValueError(f"Invalid mode {mode!r}; expected 'create' or 'overwrite'")
|
||||
|
||||
uri = getattr(db, "uri", None)
|
||||
if uri is None:
|
||||
raise TypeError("db must be a LanceDB connection")
|
||||
if get_uri_scheme(str(uri)) == "db":
|
||||
raise NotImplementedError(
|
||||
"Permutation persistence is not supported for LanceDB Enterprise "
|
||||
"connections yet; reproducible Enterprise plan ordering requires "
|
||||
"deterministic remote row ordering."
|
||||
)
|
||||
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
elif not isinstance(namespace_path, (list, tuple)):
|
||||
raise TypeError("namespace_path must be a list of strings or None")
|
||||
|
||||
namespace_path = list(namespace_path)
|
||||
self._async.persist(
|
||||
_native_connection(db),
|
||||
table_name,
|
||||
namespace_path=namespace_path,
|
||||
mode=mode,
|
||||
)
|
||||
self._persist_connection = db
|
||||
self._persist_table_name = table_name
|
||||
self._persist_namespace_path = namespace_path
|
||||
return self
|
||||
|
||||
def execute(self) -> LanceTable:
|
||||
"""
|
||||
Execute the configuration and create the permutation table.
|
||||
@@ -264,7 +364,14 @@ class PermutationBuilder:
|
||||
|
||||
async def do_execute():
|
||||
inner_tbl = await self._async.execute()
|
||||
return await LanceTable.from_inner(inner_tbl)
|
||||
if self._persist_connection is None:
|
||||
return await LanceTable.from_inner(inner_tbl)
|
||||
return await LanceTable.from_inner(
|
||||
inner_tbl,
|
||||
connection=self._persist_connection,
|
||||
name=self._persist_table_name,
|
||||
namespace_path=self._persist_namespace_path,
|
||||
)
|
||||
|
||||
return LOOP.run(do_execute())
|
||||
|
||||
@@ -406,10 +513,17 @@ class Transforms:
|
||||
DEFAULT_BATCH_SIZE = 100
|
||||
|
||||
|
||||
def _is_persisted_plan(table: Table) -> bool:
|
||||
"""Whether a permutation table lives in reopenable storage rather than memory."""
|
||||
return isinstance(table, LanceTable) and not table._conn.uri.startswith("memory://")
|
||||
|
||||
|
||||
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 +532,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 +553,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"])
|
||||
@@ -483,6 +604,9 @@ class Permutation:
|
||||
limit: Optional[int] = None,
|
||||
connection_factory: Optional[Callable[[str], Table]] = None,
|
||||
_reader: Optional[PermutationReader] = None,
|
||||
_plan_metadata: Optional[dict[bytes, bytes]] = None,
|
||||
_plan_version: Optional[int] = None,
|
||||
_plan_branch: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
Internal constructor. Use
|
||||
@@ -499,6 +623,9 @@ class Permutation:
|
||||
self.offset = offset
|
||||
self.limit = limit
|
||||
self.connection_factory = connection_factory
|
||||
self._plan_metadata = _plan_metadata
|
||||
self._plan_version = _plan_version
|
||||
self._plan_branch = _plan_branch
|
||||
if _reader is None:
|
||||
_reader = LOOP.run(self._build_reader())
|
||||
self.reader: PermutationReader = _reader
|
||||
@@ -638,6 +765,17 @@ class Permutation:
|
||||
then the first split will be used.
|
||||
"""
|
||||
assert base_table is not None, "base_table is required"
|
||||
persisted_plan = permutation_table is not None and _is_persisted_plan(
|
||||
permutation_table
|
||||
)
|
||||
if persisted_plan:
|
||||
# Pin before reading metadata or constructing the reader. The caller's
|
||||
# handle may keep tracking latest, but the live reader and pickle must
|
||||
# share one immutable plan snapshot.
|
||||
permutation_table = permutation_table._pin_current_snapshot()
|
||||
plan_metadata = None if permutation_table is not None else {}
|
||||
if permutation_table is not None and (isinstance(split, str) or persisted_plan):
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
if split is not None:
|
||||
if permutation_table is None:
|
||||
raise ValueError(
|
||||
@@ -645,12 +783,7 @@ class Permutation:
|
||||
" because no permutation table is provided"
|
||||
)
|
||||
if isinstance(split, str):
|
||||
if permutation_table.schema.metadata is None:
|
||||
raise ValueError(
|
||||
f"Cannot create a permutation on split `{split}`"
|
||||
" because no split names are defined in the permutation table"
|
||||
)
|
||||
raw = permutation_table.schema.metadata.get(b"split_names")
|
||||
raw = (plan_metadata or {}).get(b"split_names")
|
||||
split_names = raw.decode("utf-8") if raw is not None else None
|
||||
if split_names is None:
|
||||
raise ValueError(
|
||||
@@ -673,6 +806,14 @@ class Permutation:
|
||||
else:
|
||||
split = 0
|
||||
|
||||
plan_version = None
|
||||
plan_branch = None
|
||||
if persisted_plan:
|
||||
# Pin the pickled plan to the snapshot this object was created from,
|
||||
# not what the destination name points at after an overwrite.
|
||||
plan_version = permutation_table.version
|
||||
plan_branch = permutation_table.current_branch()
|
||||
|
||||
async def do_from_tables():
|
||||
reader = await PermutationReader.from_tables(
|
||||
base_table, permutation_table, split
|
||||
@@ -687,6 +828,9 @@ class Permutation:
|
||||
DEFAULT_BATCH_SIZE,
|
||||
Transforms.arrow2python,
|
||||
_reader=reader,
|
||||
_plan_metadata=plan_metadata,
|
||||
_plan_version=plan_version,
|
||||
_plan_branch=plan_branch,
|
||||
)
|
||||
|
||||
return LOOP.run(do_from_tables())
|
||||
@@ -696,18 +840,43 @@ class Permutation:
|
||||
|
||||
The base table is captured either via a user-supplied
|
||||
``connection_factory`` (see [with_connection_factory]) or, as a
|
||||
fallback, by the table's own picklable reopen state. The permutation
|
||||
table is captured as a pyarrow Table (which pickles via Arrow IPC
|
||||
natively). The reader is dropped from the wire format and rebuilt
|
||||
lazily on first use.
|
||||
fallback, by the table's own picklable reopen state. A permutation
|
||||
table in memory is captured as a pyarrow Table (which pickles via Arrow
|
||||
IPC natively). A persisted plan is reopened by reference and pinned to
|
||||
the plan snapshot this object was built from. The reader is dropped
|
||||
from the wire format and rebuilt lazily on first use.
|
||||
"""
|
||||
base_table_state = (
|
||||
None
|
||||
if self.connection_factory is not None
|
||||
else _table_to_pickle_state(self.base_table)
|
||||
)
|
||||
base_is_memory = (
|
||||
base_table_state is not None and base_table_state["kind"] == "memory"
|
||||
)
|
||||
|
||||
permutation_data: Optional[pa.Table] = None
|
||||
if self.permutation_table is not None:
|
||||
permutation_table_state: Optional[dict[str, Any]] = None
|
||||
if (
|
||||
self.permutation_table is not None
|
||||
and _is_persisted_plan(self.permutation_table)
|
||||
and not base_is_memory
|
||||
):
|
||||
plan_state = _table_to_pickle_state(self.permutation_table)
|
||||
# Keep the plan's own branch/version coordinate. A later overwrite
|
||||
# of the destination must not change what this pickle reads.
|
||||
table_state = plan_state["state"]
|
||||
if self._plan_version is not None:
|
||||
table_state["checkout_version"] = self._plan_version
|
||||
# None is the main branch. Restore it explicitly because the
|
||||
# live handle may have moved to another branch since capture.
|
||||
table_state["branch"] = self._plan_branch
|
||||
permutation_table_state = plan_state
|
||||
elif self.permutation_table is not None:
|
||||
permutation_data = self.permutation_table.to_arrow()
|
||||
|
||||
common = {
|
||||
"base_table_name": self.base_table.name,
|
||||
"permutation_data": permutation_data,
|
||||
"split": self.split,
|
||||
"selection": self.selection,
|
||||
"batch_size": self.batch_size,
|
||||
@@ -716,17 +885,13 @@ class Permutation:
|
||||
"limit": self.limit,
|
||||
"connection_factory": self.connection_factory,
|
||||
}
|
||||
|
||||
if self.connection_factory is not None:
|
||||
# The factory carries enough state to recover the base table on
|
||||
# its own; we don't need to capture the URI / storage options /
|
||||
# namespace from the existing connection.
|
||||
return common
|
||||
|
||||
return {
|
||||
**common,
|
||||
"base_table_state": _table_to_pickle_state(self.base_table),
|
||||
}
|
||||
if permutation_table_state is not None:
|
||||
common["permutation_table_state"] = permutation_table_state
|
||||
else:
|
||||
common["permutation_data"] = permutation_data
|
||||
if base_table_state is not None:
|
||||
common["base_table_state"] = base_table_state
|
||||
return common
|
||||
|
||||
def __setstate__(self, state: dict[str, Any]) -> None:
|
||||
from . import connect
|
||||
@@ -758,17 +923,32 @@ class Permutation:
|
||||
)
|
||||
|
||||
permutation_table: Optional[Table] = None
|
||||
permutation_data = state["permutation_data"]
|
||||
if permutation_data is not None:
|
||||
if rebuilt_base:
|
||||
# The base table was materialized from Arrow, so it is a fresh
|
||||
# single-version dataset and the recorded pin cannot resolve on it.
|
||||
permutation_data = _drop_base_version(permutation_data)
|
||||
mem_db = connect("memory://")
|
||||
permutation_table = mem_db.create_table("permutation", permutation_data)
|
||||
plan_metadata: dict[bytes, bytes] = {}
|
||||
plan_version = None
|
||||
plan_branch = None
|
||||
if "permutation_table_state" in state:
|
||||
plan_state = state["permutation_table_state"]
|
||||
permutation_table = _table_from_pickle_state(plan_state)
|
||||
nested_state = plan_state.get("state", {})
|
||||
plan_version = nested_state.get("checkout_version")
|
||||
plan_branch = nested_state.get("branch")
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
else:
|
||||
permutation_data = state.get("permutation_data")
|
||||
if permutation_data is not None:
|
||||
if rebuilt_base:
|
||||
# The base table was materialized from Arrow, so it is a fresh
|
||||
# single-version dataset and the recorded pin cannot resolve on it.
|
||||
permutation_data = _drop_base_version(permutation_data)
|
||||
mem_db = connect("memory://")
|
||||
permutation_table = mem_db.create_table("permutation", permutation_data)
|
||||
plan_metadata = dict(permutation_table.schema.metadata or {})
|
||||
|
||||
self.base_table = base_table
|
||||
self.permutation_table = permutation_table
|
||||
self._plan_metadata = plan_metadata
|
||||
self._plan_version = plan_version
|
||||
self._plan_branch = plan_branch
|
||||
self.split = state["split"]
|
||||
self.selection = state["selection"]
|
||||
self.batch_size = state["batch_size"]
|
||||
@@ -779,6 +959,58 @@ 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 _loaded_plan_metadata(self) -> dict[bytes, bytes]:
|
||||
if self._plan_metadata is None:
|
||||
self._plan_metadata = (
|
||||
dict(self.permutation_table.schema.metadata or {})
|
||||
if self.permutation_table is not None
|
||||
else {}
|
||||
)
|
||||
return self._plan_metadata
|
||||
|
||||
@property
|
||||
def base_version(self) -> Optional[int]:
|
||||
"""The base table version recorded in the plan, or ``None`` for legacy plans.
|
||||
|
||||
This value comes from the plan's schema metadata, so reading it does not
|
||||
query the base table. Version numbers are per-branch; see
|
||||
[base_branch][lancedb.permutation.Permutation.base_branch].
|
||||
"""
|
||||
raw = self._loaded_plan_metadata().get(b"base_version")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as error:
|
||||
raise ValueError(
|
||||
f"Permutation table has an unreadable base_version of {raw!r}"
|
||||
) from error
|
||||
|
||||
@property
|
||||
def base_branch(self) -> Optional[str]:
|
||||
"""The base table branch recorded in the plan, or ``None`` for main.
|
||||
|
||||
Legacy plans recorded no branch and therefore also return ``None``.
|
||||
"""
|
||||
raw = self._loaded_plan_metadata().get(b"base_branch")
|
||||
if raw is None:
|
||||
return None
|
||||
return raw.decode("utf-8")
|
||||
|
||||
def _ensure_open(self) -> None:
|
||||
pid = os.getpid()
|
||||
if self.reader is not None and getattr(self, "_pid", None) == pid:
|
||||
@@ -1008,6 +1240,7 @@ class Permutation:
|
||||
"pandas",
|
||||
"arrow",
|
||||
"torch",
|
||||
"torch_dict",
|
||||
"torch_row",
|
||||
"torch_col",
|
||||
"polars",
|
||||
@@ -1019,28 +1252,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 +1318,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}
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Typed snapshots of on-demand Enterprise Function worker captures."""
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal, Optional
|
||||
|
||||
FunctionProfileKind = Literal["cpu", "gpu", "memory"]
|
||||
FunctionProfileStatus = Literal["pending", "capturing", "complete", "failed"]
|
||||
|
||||
__all__ = ["FunctionProfile", "FunctionProfileKind", "FunctionProfileStatus"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FunctionProfile:
|
||||
"""A capture's identity, current status and artifact retention bounds.
|
||||
|
||||
Retain ``profile_id`` to retrieve the capture through the parent Job,
|
||||
including after its refresh completes. ``status`` and ``error`` describe
|
||||
the capture independently of the parent refresh job. Timestamp fields are
|
||||
milliseconds since the Unix epoch. ``expires_at_millis`` is an upper bound:
|
||||
the server may reclaim job scratch or evict an older capture sooner.
|
||||
|
||||
CPU evidence contains Python stacks weighted by thread CPU time. Memory
|
||||
evidence contains Python allocations made during capture and retained at
|
||||
its end. GPU evidence contains PyTorch CUDA activities; it excludes Python
|
||||
operator attribution and GPU allocation stacks.
|
||||
"""
|
||||
|
||||
profile_id: str
|
||||
job_id: str
|
||||
worker_id: str
|
||||
execution_epoch: int
|
||||
session_slot: int
|
||||
kind: FunctionProfileKind
|
||||
duration_seconds: float
|
||||
status: FunctionProfileStatus
|
||||
requested_at_millis: int
|
||||
deadline_at_millis: int
|
||||
expires_at_millis: int
|
||||
completed_at_millis: Optional[int] = None
|
||||
error: Optional[str] = None
|
||||
artifact_id: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def _from_json(cls, value: str) -> "FunctionProfile":
|
||||
return cls(**json.loads(value))
|
||||
+831
-123
File diff suppressed because it is too large
Load Diff
@@ -62,6 +62,7 @@ from lance_namespace import (
|
||||
from ..pydantic import LanceModel
|
||||
from ..table import Table
|
||||
from ..util import validate_table_name
|
||||
from ..resources import _resource_options
|
||||
|
||||
|
||||
def _duration_seconds(value: Optional[timedelta]) -> Optional[float]:
|
||||
@@ -641,6 +642,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.
|
||||
|
||||
@@ -686,6 +689,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
|
||||
-------
|
||||
@@ -761,6 +768,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"
|
||||
@@ -806,7 +823,19 @@ class RemoteDBConnection(DBConnection):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> MaterializedView:
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
from .table import RemoteTable
|
||||
|
||||
view = LOOP.run(
|
||||
@@ -821,6 +850,11 @@ class RemoteDBConnection(DBConnection):
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
)
|
||||
return MaterializedView(
|
||||
@@ -846,7 +880,19 @@ class RemoteDBConnection(DBConnection):
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> Job[None]:
|
||||
_resource_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
job = LOOP.run(
|
||||
self._conn.create_materialized_view_async(
|
||||
name,
|
||||
@@ -859,6 +905,11 @@ class RemoteDBConnection(DBConnection):
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -1405,6 +1456,9 @@ class RemoteDBConnection(DBConnection):
|
||||
*,
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
read_timeout: Optional[timedelta] = None,
|
||||
cancel_on_drop: bool = False,
|
||||
) -> SqlQuery:
|
||||
"""Start executing SQL through this LanceDB Enterprise connection.
|
||||
|
||||
@@ -1420,6 +1474,9 @@ class RemoteDBConnection(DBConnection):
|
||||
query,
|
||||
default_namespace_path=default_namespace_path,
|
||||
parameters=parameters,
|
||||
timeout=timeout,
|
||||
read_timeout=read_timeout,
|
||||
cancel_on_drop=cancel_on_drop,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -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 (
|
||||
@@ -48,8 +49,11 @@ from lancedb.index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.prewarm import PrewarmDataPlan, PrewarmDataResult
|
||||
from lancedb.cleanup import CleanupPlan, CleanupResult
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import (
|
||||
FunctionProvenance,
|
||||
FunctionApplication,
|
||||
FunctionRetryPolicy,
|
||||
RefreshColumnResult,
|
||||
@@ -77,9 +81,11 @@ from ..table import (
|
||||
BlobMode,
|
||||
Branches,
|
||||
CompactionOptions,
|
||||
CompactionResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
Table,
|
||||
TableDelta,
|
||||
Tags,
|
||||
)
|
||||
from ..types import BaseTokenizerType, ScalarIndexType
|
||||
@@ -282,6 +288,19 @@ class RemoteTable(Table):
|
||||
"""List all versions of the table"""
|
||||
return LOOP.run(self._table.list_versions())
|
||||
|
||||
def delta(
|
||||
self,
|
||||
from_version: int | str,
|
||||
to_version: Optional[int | str] = None,
|
||||
) -> TableDelta:
|
||||
"""Compare two versions or tags.
|
||||
|
||||
Streamed version deltas are not supported by LanceDB Enterprise tables;
|
||||
this raises ``NotImplementedError``.
|
||||
"""
|
||||
async_delta = LOOP.run(self._table.delta(from_version, to_version))
|
||||
return TableDelta(async_delta._inner)
|
||||
|
||||
def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table:
|
||||
"""to_arrow() is not supported in LanceDB Enterprise."""
|
||||
validate_blob_mode(blob_mode)
|
||||
@@ -600,7 +619,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
|
||||
@@ -923,6 +942,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))
|
||||
|
||||
@@ -1089,7 +1116,8 @@ class RemoteTable(Table):
|
||||
cleanup_old_versions() is a no-op in LanceDB Enterprise.
|
||||
"""
|
||||
warnings.warn(
|
||||
"cleanup_old_versions() is a no-op in LanceDB Enterprise.",
|
||||
"cleanup_old_versions() is a no-op in LanceDB Enterprise. "
|
||||
"Use cleanup_async() to submit durable cleanup explicitly.",
|
||||
stacklevel=2,
|
||||
)
|
||||
pass
|
||||
@@ -1104,6 +1132,26 @@ class RemoteTable(Table):
|
||||
)
|
||||
pass
|
||||
|
||||
def explain_cleanup(self, *, min_age_seconds: Optional[int] = None) -> CleanupPlan:
|
||||
"""Preview cleanup without submitting a job or deleting files."""
|
||||
return LOOP.run(self._table.explain_cleanup(min_age_seconds=min_age_seconds))
|
||||
|
||||
def cleanup_async(
|
||||
self, *, min_age_seconds: Optional[int] = None
|
||||
) -> Job[CleanupResult]:
|
||||
"""Submit cleanup. See
|
||||
|
||||
[Table.cleanup_async][lancedb.table.Table.cleanup_async].
|
||||
"""
|
||||
return Job(LOOP.run(self._table.cleanup_async(min_age_seconds=min_age_seconds)))
|
||||
|
||||
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,
|
||||
*,
|
||||
@@ -1152,7 +1200,9 @@ 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,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[int] = None,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
) -> AddColumnsResult:
|
||||
return LOOP.run(
|
||||
self._table.add_columns(
|
||||
@@ -1160,7 +1210,9 @@ 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,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
total_gpu_count=total_gpu_count,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1172,11 +1224,12 @@ class RemoteTable(Table):
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[Dict[str, int]] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[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,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
error_policy: Optional[Literal["fail", "skip"]] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
@@ -1184,7 +1237,14 @@ class RemoteTable(Table):
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_job_attempts: 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(
|
||||
@@ -1193,11 +1253,12 @@ class RemoteTable(Table):
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
publication_interval_rows=publication_interval_rows,
|
||||
resource_budget=resource_budget,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
supervisor_resources=supervisor_resources,
|
||||
planning_workers=planning_workers,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
total_gpu_count=total_gpu_count,
|
||||
retry_policy=retry_policy,
|
||||
error_policy=error_policy,
|
||||
max_failed_fraction=max_failed_fraction,
|
||||
@@ -1205,7 +1266,14 @@ class RemoteTable(Table):
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
init_timeout_seconds=init_timeout_seconds,
|
||||
num_workers=num_workers,
|
||||
max_job_attempts=max_job_attempts,
|
||||
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,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1217,11 +1285,12 @@ class RemoteTable(Table):
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
resource_budget: Optional[Dict[str, int]] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
total_memory_bytes: Optional[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,
|
||||
total_gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
error_policy: Optional[Literal["fail", "skip"]] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
@@ -1229,7 +1298,14 @@ class RemoteTable(Table):
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_job_attempts: 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(
|
||||
@@ -1239,11 +1315,12 @@ class RemoteTable(Table):
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
publication_interval_rows=publication_interval_rows,
|
||||
resource_budget=resource_budget,
|
||||
total_cpu_millis=total_cpu_millis,
|
||||
total_memory_bytes=total_memory_bytes,
|
||||
supervisor_resources=supervisor_resources,
|
||||
planning_workers=planning_workers,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
total_gpu_count=total_gpu_count,
|
||||
retry_policy=retry_policy,
|
||||
error_policy=error_policy,
|
||||
max_failed_fraction=max_failed_fraction,
|
||||
@@ -1251,19 +1328,67 @@ class RemoteTable(Table):
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
init_timeout_seconds=init_timeout_seconds,
|
||||
num_workers=num_workers,
|
||||
max_job_attempts=max_job_attempts,
|
||||
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,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def resume_refresh(self, job_id: str) -> Job[RefreshColumnResult]:
|
||||
return Job(LOOP.run(self._table.resume_refresh(job_id)))
|
||||
|
||||
def function_errors(
|
||||
self,
|
||||
job_id: Optional[str] = None,
|
||||
column: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
history: bool = False,
|
||||
page_token: Optional[str] = None,
|
||||
):
|
||||
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,
|
||||
page_token=page_token,
|
||||
)
|
||||
).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(
|
||||
@@ -1313,7 +1438,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]:
|
||||
@@ -1375,7 +1504,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
|
||||
@@ -1383,7 +1519,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
|
||||
@@ -1394,8 +1531,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)
|
||||
@@ -1414,9 +1605,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
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import re
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
|
||||
def _validate_gpu_class_name(value: Any) -> str:
|
||||
if not isinstance(value, str) or not re.fullmatch(
|
||||
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", value
|
||||
):
|
||||
raise ValueError(
|
||||
"gpu_class must be a lowercase name of at most 63 letters, digits, or "
|
||||
"hyphens, and cannot start or end with a hyphen"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _resource_options(
|
||||
cpu: Optional[int],
|
||||
memory: Optional[int],
|
||||
gpu: Optional[int],
|
||||
*,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
) -> dict[str, Union[int, str]]:
|
||||
result: dict[str, Union[int, str]] = {}
|
||||
for name, value, maximum, minimum in (
|
||||
("total_cpu_millis", cpu, 2**64 - 1, 1),
|
||||
("total_memory_bytes", memory, 2**64 - 1, 1),
|
||||
("total_gpu_count", gpu, 2**32 - 1, 0),
|
||||
("gpu_count", gpu_count, 2**32 - 1, 1),
|
||||
):
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{name} must be an integer")
|
||||
if not minimum <= value <= maximum:
|
||||
raise ValueError(f"{name} must be between {minimum} and {maximum}")
|
||||
result[name] = value
|
||||
if gpu_class is not None:
|
||||
result["gpu_class"] = _validate_gpu_class_name(gpu_class)
|
||||
if gpu is not None and (
|
||||
(gpu_count is not None and gpu_count > gpu)
|
||||
or (gpu_class is not None and gpu == 0)
|
||||
):
|
||||
raise ValueError("total_gpu_count cannot fit one Function worker")
|
||||
return result
|
||||
@@ -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):
|
||||
@@ -344,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.
|
||||
|
||||
|
||||
@@ -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 "
|
||||
|
||||
+1635
-151
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"]
|
||||
@@ -1958,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",
|
||||
@@ -2216,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(
|
||||
@@ -2384,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(
|
||||
@@ -3176,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,187 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb.cleanup import CleanupResult
|
||||
from test_remote_db import _create_table_handler, _mock_remote_sql_connection
|
||||
|
||||
|
||||
@pytest.mark.parametrize("counts", [(0, 0), (2, 123), (None, None)])
|
||||
def test_cleanup_result_preserves_measurements(counts):
|
||||
versions, size = counts
|
||||
result = CleanupResult.from_json(
|
||||
json.dumps(
|
||||
{
|
||||
"format_version": 1,
|
||||
"min_age_seconds": 0,
|
||||
"statistics_complete": versions is not None,
|
||||
"old_versions": versions,
|
||||
"bytes_removed": size,
|
||||
"future": True,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert result.old_versions == versions
|
||||
assert result.bytes_removed == size
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
None,
|
||||
{},
|
||||
{"format_version": 2},
|
||||
{
|
||||
"format_version": 1,
|
||||
"min_age_seconds": 0,
|
||||
"statistics_complete": False,
|
||||
"old_versions": 1,
|
||||
},
|
||||
],
|
||||
)
|
||||
def test_cleanup_result_rejects_missing_unknown_or_inconsistent_contract(payload):
|
||||
with pytest.raises(ValueError):
|
||||
CleanupResult.from_json(json.dumps(payload))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"outcome", ["counts", "no_op", "unknown", "missing", "FAILED", "CANCELLED"]
|
||||
)
|
||||
async def test_cleanup_submission_wait_and_reopen(asynchronous, outcome):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
polls = []
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"min_age_seconds": 0,
|
||||
"statistics_complete": outcome != "unknown",
|
||||
"old_versions": None
|
||||
if outcome == "unknown"
|
||||
else 0
|
||||
if outcome == "no_op"
|
||||
else 2,
|
||||
"bytes_removed": None
|
||||
if outcome == "unknown"
|
||||
else 0
|
||||
if outcome == "no_op"
|
||||
else 123,
|
||||
}
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(pa.table({"job_id": ["cleanup-job"]}))
|
||||
|
||||
def handler(request):
|
||||
if request.path != "/v1/jobs/describe":
|
||||
return _create_table_handler(request)
|
||||
polls.append(
|
||||
json.loads(request.rfile.read(int(request.headers["Content-Length"])))
|
||||
)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
json.dumps(
|
||||
{
|
||||
"job_id": "cleanup-job",
|
||||
"job_type": "cleanup",
|
||||
"job_state": outcome
|
||||
if outcome in ("FAILED", "CANCELLED")
|
||||
else "DONE",
|
||||
"result": None if outcome == "missing" else result,
|
||||
}
|
||||
).encode()
|
||||
)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server, handler) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
job = await table.cleanup_async(min_age_seconds=0)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
job = table.cleanup_async(min_age_seconds=0)
|
||||
assert job.id() == "cleanup-job" and not polls
|
||||
if outcome in ("missing", "FAILED", "CANCELLED"):
|
||||
with pytest.raises(
|
||||
Exception,
|
||||
match={
|
||||
"missing": "did not contain a result",
|
||||
"FAILED": "failed",
|
||||
"CANCELLED": "cancel",
|
||||
}[outcome],
|
||||
):
|
||||
if asynchronous:
|
||||
await job.wait()
|
||||
else:
|
||||
job.wait()
|
||||
else:
|
||||
stats = await job.wait() if asynchronous else job.wait()
|
||||
assert isinstance(stats, CleanupResult)
|
||||
assert stats.old_versions == result["old_versions"]
|
||||
reopened = (
|
||||
await db.open_job(job.id()) if asynchronous else db.open_job(job.id())
|
||||
)
|
||||
assert (await reopened.wait() if asynchronous else reopened.wait()) == stats
|
||||
assert len(server.tickets) == 1
|
||||
assert b"VACUUM" in server.tickets[0]
|
||||
assert b"min_age_seconds = 0" in server.tickets[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_cleanup_preview_is_read_only(asynchronous):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
payload = {
|
||||
"format_version": 1,
|
||||
"source_version": 42,
|
||||
"min_age_seconds": 0,
|
||||
"cutoff_millis": 123,
|
||||
"versions_to_remove": 2,
|
||||
"bytes_to_remove": 100,
|
||||
}
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.tickets = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.tickets.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"plan_type": ["logical_plan"], "plan": [json.dumps(payload)]})
|
||||
)
|
||||
|
||||
def handler(request):
|
||||
assert not request.path.startswith("/v1/jobs"), (
|
||||
"preview must not submit/monitor jobs"
|
||||
)
|
||||
return _create_table_handler(request)
|
||||
|
||||
server = Server()
|
||||
with _mock_remote_sql_connection(server, handler) as kwargs:
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(**kwargs)
|
||||
table = await db.create_table("test", [{"id": 1}])
|
||||
plan = await table.explain_cleanup(min_age_seconds=0)
|
||||
else:
|
||||
db = lancedb.connect(**kwargs)
|
||||
table = db.create_table("test", [{"id": 1}])
|
||||
plan = table.explain_cleanup(min_age_seconds=0)
|
||||
assert plan.source_version == 42
|
||||
assert plan.versions_to_remove == 2
|
||||
assert len(server.tickets) == 1
|
||||
assert b"EXPLAIN (FORMAT JSON) VACUUM" in server.tickets[0]
|
||||
@@ -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
|
||||
|
||||
@@ -845,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
|
||||
@@ -932,7 +985,7 @@ def test_drop_table_async(tmp_db: lancedb.DBConnection):
|
||||
assert tmp_db.table_names() == ["test"]
|
||||
|
||||
job = tmp_db.drop_table_async("test")
|
||||
assert job.id is None
|
||||
assert job.id() is None
|
||||
assert job.status() == "finished"
|
||||
assert job.wait() is None
|
||||
assert tmp_db.table_names() == []
|
||||
@@ -948,7 +1001,7 @@ async def test_drop_table_async_connection(tmp_db_async: lancedb.AsyncConnection
|
||||
await tmp_db_async.create_table("test", data=pa.table({"id": [1, 2]}))
|
||||
|
||||
job = await tmp_db_async.drop_table_async("test")
|
||||
assert job.id is None
|
||||
assert job.id() is None
|
||||
assert await job.status() == "finished"
|
||||
assert await job.wait() is None
|
||||
assert await tmp_db_async.table_names() == []
|
||||
|
||||
@@ -11,11 +11,139 @@ import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
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"
|
||||
)
|
||||
@@ -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 ─────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ from lancedb.functions import (
|
||||
SecretReference,
|
||||
)
|
||||
from lancedb.table import AsyncTable
|
||||
from lancedb.resources import _resource_options
|
||||
|
||||
|
||||
FIXTURES = (
|
||||
@@ -614,7 +615,11 @@ class _FunctionDeclarationInner:
|
||||
output_name,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
auto_refresh_resource_budget,
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=None,
|
||||
gpu_count=None,
|
||||
):
|
||||
self.calls.append(
|
||||
(
|
||||
@@ -622,7 +627,9 @@ class _FunctionDeclarationInner:
|
||||
output_name,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
auto_refresh_resource_budget,
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
)
|
||||
)
|
||||
return "declared"
|
||||
@@ -648,18 +655,22 @@ 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, None)
|
||||
assert inner.calls[-1][2:] == (None, None, None, None, None)
|
||||
|
||||
bare = application._copy(update={"columns": {}}).rename(
|
||||
columns={"normalized_text": "search_text"}
|
||||
)
|
||||
result = await table.add_columns(
|
||||
bare, auto_refresh_enabled=False, auto_refresh_interval_seconds=300
|
||||
bare,
|
||||
auto_refresh_enabled=False,
|
||||
auto_refresh_interval_seconds=300,
|
||||
total_cpu_millis=8000,
|
||||
total_gpu_count=0,
|
||||
)
|
||||
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, None)
|
||||
assert inner.calls[-1][2:] == (False, 300, 8000, None, 0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -715,3 +726,20 @@ def test_rename_requires_named_struct_and_keeps_partial_mapping_immutable():
|
||||
renamed = application.rename(columns={"normalized_text": "search_text"})
|
||||
assert dict(application.columns) == {}
|
||||
assert dict(renamed.columns) == {"normalized_text": "search_text"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gpu_count", [0, -1, True, 1.5, 2**32])
|
||||
def test_gpu_worker_count_rejects_invalid_values(gpu_count):
|
||||
with pytest.raises(ValueError, match="gpu_count"):
|
||||
_resource_options(None, None, None, gpu_count=gpu_count)
|
||||
|
||||
|
||||
def test_gpu_worker_settings_are_separate_from_execution_totals():
|
||||
assert _resource_options(8000, None, 8, gpu_class="any", gpu_count=2) == {
|
||||
"total_cpu_millis": 8000,
|
||||
"total_gpu_count": 8,
|
||||
"gpu_class": "any",
|
||||
"gpu_count": 2,
|
||||
}
|
||||
with pytest.raises(ValueError, match="cannot fit"):
|
||||
_resource_options(None, None, 1, gpu_count=2)
|
||||
|
||||
@@ -833,7 +833,7 @@ def test_function_image_requires_digest_reference(image):
|
||||
def test_function_gpu_marker_uses_gpu_runtime():
|
||||
with pytest.warns(UserWarning, match="uses a scalar callable"):
|
||||
|
||||
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
|
||||
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g", gpu_count=2)
|
||||
def double_on_gpu(value: int) -> int:
|
||||
return value * 2
|
||||
|
||||
@@ -841,6 +841,7 @@ def test_function_gpu_marker_uses_gpu_runtime():
|
||||
assert request["runtime"]["kind"] == "python_v2"
|
||||
assert request["runtime"]["gpu"] is True
|
||||
assert request["runtime"]["gpu_class"] == "a10g"
|
||||
assert request["runtime"]["gpus_per_worker"] == 2
|
||||
|
||||
@function(pip=["pyarrow"])
|
||||
def cpu_function(value: int) -> int:
|
||||
@@ -856,14 +857,29 @@ def test_function_gpu_marker_uses_gpu_runtime():
|
||||
def identity(value: int) -> int:
|
||||
return value
|
||||
|
||||
for invalid in [None, 0, 1, -1, 1.5, "", "true", "1", "H100"]:
|
||||
with pytest.raises(ValueError, match="gpu must be a boolean"):
|
||||
for invalid in [
|
||||
0,
|
||||
1,
|
||||
-1,
|
||||
1.5,
|
||||
"",
|
||||
"true",
|
||||
"1",
|
||||
"a_b",
|
||||
"-a10g",
|
||||
"a10g-",
|
||||
"a" * 64,
|
||||
]:
|
||||
with pytest.raises(ValueError, match="gpu"):
|
||||
function(name="invalid_gpu", gpu=invalid)(identity)
|
||||
for invalid in ["H100", "a_b", "-a10g", "a10g-", "a" * 64]:
|
||||
for enabled in (None, False):
|
||||
for options in ({"gpu_class": "h100"}, {"gpu_count": 2}):
|
||||
with pytest.raises(ValueError, match="require gpu=True"):
|
||||
function(gpu=enabled, **options)(identity)
|
||||
for invalid_class in ("H100", "a_b", "-h100", "h100-", "", "a" * 64):
|
||||
with pytest.raises(ValueError, match="gpu_class"):
|
||||
function(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity)
|
||||
with pytest.raises(ValueError, match="requires gpu=True"):
|
||||
function(name="gpu_class_without_gpu", gpu_class="a10g")(identity)
|
||||
function(gpu=True, gpu_class=invalid_class)(identity)
|
||||
assert function(gpu=False)(identity).registration_request.runtime.gpu is None
|
||||
|
||||
base_runtime = {
|
||||
"kind": "python_v2",
|
||||
@@ -895,6 +911,66 @@ class _GpuArrayFunction:
|
||||
return value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name, count", [(None, 1), ("h100", 2), ("a10g", 4), ("any", 2)]
|
||||
)
|
||||
def test_gpu_count_is_part_of_runtime_identity(name, count):
|
||||
with pytest.warns(UserWarning):
|
||||
definition = function(gpu=True, gpu_class=name, gpu_count=count)(
|
||||
normalize_score.__wrapped__
|
||||
)
|
||||
runtime = definition.registration_request.runtime
|
||||
assert runtime.gpu is True
|
||||
assert runtime.gpu_class == name
|
||||
assert runtime.gpus_per_worker == count
|
||||
encoded = definition.registration_request.to_canonical_json()
|
||||
assert json.loads(encoded)["runtime"]["gpus_per_worker"] == count
|
||||
different = runtime._copy(update={"gpus_per_worker": count + 1})
|
||||
assert runtime.digest != different.digest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count", [0, -1, True, 1.5, "2", 2**32])
|
||||
def test_gpu_annotation_rejects_invalid_counts(count):
|
||||
with pytest.raises(ValueError, match="gpu_count"):
|
||||
function(gpu=True, gpu_count=count)(normalize_score.__wrapped__)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count", [0, -1, True, 1.5, "2", 2**32])
|
||||
def test_gpu_wire_count_is_a_strict_positive_uint32(count):
|
||||
with pytest.raises(ValueError):
|
||||
PythonRuntimeSpec.model_validate(
|
||||
{
|
||||
"kind": "python_v2",
|
||||
"python_version": "3.12",
|
||||
"environment": {"kind": "pip"},
|
||||
"gpu": True,
|
||||
"gpus_per_worker": count,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_function_annotation_carries_independent_total_defaults():
|
||||
definition = function(
|
||||
total_cpu_millis=8000,
|
||||
total_memory_bytes=16 * 1024**3,
|
||||
total_gpu_count=0,
|
||||
)(normalize_score.__wrapped__)
|
||||
request = json.loads(definition.registration_request.to_canonical_json())
|
||||
assert request["total_cpu_millis"] == 8000
|
||||
assert request["total_memory_bytes"] == 16 * 1024**3
|
||||
assert request["total_gpu_count"] == 0
|
||||
assert "gpu" not in request["runtime"]
|
||||
for values in (
|
||||
{"total_cpu_millis": 0},
|
||||
{"total_memory_bytes": True},
|
||||
{"total_memory_bytes": 2**64},
|
||||
{"total_gpu_count": -1},
|
||||
{"total_gpu_count": 2**32},
|
||||
):
|
||||
with pytest.raises(ValueError):
|
||||
function(**values)(normalize_score.__wrapped__)
|
||||
|
||||
|
||||
def test_gpu_scalar_warning_names_the_vectorized_alternative():
|
||||
with pytest.warns(UserWarning, match="model batch is not inferred"):
|
||||
|
||||
|
||||
@@ -1655,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"
|
||||
@@ -1677,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,
|
||||
|
||||
@@ -20,6 +20,7 @@ from typing import Annotated, Optional, get_type_hints
|
||||
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pyarrow.compute as pc
|
||||
import pytest
|
||||
|
||||
from lancedb import col
|
||||
@@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas():
|
||||
assert identity(values).equals(values)
|
||||
|
||||
|
||||
def test_batch_functions_take_one_array_parameter_per_input_column():
|
||||
@function(
|
||||
input_schema=pa.schema(
|
||||
[
|
||||
pa.field("value", pa.float64(), nullable=False),
|
||||
pa.field("weight", pa.float64(), nullable=False),
|
||||
]
|
||||
),
|
||||
output_schema=pa.float64(),
|
||||
)
|
||||
def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array:
|
||||
return pc.multiply(value, weight)
|
||||
|
||||
signature = weighted_score.registration_request.signature
|
||||
assert [parameter.name for parameter in signature.inputs] == ["value", "weight"]
|
||||
result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0]))
|
||||
assert result.to_pylist() == [3.0, 8.0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"invoke",
|
||||
[
|
||||
lambda definition: definition(col("value")),
|
||||
lambda definition: definition(value=col("value")),
|
||||
lambda definition: definition(value=col("value") * 2),
|
||||
],
|
||||
ids=["positional", "keyword", "derived"],
|
||||
)
|
||||
def test_definition_calls_reject_expr_inputs_before_user_code(invoke):
|
||||
@function
|
||||
def double(value: float) -> float:
|
||||
raise AssertionError("user code ran")
|
||||
|
||||
with pytest.raises(TypeError, match="registered FunctionVersion"):
|
||||
invoke(double)
|
||||
|
||||
|
||||
def test_class_definition_binds_initialization_only_on_a_version():
|
||||
with pytest.raises(TypeError, match="registered FunctionVersion"):
|
||||
scale(factor=col("factor"), label="x")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("class_function", [False, True])
|
||||
@pytest.mark.parametrize("postponed", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
@@ -727,7 +770,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
|
||||
@pytest.mark.parametrize(
|
||||
"module_name",
|
||||
[
|
||||
"sys",
|
||||
"builtins",
|
||||
"importlib",
|
||||
"inspect",
|
||||
@@ -735,7 +777,6 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
|
||||
"ctypes",
|
||||
"types",
|
||||
"ctypes.util",
|
||||
"importlib.metadata",
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("import_style", ["import", "from", "global"])
|
||||
@@ -772,6 +813,146 @@ def test_namespace_module_errors_explain_the_rule_and_remedy(
|
||||
assert "dynamic namespace access" not in message
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module_level", [False, True], ids=["body", "module"])
|
||||
@pytest.mark.parametrize(
|
||||
("import_statement", "expression"),
|
||||
[
|
||||
("import sys", "sys.stderr"),
|
||||
("import sys as diagnostic", "diagnostic.stderr"),
|
||||
("from sys import stderr", "stderr"),
|
||||
("from sys import stderr as error_stream", "error_stream"),
|
||||
("import sys", "sys.version_info"),
|
||||
("import sys as diagnostic", "diagnostic.version_info"),
|
||||
("from sys import version_info", "version_info"),
|
||||
("from sys import version_info as python_version", "python_version"),
|
||||
("import importlib.metadata", "importlib.metadata.version('pytest')"),
|
||||
("import importlib.metadata as diagnostic", "diagnostic.version('pytest')"),
|
||||
("from importlib import metadata", "metadata.version('pytest')"),
|
||||
(
|
||||
"from importlib import metadata as diagnostic",
|
||||
"diagnostic.version('pytest')",
|
||||
),
|
||||
("from importlib.metadata import version", "version('pytest')"),
|
||||
(
|
||||
"from importlib.metadata import version as diagnostic",
|
||||
"diagnostic('pytest')",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_diagnostic_namespace_operations_package_and_run(
|
||||
helper_package, module_level, import_statement, expression
|
||||
):
|
||||
if module_level:
|
||||
source = (
|
||||
f"{import_statement}\n\n"
|
||||
"def probe(value: str) -> str:\n"
|
||||
f" return str({expression}) + value\n"
|
||||
)
|
||||
else:
|
||||
source = (
|
||||
"def probe(value: str) -> str:\n"
|
||||
f" {import_statement}\n"
|
||||
f" return str({expression}) + value\n"
|
||||
)
|
||||
module = helper_package("fx_diagnostic_operation", {"__init__.py": source})
|
||||
|
||||
packaged = artifact(function(module.probe)).decode()
|
||||
namespace = {}
|
||||
exec(compile(packaged, "user_function.py", "exec"), namespace)
|
||||
assert namespace["probe"]("!").endswith("!")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("body", "operation"),
|
||||
[
|
||||
("import sys\nreturn str(sys.modules)", "sys.modules"),
|
||||
("import sys as s\nreturn str(s.path)", "s.path"),
|
||||
("import sys\nreturn str(sys.version)", "sys.version"),
|
||||
("import sys\nreturn str(sys.stdout)", "sys.stdout"),
|
||||
("import sys\nreturn str(getattr(sys, 'stderr'))", "sys"),
|
||||
("import sys\nstream = sys\nreturn str(stream)", "sys"),
|
||||
("import sys\nsys = object()\nreturn str(sys)", "sys"),
|
||||
("from sys import path\nreturn str(path)", "sys.path"),
|
||||
(
|
||||
"import importlib.metadata\n"
|
||||
"return importlib.metadata.distribution('pytest').version",
|
||||
"importlib.metadata.distribution",
|
||||
),
|
||||
(
|
||||
"import importlib.metadata as m\nreturn m.distribution('pytest').version",
|
||||
"m.distribution",
|
||||
),
|
||||
(
|
||||
"from importlib.metadata import distribution\n"
|
||||
"return distribution('pytest').version",
|
||||
"importlib.metadata.distribution",
|
||||
),
|
||||
(
|
||||
"from importlib.metadata import version\nreturn str(version.__globals__)",
|
||||
"version.__globals__",
|
||||
),
|
||||
(
|
||||
"import importlib\nreturn str(importlib.import_module('os'))",
|
||||
"importlib",
|
||||
),
|
||||
(
|
||||
"from importlib import import_module\nreturn str(import_module('os'))",
|
||||
"importlib",
|
||||
),
|
||||
(
|
||||
"import importlib.resources\nreturn str(importlib.resources.files('x'))",
|
||||
"importlib.resources",
|
||||
),
|
||||
("import inspect\nreturn str(inspect.currentframe())", "inspect"),
|
||||
(
|
||||
"from ctypes import util\nreturn str(util.find_library('c'))",
|
||||
"ctypes",
|
||||
),
|
||||
("import gc\nreturn str(gc.get_objects())", "gc"),
|
||||
("import builtins\nreturn str(builtins)", "builtins"),
|
||||
("import types\nreturn str(types.SimpleNamespace())", "types"),
|
||||
],
|
||||
)
|
||||
def test_unsupported_namespace_operations_are_rejected(helper_package, body, operation):
|
||||
source = "def blocked(value: str) -> str:\n" + textwrap.indent(body, " ")
|
||||
module = helper_package(
|
||||
"fx_unsupported_namespace_operation", {"__init__.py": source}
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError) as error:
|
||||
function(module.blocked)
|
||||
message = str(error.value)
|
||||
assert repr(operation) in message
|
||||
assert "supported diagnostic operations" in message
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("preamble", "body", "operation"),
|
||||
[
|
||||
(
|
||||
"import sys as diagnostic",
|
||||
"return str(diagnostic.modules)",
|
||||
"diagnostic.modules",
|
||||
),
|
||||
(
|
||||
"import importlib.metadata as diagnostic",
|
||||
"return diagnostic.distribution('pytest').version",
|
||||
"diagnostic.distribution",
|
||||
),
|
||||
("from sys import stderr", "return str(stderr.__class__)", "stderr.__class__"),
|
||||
],
|
||||
)
|
||||
def test_module_level_diagnostic_alias_rejects_unsupported_use(
|
||||
helper_package, preamble, body, operation
|
||||
):
|
||||
source = f"{preamble}\n\ndef blocked(value: str) -> str:\n {body}\n"
|
||||
module = helper_package("fx_diagnostic_alias", {"__init__.py": source})
|
||||
|
||||
with pytest.raises(ValueError) as error:
|
||||
function(module.blocked)
|
||||
assert repr(operation) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
|
||||
def test_udf_namespace_import_error_explains_the_helper_alternative():
|
||||
with pytest.raises(ValueError, match="ctypes.util.*importable helper module"):
|
||||
|
||||
@@ -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,
|
||||
@@ -23,6 +25,7 @@ from lancedb.index import (
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -89,7 +92,7 @@ async def binary_table(db_async):
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_index_async_returns_done_job(some_table: AsyncTable):
|
||||
job = await some_table.create_index_async("id", config=BTree())
|
||||
assert job.id is None
|
||||
assert job.id() is None
|
||||
assert await job.wait() is None
|
||||
assert len(await some_table.list_indices()) == 1
|
||||
await job.cancel()
|
||||
@@ -250,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.
|
||||
@@ -615,6 +1000,7 @@ def test_index_statistics_index_type_lists_all_supported_values():
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
"ZONEMAP",
|
||||
"RTREE",
|
||||
}
|
||||
|
||||
assert (
|
||||
@@ -659,7 +1045,7 @@ async def test_named_index_exist_ok_checks_before_column_validation(
|
||||
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
|
||||
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"]
|
||||
|
||||
@@ -9,13 +9,202 @@ from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
|
||||
from lancedb.exceptions import JobCancelledError, JobFailedError
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.job import AsyncJob, Job, _progress_eta
|
||||
from lancedb.job import AsyncJob, Job, JobState, _progress_eta
|
||||
from lancedb.remote.errors import HttpError, RetryError
|
||||
|
||||
|
||||
@pytest.mark.parametrize("job_class", [AsyncJob, Job])
|
||||
def test_job_handle_data_access_uses_methods(job_class):
|
||||
assert all(
|
||||
name.startswith("_")
|
||||
for name, member in vars(job_class).items()
|
||||
if isinstance(member, property)
|
||||
)
|
||||
job = job_class(None)
|
||||
expected = {
|
||||
"id": None,
|
||||
"state": "finished",
|
||||
"job_type": None,
|
||||
"creation_ms": None,
|
||||
"spec": None,
|
||||
"result": None,
|
||||
"failure": None,
|
||||
}
|
||||
for name, value in expected.items():
|
||||
assert callable(getattr(job, name))
|
||||
assert getattr(job, name)() == value
|
||||
assert getattr(job, f"_{name}") == value
|
||||
|
||||
|
||||
@pytest.fixture(params=[False, True], ids=["async", "sync"])
|
||||
def job_snapshot(request):
|
||||
def create(inner):
|
||||
job = AsyncJob(inner)
|
||||
if request.param:
|
||||
job = Job(job)
|
||||
|
||||
async def call(method="checkout_latest"):
|
||||
if request.param:
|
||||
return await asyncio.to_thread(getattr(job, method))
|
||||
return await getattr(job, method)()
|
||||
|
||||
return job, call
|
||||
|
||||
return create
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["checkout_latest", "refresh"])
|
||||
@pytest.mark.parametrize("state", ["finished", "failed", "cancelled", "future_state"])
|
||||
async def test_job_checkout_latest_refreshes_the_complete_snapshot(
|
||||
job_snapshot, method, state
|
||||
):
|
||||
spec = {"column": "vector", "initialization": list(range(1000))}
|
||||
result = {"rows_assigned": 1000} if state == "finished" else None
|
||||
failure = SimpleNamespace(message="worker failed") if state == "failed" else None
|
||||
description = SimpleNamespace(
|
||||
creation_ms=2000, spec=spec, result=result, failure=failure
|
||||
)
|
||||
inner = SimpleNamespace(
|
||||
id="operation-1",
|
||||
_state=None,
|
||||
_description=None,
|
||||
job_type=None,
|
||||
status=AsyncMock(),
|
||||
)
|
||||
|
||||
async def observe():
|
||||
inner._state = state
|
||||
inner.job_type = "refresh_column"
|
||||
inner._description = description
|
||||
inner.job_id = "attempt-2"
|
||||
inner.operation_id = "operation-1"
|
||||
inner.attempt = 2
|
||||
inner.retry_of = "attempt-1"
|
||||
inner.lifecycle_state = str(JobState(state))
|
||||
inner.source_table_version = 7
|
||||
inner.execution_epoch = 3
|
||||
|
||||
inner.refresh = AsyncMock(side_effect=observe)
|
||||
job, call = job_snapshot(inner)
|
||||
assert job.state() is None
|
||||
assert job.job_id() == "operation-1"
|
||||
assert job.lifecycle_state() is None
|
||||
assert job.job_type() is None
|
||||
assert job.creation_ms() is None
|
||||
assert job.spec() is None
|
||||
assert job.result() is None
|
||||
assert job.failure() is None
|
||||
inner.refresh.assert_not_called()
|
||||
|
||||
assert await call(method) is None
|
||||
assert job.state() == state
|
||||
assert job.job_type() == "refresh_column"
|
||||
assert job.creation_ms() == 2000
|
||||
assert job.spec() is spec
|
||||
assert job.result() is result
|
||||
assert job.failure() is failure
|
||||
assert job.id() == "operation-1"
|
||||
assert job.job_id() == "attempt-2"
|
||||
assert job.operation_id() == "operation-1"
|
||||
assert job.attempt() == 2
|
||||
assert job.retry_of() == "attempt-1"
|
||||
assert job.lifecycle_state() == JobState(state)
|
||||
assert job.source_table_version() == 7
|
||||
assert job.execution_epoch() == 3
|
||||
inner.refresh.assert_awaited_once_with()
|
||||
inner.status.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_checkout_latest_keeps_cached_details_on_request_error(job_snapshot):
|
||||
error = HttpError("not found", "req-job", 404)
|
||||
description = SimpleNamespace(
|
||||
creation_ms=2000, spec={"column": "vector"}, result=None, failure=None
|
||||
)
|
||||
inner = SimpleNamespace(
|
||||
_state="running",
|
||||
_description=description,
|
||||
job_type="refresh_column",
|
||||
refresh=AsyncMock(side_effect=error),
|
||||
)
|
||||
job, call = job_snapshot(inner)
|
||||
|
||||
with pytest.raises(HttpError) as exc:
|
||||
await call()
|
||||
assert exc.value is error
|
||||
assert job.state() == "running"
|
||||
assert job.spec() is description.spec
|
||||
assert job.result() is None
|
||||
assert job.failure() is None
|
||||
inner.refresh.assert_awaited_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_job_checkout_latest_preserves_refresh_overrides(sync, monkeypatch):
|
||||
job = AsyncJob(None)
|
||||
if sync:
|
||||
job = Job(job)
|
||||
refresh = MagicMock() if sync else AsyncMock()
|
||||
monkeypatch.setattr(job, "refresh", refresh)
|
||||
|
||||
if sync:
|
||||
assert await asyncio.to_thread(job.checkout_latest) is None
|
||||
else:
|
||||
assert await job.checkout_latest() is None
|
||||
refresh.assert_awaited_once_with()
|
||||
refresh.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_job_checkout_latest_for_completed_local_jobs(job_snapshot):
|
||||
job, call = job_snapshot(None)
|
||||
assert await call() is None
|
||||
assert job.state() == "finished"
|
||||
assert job.job_type() is None
|
||||
assert job.spec() is None
|
||||
assert job.result() is None
|
||||
assert job.failure() is None
|
||||
assert Job(None).checkout_latest() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
def test_local_jobs_retain_identity_and_typed_state(sync):
|
||||
job = AsyncJob(None)
|
||||
if sync:
|
||||
job = Job(job)
|
||||
assert job.job_id() == job.operation_id()
|
||||
assert job.job_id() == job.job_id()
|
||||
assert job.attempt() == 1
|
||||
assert job.retry_of() is None
|
||||
assert job.lifecycle_state() is JobState.SUCCEEDED
|
||||
|
||||
|
||||
def test_unknown_job_state_is_preserved_without_becoming_success():
|
||||
state = JobState("future_publication_state")
|
||||
assert state.value == "future_publication_state"
|
||||
assert str(state) == "future_publication_state"
|
||||
assert not state.is_terminal
|
||||
assert not state.is_success
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_history_follows_page_tokens():
|
||||
first = pa.table({"event_seq": [2, 1]}).replace_schema_metadata(
|
||||
{b"lancedb.job_coordinator.page_token": b"next"}
|
||||
)
|
||||
last = pa.table({"event_seq": [0]})
|
||||
inner = SimpleNamespace(events=AsyncMock(side_effect=[first, last]))
|
||||
pages = [page async for page in AsyncJob(inner).history(limit=2)]
|
||||
assert [page["event_seq"].to_pylist() for page in pages] == [[2, 1], [0]]
|
||||
assert inner.events.call_args_list[1].kwargs["page_token"] == "next"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
def test_job_repr_bounds_large_payloads_without_fetching(sync):
|
||||
spec = {"initialization": list(range(100000)), "source": "x" * 100000}
|
||||
@@ -44,9 +233,9 @@ def test_job_repr_bounds_large_payloads_without_fetching(sync):
|
||||
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
|
||||
assert job.spec() is spec
|
||||
assert job.result() is result
|
||||
assert len(job.spec()["initialization"]) == 100000
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@@ -1027,3 +1216,203 @@ async def test_export_timeline_reports_filesystem_errors(tmp_path):
|
||||
)
|
||||
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"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_profile_wait_preserves_timeout_and_never_waits_or_cancels_parent(sync):
|
||||
error = TimeoutError("capture and refresh continue")
|
||||
inner = SimpleNamespace(
|
||||
wait_for_profile=AsyncMock(side_effect=error),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
kwargs = {
|
||||
"timeout": timedelta(milliseconds=50),
|
||||
"poll_interval": timedelta(seconds=5),
|
||||
}
|
||||
with pytest.raises(TimeoutError) as caught:
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).wait_for_profile, "profile-1", **kwargs)
|
||||
else:
|
||||
await job.wait_for_profile("profile-1", **kwargs)
|
||||
assert caught.value is error
|
||||
inner.wait_for_profile.assert_awaited_once_with(
|
||||
"profile-1", timeout_seconds=0.05, poll_interval_seconds=5.0
|
||||
)
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_profile_export_failure_preserves_destination_and_server_error(
|
||||
sync, tmp_path
|
||||
):
|
||||
error = HttpError("403: System Operate required", "request-1", 403)
|
||||
inner = SimpleNamespace(profile_artifact=AsyncMock(side_effect=error))
|
||||
job = AsyncJob(inner)
|
||||
path = tmp_path / "profile.json"
|
||||
path.write_text("previous capture")
|
||||
with pytest.raises(HttpError) as caught:
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).export_profile, "profile-1", path)
|
||||
else:
|
||||
await job.export_profile("profile-1", path)
|
||||
assert caught.value is error
|
||||
assert path.read_text() == "previous capture"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"method,args",
|
||||
[
|
||||
("capture_profile", ("worker-1",)),
|
||||
("profile_status", ("profile-1",)),
|
||||
("wait_for_profile", ("profile-1",)),
|
||||
("profile_artifact", ("profile-1",)),
|
||||
],
|
||||
)
|
||||
async def test_function_profiles_reject_embedded_handles(method, args):
|
||||
with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"):
|
||||
await getattr(AsyncJob(None), method)(*args)
|
||||
with pytest.raises(NotImplementedError, match="Enterprise Function refresh job"):
|
||||
getattr(Job(None), method)(*args)
|
||||
|
||||
@@ -68,8 +68,12 @@ def mock_remote_materialized_view_refresh():
|
||||
"resources",
|
||||
[
|
||||
{},
|
||||
{"gpu_count": 2, "gpu_class": "h100"},
|
||||
{"cpu_millis": 8000, "memory_bytes": 16 * 1024**3, "gpu_count": 0},
|
||||
{"total_gpu_count": 2, "gpu_class": "h100"},
|
||||
{
|
||||
"total_cpu_millis": 8000,
|
||||
"total_memory_bytes": 16 * 1024**3,
|
||||
"total_gpu_count": 0,
|
||||
},
|
||||
],
|
||||
)
|
||||
async def test_remote_refresh_reports_unknown_metrics(
|
||||
@@ -159,13 +163,12 @@ async def test_remote_refresh_reports_unknown_metrics(
|
||||
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},
|
||||
{"total_cpu_millis": 0},
|
||||
{"total_gpu_count": -1},
|
||||
{"total_gpu_count": True},
|
||||
{"total_gpu_count": 2**32},
|
||||
{"gpu_class": "H200:8"},
|
||||
{"gpu_count": 0, "gpu_class": "h100"},
|
||||
{"total_gpu_count": 0, "gpu_class": "h100"},
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
if sync:
|
||||
@@ -200,6 +203,11 @@ def test_sync_remote_create_uses_public_async_connection(query):
|
||||
exist_ok=False,
|
||||
auto_refresh_enabled=None,
|
||||
auto_refresh_interval_seconds=None,
|
||||
total_cpu_millis=None,
|
||||
total_memory_bytes=None,
|
||||
total_gpu_count=None,
|
||||
gpu_class=None,
|
||||
gpu_count=None,
|
||||
):
|
||||
calls.append(
|
||||
(
|
||||
@@ -269,21 +277,21 @@ def test_create_and_refresh_jobs(tmp_path):
|
||||
create_job = db.create_materialized_view_async(
|
||||
"adults", "people", where="age >= 18", with_no_data=True
|
||||
)
|
||||
assert create_job.id is None
|
||||
assert create_job.job_type is None
|
||||
assert create_job.id() is None
|
||||
assert create_job.job_type() is None
|
||||
assert create_job.wait() is None
|
||||
|
||||
view = db.open_materialized_view("adults")
|
||||
refresh_job = view.refresh_async()
|
||||
assert refresh_job.id is None
|
||||
assert refresh_job.job_type is None
|
||||
assert refresh_job.id() is None
|
||||
assert refresh_job.job_type() is None
|
||||
result = refresh_job.wait()
|
||||
assert result.mode == "rebuild"
|
||||
assert result.rows_written == 2
|
||||
assert view.table.count_rows() == 2
|
||||
|
||||
drop_job = db.drop_materialized_view_async("adults")
|
||||
assert drop_job.id is None
|
||||
assert drop_job.id() is None
|
||||
assert drop_job.wait() is None
|
||||
assert "adults" not in list(db.list_materialized_views())
|
||||
|
||||
@@ -442,20 +450,20 @@ async def test_async_create_and_refresh_jobs(tmp_path):
|
||||
create_job = await db.create_materialized_view_async(
|
||||
"adults", "people", with_no_data=True
|
||||
)
|
||||
assert create_job.id is None
|
||||
assert create_job.job_type is None
|
||||
assert create_job.id() is None
|
||||
assert create_job.job_type() is None
|
||||
assert await create_job.wait() is None
|
||||
|
||||
view = await db.open_materialized_view("adults")
|
||||
refresh_job = await view.refresh_async()
|
||||
assert refresh_job.id is None
|
||||
assert refresh_job.job_type is None
|
||||
assert refresh_job.id() is None
|
||||
assert refresh_job.job_type() is None
|
||||
result = await refresh_job.wait()
|
||||
assert result.mode == "rebuild"
|
||||
assert result.rows_written == 1
|
||||
|
||||
drop_job = await db.drop_materialized_view_async("adults")
|
||||
assert drop_job.id is None
|
||||
assert drop_job.id() is None
|
||||
assert await drop_job.wait() is None
|
||||
assert "adults" not in [item async for item in db.list_materialized_views()]
|
||||
|
||||
@@ -709,6 +717,11 @@ class CapturingCreateConnection:
|
||||
{},
|
||||
{"auto_refresh_enabled": True},
|
||||
{"auto_refresh_enabled": False, "auto_refresh_interval_seconds": 0.5},
|
||||
{"total_cpu_millis": 8000, "total_gpu_count": 0},
|
||||
{"total_memory_bytes": 16 * 1024**3},
|
||||
{"gpu_class": "any"},
|
||||
{"gpu_count": 2},
|
||||
{"gpu_class": "h100", "gpu_count": 2, "total_gpu_count": 4},
|
||||
],
|
||||
)
|
||||
def test_remote_create_forwards_refresh_options_without_interval_default(options):
|
||||
@@ -716,8 +729,8 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
|
||||
db = RemoteDBConnection.__new__(RemoteDBConnection)
|
||||
db._conn = AsyncConnection(native)
|
||||
job = db.create_materialized_view_async("adults", "people", **options)
|
||||
assert job.id == QueryBackedCreateJob.id
|
||||
assert job.job_type == "query"
|
||||
assert job.id() == QueryBackedCreateJob.id
|
||||
assert job.job_type() == "query"
|
||||
assert not hasattr(job, "query_id")
|
||||
assert job.wait() is None
|
||||
assert job.status() == "finished"
|
||||
@@ -731,6 +744,11 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
|
||||
"limit": None,
|
||||
"with_no_data": False,
|
||||
"exist_ok": False,
|
||||
"total_cpu_millis": options.get("total_cpu_millis"),
|
||||
"total_memory_bytes": options.get("total_memory_bytes"),
|
||||
"total_gpu_count": options.get("total_gpu_count"),
|
||||
"gpu_class": options.get("gpu_class"),
|
||||
"gpu_count": options.get("gpu_count"),
|
||||
"auto_refresh_enabled": options.get("auto_refresh_enabled"),
|
||||
"auto_refresh_interval_seconds": options.get(
|
||||
"auto_refresh_interval_seconds"
|
||||
@@ -747,8 +765,8 @@ async def test_async_remote_create_keeps_interval_unspecified():
|
||||
job = await db.create_materialized_view_async(
|
||||
"adults", "people", auto_refresh_enabled=True
|
||||
)
|
||||
assert job.id == QueryBackedCreateJob.id
|
||||
assert job.job_type == "query"
|
||||
assert job.id() == QueryBackedCreateJob.id
|
||||
assert job.job_type() == "query"
|
||||
assert not hasattr(job, "query_id")
|
||||
assert await job.wait() is None
|
||||
assert await job.status() == "finished"
|
||||
@@ -783,18 +801,34 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds):
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
def test_namespace_forwards_automatic_refresh_request(tmp_path):
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"auto_refresh_enabled": True},
|
||||
{"total_cpu_millis": 8000, "total_gpu_count": 0},
|
||||
{"total_memory_bytes": 1024},
|
||||
],
|
||||
)
|
||||
def test_namespace_forwards_automatic_refresh_request(tmp_path, options):
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
|
||||
db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
|
||||
db.create_materialized_view("mv", "source", **options)
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_namespace_forwards_automatic_refresh_request(tmp_path):
|
||||
@pytest.mark.parametrize(
|
||||
"options",
|
||||
[
|
||||
{"auto_refresh_enabled": True},
|
||||
{"total_cpu_millis": 8000, "total_gpu_count": 0},
|
||||
{"total_memory_bytes": 1024},
|
||||
],
|
||||
)
|
||||
async def test_async_namespace_forwards_automatic_refresh_request(tmp_path, options):
|
||||
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)})
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
|
||||
await db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
|
||||
await db.create_materialized_view("mv", "source", **options)
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
|
||||
@@ -241,6 +241,25 @@ def test_lsm_read_sees_active_memtable(tmp_path):
|
||||
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_to_batches_sees_active_memtable(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3])) # base ids 1,2,3
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
|
||||
_lsm_upsert(table, [4, 5]) # active memtable only, not committed to base
|
||||
|
||||
# The sync batch reader keeps the default LSM route and its pending writes.
|
||||
lsm = pa.Table.from_batches(list(table.search().to_batches(batch_size=2)))
|
||||
assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5]
|
||||
|
||||
# use_rte(False) still takes the base-only escape hatch through to_batches.
|
||||
base_only = pa.Table.from_batches(
|
||||
list(table.search().use_rte(False).to_batches(batch_size=2))
|
||||
)
|
||||
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_dedup_newest_wins(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3])) # id 2 -> value 1
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
import tempfile
|
||||
import shutil
|
||||
import importlib
|
||||
import asyncio
|
||||
import pickle
|
||||
import warnings
|
||||
import http.server
|
||||
import json
|
||||
@@ -16,6 +18,7 @@ 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
|
||||
@@ -26,7 +29,7 @@ from lancedb.namespace import (
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import FullTextSearchQuery, Query
|
||||
from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
|
||||
@@ -35,6 +38,37 @@ 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):
|
||||
@@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
|
||||
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])
|
||||
@@ -309,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(
|
||||
@@ -1352,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:
|
||||
@@ -1414,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",
|
||||
[
|
||||
|
||||
@@ -5,9 +5,15 @@ import pyarrow as pa
|
||||
import math
|
||||
import pytest
|
||||
|
||||
from lancedb import DBConnection, Table, connect
|
||||
from lancedb import DBConnection, Session, Table, connect, connect_namespace
|
||||
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,
|
||||
@@ -15,6 +21,18 @@ from utils import (
|
||||
)
|
||||
|
||||
|
||||
def _read_permutation_in_spawned_process(payload: bytes, output) -> None:
|
||||
import pickle
|
||||
|
||||
permutation = pickle.loads(payload)
|
||||
output.put(
|
||||
[
|
||||
row["id"]
|
||||
for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def test_split_random_ratios(mem_db):
|
||||
"""Test random splitting with ratios."""
|
||||
tbl = mem_db.create_table(
|
||||
@@ -81,6 +99,368 @@ def test_pickled_permutation_reads_pinned_version(tmp_path):
|
||||
assert sorted(row["idx"] for row in rows) == list(range(20))
|
||||
|
||||
|
||||
def test_persist_plan_create_overwrite_namespace_and_metadata(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
db.create_namespace(["plans"])
|
||||
namespace_path = ["plans"]
|
||||
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits", namespace_path=namespace_path)
|
||||
.execute()
|
||||
)
|
||||
assert plan.count_rows() == 20
|
||||
assert plan.namespace == namespace_path
|
||||
assert pickle.loads(pickle.dumps(plan)).namespace == namespace_path
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
assert permutation.base_version == tbl.version
|
||||
assert permutation.base_branch is None
|
||||
assert permutation.num_rows == 10
|
||||
|
||||
with pytest.raises((ValueError, RuntimeError), match="already exists"):
|
||||
(
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2)
|
||||
.persist(db, "splits", namespace_path=namespace_path)
|
||||
.execute()
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid mode"):
|
||||
permutation_builder(tbl).persist(db, "other", mode="replace")
|
||||
|
||||
class RemoteLike:
|
||||
uri = "db://example"
|
||||
|
||||
with pytest.raises(NotImplementedError, match="Enterprise"):
|
||||
permutation_builder(tbl).persist(RemoteLike(), "remote_splits")
|
||||
|
||||
tbl.add(pa.table({"id": range(20, 40)}))
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2)
|
||||
.persist(db, "splits", namespace_path=namespace_path, mode="overwrite")
|
||||
.execute()
|
||||
)
|
||||
assert plan.count_rows() == 40
|
||||
assert db.open_table("splits", namespace_path=namespace_path).count_rows() == 40
|
||||
# The earlier permutation still reads the plan and base snapshot it was built from.
|
||||
assert permutation.num_rows == 10
|
||||
assert [row["id"] for row in permutation.__getitems__([0, 1])] == [0, 1]
|
||||
|
||||
|
||||
def test_persist_namespace_connection_direct_result_pickle(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect_namespace("dir", {"root": str(tmp_path)})
|
||||
db.create_namespace(["plans"])
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits", namespace_path=["plans"])
|
||||
.execute()
|
||||
)
|
||||
assert plan.namespace == ["plans"]
|
||||
assert plan._conn is db
|
||||
|
||||
restored_plan = pickle.loads(pickle.dumps(plan))
|
||||
assert restored_plan.namespace == ["plans"]
|
||||
assert restored_plan.count_rows() == 20
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.num_rows == 10
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(10))
|
||||
|
||||
|
||||
def test_persist_direct_result_keeps_session_pickle_error(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, session=Session())
|
||||
tbl = db.create_table("base", pa.table({"id": range(5)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(plan)
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan)
|
||||
with pytest.raises(TypeError, match="Session"):
|
||||
pickle.dumps(permutation)
|
||||
|
||||
|
||||
def test_persist_direct_result_preserves_manifest_connection_state(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, manifest_enabled=True)
|
||||
tbl = db.create_table("base", pa.table({"id": range(5)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
restored = pickle.loads(pickle.dumps(plan))
|
||||
assert restored._conn._manifest_enabled is True
|
||||
assert restored.count_rows() == 5
|
||||
|
||||
|
||||
def test_base_branch_property_reads_plan_metadata(tmp_path):
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(10)}))
|
||||
branch = tbl.branches.create("exp")
|
||||
branch.add(pa.table({"id": range(10, 20)}))
|
||||
|
||||
plan = permutation_builder(branch).persist(db, "branch_splits").execute()
|
||||
permutation = Permutation.from_tables(branch, plan)
|
||||
|
||||
assert permutation.base_branch == "exp"
|
||||
assert permutation.base_version == branch.version
|
||||
assert permutation.num_rows == 20
|
||||
|
||||
|
||||
def test_persist_embedded_plan_for_remote_base(tmp_path):
|
||||
from lancedb import deserialize_conn
|
||||
|
||||
server = MockPermutationServer(num_rows=8)
|
||||
db = connect(tmp_path)
|
||||
|
||||
with mock_remote_table(server) as remote:
|
||||
permutation_builder(remote).shuffle(seed=7).persist(db, "plan").execute()
|
||||
plan = db.open_table("plan")
|
||||
expected_ids = plan.to_arrow().to_pydict()["row_id"]
|
||||
assert expected_ids != list(range(8))
|
||||
|
||||
# Advance the mock's latest version. A fresh handle must see v2, while
|
||||
# the plan's recorded v1 still pins every read to the old snapshot.
|
||||
server.publish_version(2, list(range(100, 108)))
|
||||
fresh_remote = deserialize_conn(
|
||||
remote._serialized_connection_state()
|
||||
).open_table(server.name)
|
||||
assert fresh_remote.version == 2
|
||||
|
||||
permutation = Permutation.from_tables(fresh_remote, plan)
|
||||
assert permutation.base_version == 1
|
||||
assert permutation.base_branch is None
|
||||
assert permutation._plan_version == 1
|
||||
assert permutation.permutation_table.version == 1
|
||||
|
||||
sequential_ids = [
|
||||
row["id"]
|
||||
for batch in permutation.iter(3, skip_last_batch=False)
|
||||
for row in batch
|
||||
]
|
||||
assert sequential_ids == expected_ids
|
||||
assert [row["id"] for row in permutation.__getitems__([5, 1, 5, 3])] == [
|
||||
expected_ids[i] for i in [5, 1, 5, 3]
|
||||
]
|
||||
|
||||
# The plan is local, but its build and gathers address the remote base
|
||||
# at the recorded main/v1 snapshot. Latest describes carry no version.
|
||||
assert server.scans
|
||||
assert server.takes
|
||||
for body in [*server.scans, *server.takes]:
|
||||
assert body.get("version") == 1
|
||||
assert body.get("branch") is None
|
||||
describe_versions = [body.get("version") for body in server.describe_bodies]
|
||||
assert None in describe_versions
|
||||
assert 1 in describe_versions
|
||||
assert all(body.get("branch") is None for body in server.describe_bodies)
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_reopens_same_snapshot_after_overwrite(tmp_path):
|
||||
from datetime import timedelta
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = permutation_builder(tbl).filter("id < 10").persist(db, "splits").execute()
|
||||
permutation = Permutation.from_tables(tbl, plan)
|
||||
old_base_version = permutation.base_version
|
||||
old_plan_version = permutation._plan_version
|
||||
state = permutation.__getstate__()
|
||||
assert "permutation_data" not in state
|
||||
assert (
|
||||
state["permutation_table_state"]["state"]["checkout_version"]
|
||||
== old_plan_version
|
||||
)
|
||||
|
||||
# Replace the plan with disjoint rows of the same cardinality.
|
||||
permutation_builder(tbl).filter("id >= 10").persist(
|
||||
db, "splits", mode="overwrite"
|
||||
).execute()
|
||||
assert plan.version == old_plan_version + 1
|
||||
assert permutation.permutation_table.version == old_plan_version
|
||||
|
||||
live_ids = [
|
||||
row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
assert live_ids == list(range(10))
|
||||
|
||||
# A reader recreated after the overwrite must still use the pinned snapshot.
|
||||
permutation.reader = None
|
||||
permutation._pid = None
|
||||
recreated_ids = [
|
||||
row["id"] for row in permutation.__getitems__(list(range(permutation.num_rows)))
|
||||
]
|
||||
assert recreated_ids == list(range(10))
|
||||
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.base_version == old_base_version
|
||||
restored_ids = [
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
]
|
||||
assert restored_ids == list(range(10))
|
||||
|
||||
# A newly constructed permutation sees the overwritten plan.
|
||||
fresh = Permutation.from_tables(tbl, db.open_table("splits"))
|
||||
assert fresh.base_version == old_base_version
|
||||
fresh_ids = [row["id"] for row in fresh.__getitems__(list(range(fresh.num_rows)))]
|
||||
assert fresh_ids == list(range(10, 20))
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_uses_captured_main_branch(tmp_path):
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
permutation_builder(tbl).persist(db, "splits").execute()
|
||||
|
||||
initial_plan = db.open_table("splits")
|
||||
initial_plan.branches.create("exp", from_version=1)
|
||||
|
||||
# Main plan version 2 still has all 20 rows.
|
||||
permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
|
||||
main_plan = db.open_table("splits")
|
||||
assert main_plan.version == 2
|
||||
|
||||
# Branch plan version 2 has different contents, so the numeric version alone
|
||||
# does not identify the snapshot.
|
||||
branch_plan = db.open_table("splits", branch="exp")
|
||||
branch_plan.add(
|
||||
pa.table(
|
||||
{
|
||||
"row_id": pa.array([0], type=pa.uint64()),
|
||||
"split_id": pa.array([0], type=pa.uint32()),
|
||||
}
|
||||
)
|
||||
)
|
||||
branch_plan = db.open_table("splits", branch="exp")
|
||||
assert branch_plan.version == 2
|
||||
assert branch_plan.count_rows() == 21
|
||||
branch_plan.tags.create("exp_v2", 2)
|
||||
|
||||
permutation = Permutation.from_tables(tbl, main_plan)
|
||||
|
||||
# Move the same passed-in plan handle to the other branch at the same
|
||||
# numeric version. Pickle must still reopen the captured main snapshot.
|
||||
main_plan.checkout("exp_v2")
|
||||
assert main_plan.current_branch() == "exp"
|
||||
assert main_plan.version == 2
|
||||
payload = pickle.dumps(permutation)
|
||||
|
||||
restored = pickle.loads(payload)
|
||||
assert restored.permutation_table.current_branch() is None
|
||||
assert restored.permutation_table.version == 2
|
||||
assert restored.num_rows == 20
|
||||
|
||||
|
||||
def test_persisted_plan_pickle_reopens_in_spawned_process(tmp_path):
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(12)}))
|
||||
plan = permutation_builder(tbl).persist(db, "splits").execute()
|
||||
payload = pickle.dumps(Permutation.from_tables(tbl, plan))
|
||||
|
||||
tbl.add(pa.table({"id": range(12, 24)}))
|
||||
permutation_builder(tbl).persist(db, "splits", mode="overwrite").execute()
|
||||
|
||||
context = mp.get_context("spawn")
|
||||
output = context.Queue()
|
||||
process = context.Process(
|
||||
target=_read_permutation_in_spawned_process, args=(payload, output)
|
||||
)
|
||||
process.start()
|
||||
try:
|
||||
ids = output.get(timeout=60)
|
||||
finally:
|
||||
process.join(timeout=60)
|
||||
|
||||
assert process.exitcode == 0
|
||||
assert sorted(ids) == list(range(12))
|
||||
|
||||
|
||||
def test_old_permutation_pickle_state_still_round_trips(tmp_path):
|
||||
db = connect(tmp_path)
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = permutation_builder(tbl).execute()
|
||||
state = {
|
||||
"base_table_name": tbl.name,
|
||||
"permutation_data": plan.to_arrow(),
|
||||
"split": 0,
|
||||
"selection": {"id": "id"},
|
||||
"batch_size": DEFAULT_BATCH_SIZE,
|
||||
"transform_fn": Transforms.arrow2python,
|
||||
"offset": None,
|
||||
"limit": None,
|
||||
"connection_factory": None,
|
||||
"base_table_uri": str(tmp_path),
|
||||
"base_table_storage_options": None,
|
||||
"base_table_namespace": [],
|
||||
}
|
||||
|
||||
restored = Permutation.__new__(Permutation)
|
||||
restored.__setstate__(state)
|
||||
|
||||
assert restored.base_version == tbl.version
|
||||
assert restored.base_branch is None
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_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 +655,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 +1561,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(
|
||||
[
|
||||
@@ -435,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):
|
||||
@@ -744,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):
|
||||
@@ -811,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")
|
||||
@@ -1463,18 +2000,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):
|
||||
@@ -2382,6 +2917,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)
|
||||
@@ -2486,6 +3076,86 @@ def test_take_queries(tmp_path):
|
||||
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):
|
||||
@@ -2592,6 +3262,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)
|
||||
|
||||
+1573
-155
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,7 @@ import threading
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lancedb.permutation import Permutation, permutation_builder
|
||||
|
||||
|
||||
# These are all keys that are accepted by storage_options
|
||||
@@ -87,6 +88,36 @@ def test_s3_lifecycle(s3_bucket: str):
|
||||
asyncio.run(test())
|
||||
|
||||
|
||||
@pytest.mark.s3_test
|
||||
def test_s3_permutation_persist_direct_result_pickle(s3_bucket: str):
|
||||
import pickle
|
||||
|
||||
storage_options = copy.copy(CONFIG)
|
||||
uri = f"s3://{s3_bucket}/test_permutation_persist"
|
||||
db = lancedb.connect(uri, storage_options=storage_options)
|
||||
try:
|
||||
tbl = db.create_table("base", pa.table({"id": range(20)}))
|
||||
plan = (
|
||||
permutation_builder(tbl)
|
||||
.split_sequential(fixed=2, split_names=["train", "test"])
|
||||
.persist(db, "splits")
|
||||
.execute()
|
||||
)
|
||||
assert plan._storage_options == storage_options
|
||||
|
||||
restored_plan = pickle.loads(pickle.dumps(plan))
|
||||
assert restored_plan.count_rows() == 20
|
||||
|
||||
permutation = Permutation.from_tables(tbl, plan, split="train")
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
assert restored.num_rows == 10
|
||||
assert sorted(
|
||||
row["id"] for row in restored.__getitems__(list(range(restored.num_rows)))
|
||||
) == list(range(10))
|
||||
finally:
|
||||
db.drop_all_tables()
|
||||
|
||||
|
||||
@pytest.mark.s3_test
|
||||
def test_concurrent_open_table(s3_bucket: str):
|
||||
uri = f"s3://{s3_bucket}/test_concurrent_open_table"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import threading
|
||||
from datetime import timedelta
|
||||
from uuid import UUID
|
||||
|
||||
import numpy as np
|
||||
@@ -13,6 +14,7 @@ from lancedb import _lancedb
|
||||
from lancedb.arrow import AsyncRecordBatchReader
|
||||
from lancedb.db import AsyncConnection
|
||||
from lancedb.remote.db import RemoteDBConnection
|
||||
from lancedb.namespace import AsyncLanceNamespaceDBConnection
|
||||
from lancedb.sql import AsyncQuery, Query, to_parameter_batch
|
||||
|
||||
NIL_QUERY_ID = UUID(int=0)
|
||||
@@ -22,24 +24,46 @@ class FakeNativeQuery:
|
||||
id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef")
|
||||
job_id = None
|
||||
|
||||
def __init__(self):
|
||||
self.cancelled = False
|
||||
|
||||
async def reader(self):
|
||||
return pa.table({"value": [1, 2]})
|
||||
|
||||
async def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
|
||||
class FakeNativeConnection:
|
||||
def __init__(self):
|
||||
self.parameters = []
|
||||
self.options = []
|
||||
|
||||
async def execute_query_async(
|
||||
self, query, *, default_namespace_path=None, parameters=None
|
||||
self,
|
||||
query,
|
||||
*,
|
||||
default_namespace_path=None,
|
||||
parameters=None,
|
||||
timeout=None,
|
||||
read_timeout=None,
|
||||
cancel_on_drop=False,
|
||||
):
|
||||
self.parameters.append(parameters)
|
||||
self.options.append((timeout, read_timeout, cancel_on_drop))
|
||||
return FakeNativeQuery()
|
||||
|
||||
|
||||
class FakeAsyncConnection:
|
||||
async def execute_query_async(
|
||||
self, query, *, default_namespace_path=None, parameters=None
|
||||
self,
|
||||
query,
|
||||
*,
|
||||
default_namespace_path=None,
|
||||
parameters=None,
|
||||
timeout=None,
|
||||
read_timeout=None,
|
||||
cancel_on_drop=False,
|
||||
):
|
||||
return AsyncQuery(FakeNativeQuery())
|
||||
|
||||
@@ -401,3 +425,61 @@ def test_sql_input_error_metadata_crosses_native_boundary(job_id):
|
||||
assert error.grpc_code == 3
|
||||
assert str(error).startswith("No column 'missing' in table events")
|
||||
assert not str(error).startswith("SQL error")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"])
|
||||
async def test_async_sql_execution_controls_are_forwarded(method):
|
||||
native = FakeNativeConnection()
|
||||
connection = AsyncConnection(native)
|
||||
await getattr(connection, method)(
|
||||
"SELECT 1",
|
||||
timeout=timedelta(seconds=30),
|
||||
read_timeout=timedelta(seconds=5),
|
||||
cancel_on_drop=True,
|
||||
)
|
||||
assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"])
|
||||
def test_sync_sql_execution_controls_are_forwarded(method):
|
||||
native = FakeNativeConnection()
|
||||
connection = RemoteDBConnection.__new__(RemoteDBConnection)
|
||||
connection._conn = AsyncConnection(native)
|
||||
getattr(connection, method)(
|
||||
"SELECT 1",
|
||||
timeout=timedelta(seconds=30),
|
||||
read_timeout=timedelta(seconds=5),
|
||||
cancel_on_drop=True,
|
||||
)
|
||||
assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_query_cancellation_reaches_the_native_handle():
|
||||
native = FakeNativeQuery()
|
||||
await AsyncQuery(native).cancel()
|
||||
assert native.cancelled
|
||||
|
||||
|
||||
def test_sync_query_cancellation_reaches_the_native_handle():
|
||||
native = FakeNativeQuery()
|
||||
Query(AsyncQuery(native)).cancel()
|
||||
assert native.cancelled
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["execute_query", "execute_query_async"])
|
||||
async def test_namespace_sql_execution_controls_are_forwarded(method):
|
||||
native = FakeNativeConnection()
|
||||
connection = AsyncLanceNamespaceDBConnection.__new__(
|
||||
AsyncLanceNamespaceDBConnection
|
||||
)
|
||||
connection._inner = AsyncConnection(native)
|
||||
await getattr(connection, method)(
|
||||
"SELECT 1",
|
||||
timeout=timedelta(seconds=30),
|
||||
read_timeout=timedelta(seconds=5),
|
||||
cancel_on_drop=True,
|
||||
)
|
||||
assert native.options == [(timedelta(seconds=30), timedelta(seconds=5), True)]
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import gc
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
import lancedb.table as table_module
|
||||
from lancedb.query import AsyncQuery
|
||||
|
||||
|
||||
def _table(db, name="sync_pull_reader"):
|
||||
return db.create_table(
|
||||
name,
|
||||
data=[{"id": i, "vector": [float(i), float(i)]} for i in range(10)],
|
||||
)
|
||||
|
||||
|
||||
def _spy_on_pull_reader(monkeypatch):
|
||||
calls = []
|
||||
real = AsyncQuery._execute_batches_sync
|
||||
|
||||
def spy(self, *, max_batch_length=None, timeout=None):
|
||||
calls.append((max_batch_length, timeout))
|
||||
return real(self, max_batch_length=max_batch_length, timeout=timeout)
|
||||
|
||||
monkeypatch.setattr(AsyncQuery, "_execute_batches_sync", spy)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_size,row_limit",
|
||||
[
|
||||
(None, 1024),
|
||||
(0, None),
|
||||
(4, 4),
|
||||
],
|
||||
)
|
||||
def test_plain_sync_batches_use_pull_reader(mem_db, monkeypatch, batch_size, row_limit):
|
||||
table = _table(mem_db)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=batch_size)
|
||||
|
||||
assert isinstance(reader, pa.RecordBatchReader)
|
||||
assert calls == [(batch_size, None)]
|
||||
batches = list(reader)
|
||||
assert sum(batch.num_rows for batch in batches) == 10
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == list(range(10))
|
||||
if row_limit is not None:
|
||||
assert all(batch.num_rows <= row_limit for batch in batches)
|
||||
|
||||
|
||||
def test_scan_in_order_routes_through_pull_reader(tmp_db, monkeypatch):
|
||||
table = tmp_db.create_table("ordered_pull_reader", pa.table({"id": [0, 1]}))
|
||||
table.add(pa.table({"id": [2, 3]}))
|
||||
table.add(pa.table({"id": [4, 5]}))
|
||||
table.checkout(table.version)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
reader = table.search().scan_in_order(True).select(["id"]).to_batches(batch_size=2)
|
||||
|
||||
assert calls == [(2, None)]
|
||||
assert [value for batch in reader for value in batch["id"].to_pylist()] == [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
]
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
table.search().scan_in_order(True).order_by("id").to_batches()
|
||||
|
||||
|
||||
def test_plain_sync_batches_do_not_enter_background_loop(mem_db, monkeypatch):
|
||||
table = _table(mem_db)
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise AssertionError("plain sync batches entered the background event loop")
|
||||
|
||||
monkeypatch.setattr(table_module.LOOP, "run", fail)
|
||||
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=4)
|
||||
|
||||
assert sum(batch.num_rows for batch in reader) == 10
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"execute",
|
||||
[
|
||||
lambda table: table.search().select(["id"]).to_arrow(),
|
||||
lambda table: table.search([0.0, 0.0]).to_batches(),
|
||||
lambda table: table.take_offsets([0]).to_batches(),
|
||||
lambda table: table.search().select(["id"]).order_by(["id"]).to_batches(),
|
||||
lambda table: (
|
||||
table.search().select(["id"]).to_batches(blob_mode="descriptions")
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_other_sync_routes_keep_the_existing_reader(mem_db, monkeypatch, execute):
|
||||
table = _table(mem_db)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
execute(table)
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_batches_keep_the_existing_reader(monkeypatch):
|
||||
db = await lancedb.connect_async("memory://")
|
||||
table = await db.create_table(
|
||||
"async_sync_pull_reader", data=[{"id": i} for i in range(4)]
|
||||
)
|
||||
calls = _spy_on_pull_reader(monkeypatch)
|
||||
|
||||
reader = await table.query().to_batches()
|
||||
|
||||
total_rows = 0
|
||||
async for batch in reader:
|
||||
total_rows += batch.num_rows
|
||||
assert total_rows == 4
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_timeout_starts_on_first_read_and_spans_reads(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"timeout_pull_reader", data=[{"id": i} for i in range(8)]
|
||||
)
|
||||
reader = (
|
||||
table.search()
|
||||
.select(["id"])
|
||||
.to_batches(batch_size=2, timeout=timedelta(milliseconds=200))
|
||||
)
|
||||
|
||||
# A slow consumer before the first poll must not count against the query:
|
||||
# the timeout starts when the first batch is requested.
|
||||
time.sleep(0.25)
|
||||
first = reader.read_next_batch()
|
||||
assert first.num_rows == 2
|
||||
|
||||
# The deadline spans reads, so a pause between batches expires it.
|
||||
time.sleep(0.25)
|
||||
with pytest.raises(RuntimeError, match="Query timeout"):
|
||||
reader.read_next_batch()
|
||||
|
||||
|
||||
def test_early_break_can_resume_the_same_reader(mem_db):
|
||||
table = _table(mem_db)
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=2)
|
||||
|
||||
first = next(iter(reader))
|
||||
rest = list(reader)
|
||||
|
||||
assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
|
||||
range(10)
|
||||
)
|
||||
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=2)
|
||||
for first in reader:
|
||||
break
|
||||
rest = list(reader)
|
||||
assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
|
||||
range(10)
|
||||
)
|
||||
|
||||
|
||||
def test_arrow_export_shares_cursor_with_the_last_owner(mem_db):
|
||||
table = _table(mem_db)
|
||||
reader = table.search().select(["id"]).to_batches(batch_size=2)
|
||||
first = reader.read_next_batch()
|
||||
|
||||
capsule = reader.__arrow_c_stream__()
|
||||
del reader
|
||||
gc.collect()
|
||||
|
||||
imported = pa.RecordBatchReader._import_from_c_capsule(capsule)
|
||||
rest = imported.read_all()
|
||||
combined = pa.concat_tables([pa.Table.from_batches([first]), rest])
|
||||
assert combined.column("id").to_pylist() == list(range(10))
|
||||
|
||||
|
||||
def test_empty_result_preserves_the_query_schema(mem_db):
|
||||
table = _table(mem_db)
|
||||
query = table.search().select(["id"]).where("id < 0")
|
||||
|
||||
reader = query.to_batches(batch_size=4)
|
||||
|
||||
assert reader.schema == query.output_schema()
|
||||
assert reader.read_all().num_rows == 0
|
||||
@@ -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",
|
||||
@@ -1250,6 +1373,270 @@ def test_versioning(mem_db: DBConnection):
|
||||
assert len(table) == 2
|
||||
|
||||
|
||||
def test_delta_streams_and_pins_endpoints(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"delta",
|
||||
data=[
|
||||
{"id": 1, "value": 0},
|
||||
{"id": 2, "value": 0},
|
||||
],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
|
||||
table.add([{"id": 3, "value": 0}])
|
||||
table.tags.create("baseline", 2)
|
||||
table.update(where="id = 1", values_sql={"value": "value + 10"})
|
||||
table.delete("id = 2")
|
||||
assert table.version == 4
|
||||
|
||||
delta = table.delta(1)
|
||||
assert delta.begin_version == 1
|
||||
assert delta.end_version == 4
|
||||
|
||||
inserted = delta.inserted_rows().read_all()
|
||||
assert inserted["id"].to_pylist() == [3]
|
||||
assert inserted.schema.names == [
|
||||
"id",
|
||||
"value",
|
||||
"_rowid",
|
||||
"_row_created_at_version",
|
||||
"_row_last_updated_at_version",
|
||||
]
|
||||
|
||||
updated = delta.updated_rows().read_all()
|
||||
assert updated["id"].to_pylist() == [1]
|
||||
assert updated["value"].to_pylist() == [10]
|
||||
|
||||
upserted = delta.upserted_rows().read_all()
|
||||
assert sorted(upserted["id"].to_pylist()) == [1, 3]
|
||||
|
||||
deleted = delta.deleted_row_ids().read_all()
|
||||
assert deleted.schema.names == ["_rowid"]
|
||||
assert deleted.schema.field("_rowid").type == pa.uint64()
|
||||
assert deleted.num_rows == 1
|
||||
|
||||
transactions = delta.list_transactions()
|
||||
assert [transaction["operation"] for transaction in transactions] == [
|
||||
"Append",
|
||||
"Update",
|
||||
"Delete",
|
||||
]
|
||||
assert transactions[0]["read_version"] == 1
|
||||
|
||||
# Tags are resolved on the current branch and can be either endpoint.
|
||||
from_tag = table.delta("baseline")
|
||||
assert from_tag.begin_version == 2
|
||||
assert from_tag.end_version == 4
|
||||
assert from_tag.updated_rows().read_all()["id"].to_pylist() == [1]
|
||||
|
||||
to_tag = table.delta(1, "baseline")
|
||||
assert to_tag.end_version == 2
|
||||
assert to_tag.inserted_rows().read_all()["id"].to_pylist() == [3]
|
||||
|
||||
# Equal valid versions keep the reader schemas even when no rows change.
|
||||
equal = table.delta(2, 2)
|
||||
empty_inserted = equal.inserted_rows().read_all()
|
||||
assert empty_inserted.num_rows == 0
|
||||
assert empty_inserted.schema == inserted.schema
|
||||
empty_deleted = equal.deleted_row_ids().read_all()
|
||||
assert empty_deleted.num_rows == 0
|
||||
assert empty_deleted.schema.names == ["_rowid"]
|
||||
|
||||
# Reversed, zero, missing, and missing-tag endpoints are input errors.
|
||||
with pytest.raises(ValueError, match="newer than"):
|
||||
table.delta(4, 2)
|
||||
with pytest.raises(ValueError, match="start at 1"):
|
||||
table.delta(0)
|
||||
with pytest.raises(ValueError, match="does not exist"):
|
||||
table.delta(999)
|
||||
with pytest.raises(ValueError, match="does not exist"):
|
||||
table.delta("missing-tag")
|
||||
|
||||
# An omitted target follows the visible checkout and leaves the shared
|
||||
# checkout in place.
|
||||
table.checkout(2)
|
||||
checked_out = table.delta(1)
|
||||
assert checked_out.end_version == 2
|
||||
assert checked_out.inserted_rows().read_all()["id"].to_pylist() == [3]
|
||||
assert table.version == 2
|
||||
|
||||
# An explicit target works from a pinned handle without moving it.
|
||||
explicit = table.delta(1, 3)
|
||||
assert explicit.updated_rows().read_all()["id"].to_pylist() == [1]
|
||||
assert table.version == 2
|
||||
table.checkout_latest()
|
||||
assert table.version == 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ["update", "delete"])
|
||||
def test_delta_rejects_restore_ranges(tmp_path, mutation):
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"restore_delta",
|
||||
[{"id": 1, "value": 0}],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
if mutation == "update":
|
||||
table.update(values={"value": 10})
|
||||
else:
|
||||
table.delete("id = 1")
|
||||
assert table.version == 2
|
||||
|
||||
table.restore(1)
|
||||
assert table.version == 3
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1, "value": 0}]
|
||||
|
||||
restore_range = table.delta(2, 3)
|
||||
assert [tx["operation"] for tx in restore_range.list_transactions()] == ["Restore"]
|
||||
for reader in (
|
||||
restore_range.inserted_rows,
|
||||
restore_range.updated_rows,
|
||||
restore_range.upserted_rows,
|
||||
restore_range.deleted_row_ids,
|
||||
):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
reader()
|
||||
message = str(exc_info.value)
|
||||
assert "Restore" in message
|
||||
assert "full rescan" in message
|
||||
assert "reinitialize" in message
|
||||
|
||||
# A restore in the middle of the range is still unverifiable.
|
||||
table.add([{"id": 2, "value": 0}])
|
||||
assert table.version == 4
|
||||
with pytest.raises(ValueError, match="Restore"):
|
||||
table.delta(2, 4).upserted_rows()
|
||||
|
||||
# A restore at the exclusive boundary is the base snapshot, so later
|
||||
# changes remain usable.
|
||||
after_restore = table.delta(3, 4)
|
||||
assert after_restore.inserted_rows().read_all()["id"].to_pylist() == [2]
|
||||
assert [tx["operation"] for tx in after_restore.list_transactions()] == ["Append"]
|
||||
|
||||
# Equal endpoints remain empty and do not run the restore guard.
|
||||
equal = table.delta(3, 3)
|
||||
assert equal.inserted_rows().read_all().num_rows == 0
|
||||
|
||||
|
||||
def test_delta_rejects_restore_after_same_uri_recreate(tmp_path):
|
||||
stable = {"new_table_enable_stable_row_ids": "true"}
|
||||
old_db = lancedb.connect(tmp_path)
|
||||
old = old_db.create_table("t", [{"id": 1, "value": 0}], storage_options=stable)
|
||||
old.add([{"id": 2, "value": 0}])
|
||||
old.add([{"id": 3, "value": 0}])
|
||||
assert [tx["operation"] for tx in old.delta(2, 3).list_transactions()] == ["Append"]
|
||||
|
||||
writer_db = lancedb.connect(tmp_path)
|
||||
writer_db.drop_table("t")
|
||||
schema = pa.schema(
|
||||
[("id", pa.int32()), ("value", pa.int32())],
|
||||
metadata={"padding": "x" * (256 * 1024)},
|
||||
)
|
||||
recreated = writer_db.create_table(
|
||||
"t",
|
||||
pa.Table.from_pylist([{"id": 1, "value": 0}], schema=schema),
|
||||
storage_options=stable,
|
||||
)
|
||||
recreated.update(values={"value": 10})
|
||||
recreated.restore(1)
|
||||
assert [tx["operation"] for tx in recreated.delta(2, 3).list_transactions()] == [
|
||||
"Restore"
|
||||
]
|
||||
|
||||
delta = old_db.open_table("t").delta(2, 3)
|
||||
assert [tx["operation"] for tx in delta.list_transactions()] == ["Restore"]
|
||||
with pytest.raises(ValueError, match="Restore"):
|
||||
delta.upserted_rows()
|
||||
|
||||
|
||||
def test_delta_requires_stable_row_ids(mem_db: DBConnection):
|
||||
table = mem_db.create_table("delta_no_stable", data=[{"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
delta = table.delta(1)
|
||||
|
||||
for reader in (
|
||||
delta.inserted_rows,
|
||||
delta.updated_rows,
|
||||
delta.upserted_rows,
|
||||
delta.deleted_row_ids,
|
||||
):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
reader()
|
||||
message = str(exc_info.value)
|
||||
assert "new_table_enable_stable_row_ids" in message
|
||||
assert "list_transactions" in message
|
||||
|
||||
# Transactions remain available without stable row ids.
|
||||
transactions = delta.list_transactions()
|
||||
assert [transaction["operation"] for transaction in transactions] == ["Append"]
|
||||
|
||||
# Equal endpoints need no row lineage, so they are empty rather than
|
||||
# rejected.
|
||||
version = table.version
|
||||
equal = table.delta(version, version)
|
||||
assert equal.inserted_rows().read_all().num_rows == 0
|
||||
assert equal.deleted_row_ids().read_all().num_rows == 0
|
||||
|
||||
|
||||
def test_delta_rejects_cross_branch_tags(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table(
|
||||
"delta_branches",
|
||||
data=[{"id": 0}],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
branch = table.branches.create("exp")
|
||||
branch.add([{"id": 1}])
|
||||
table.add([{"id": 100}, {"id": 101}, {"id": 102}])
|
||||
assert branch.version == table.version
|
||||
|
||||
table.tags.create("main_tag", table.version)
|
||||
branch.tags.create("exp_tag", branch.version)
|
||||
|
||||
# The same-branch tag resolves through the branch, not main's data at the
|
||||
# same version number.
|
||||
delta = branch.delta(1, "exp_tag")
|
||||
assert delta.inserted_rows().read_all()["id"].to_pylist() == [1]
|
||||
|
||||
# Cross-branch tags are rejected even though the version number exists on
|
||||
# both branches.
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
branch.delta("main_tag")
|
||||
message = str(exc_info.value)
|
||||
assert "main_tag" in message
|
||||
assert "main" in message
|
||||
assert "exp" in message
|
||||
|
||||
with pytest.raises(ValueError, match="exp_tag"):
|
||||
table.delta("exp_tag")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_delta(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"async_delta",
|
||||
data=[{"id": 1}],
|
||||
storage_options={"new_table_enable_stable_row_ids": "true"},
|
||||
)
|
||||
await table.add([{"id": 2}])
|
||||
|
||||
delta = await table.delta(1)
|
||||
assert delta.begin_version == 1
|
||||
assert delta.end_version == 2
|
||||
|
||||
reader = await delta.inserted_rows()
|
||||
inserted = await reader.read_all()
|
||||
assert inserted[0]["id"].to_pylist() == [2]
|
||||
|
||||
transactions = await delta.list_transactions()
|
||||
assert [transaction["operation"] for transaction in transactions] == ["Append"]
|
||||
|
||||
equal = await table.delta(2, 2)
|
||||
reader = await equal.inserted_rows()
|
||||
assert await reader.read_all() == []
|
||||
|
||||
|
||||
def test_tags(mem_db: DBConnection):
|
||||
table = mem_db.create_table(
|
||||
"test",
|
||||
@@ -1303,6 +1690,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 +1769,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 +1836,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 +2187,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))
|
||||
@@ -1758,7 +2312,7 @@ async def test_async_open_table_with_branch_version(tmp_path):
|
||||
def test_create_index_async_returns_done_job(mem_db: DBConnection):
|
||||
table = mem_db.create_table("job_test", [{"id": i} for i in range(10)])
|
||||
job = table.create_index_async("id", config=BTree())
|
||||
assert job.id is None
|
||||
assert job.id() is None
|
||||
assert job.wait() is None
|
||||
assert len(table.list_indices()) == 1
|
||||
job.cancel()
|
||||
@@ -6011,8 +6565,8 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
|
||||
({"max_concurrency": 4}, "max_concurrency"),
|
||||
({"publication_interval_rows": 60}, "publication_interval_rows"),
|
||||
(
|
||||
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
|
||||
"resource_budget",
|
||||
{"total_cpu_millis": 1000, "total_memory_bytes": 1024},
|
||||
"total_cpu_millis",
|
||||
),
|
||||
(
|
||||
{
|
||||
@@ -6092,7 +6646,7 @@ def test_refresh_column_async_returns_job(tmp_path, batch_size):
|
||||
table.add_columns(computed={"doubled": "x * 2"})
|
||||
|
||||
job = table.refresh_column_async("doubled", batch_size=batch_size)
|
||||
assert job.id is None # in-process jobs have no server id
|
||||
assert job.id() is None # in-process jobs have no server id
|
||||
result = job.wait()
|
||||
assert isinstance(result, lancedb.RefreshColumnResult)
|
||||
assert result.rows_assigned == 2
|
||||
@@ -6310,10 +6864,8 @@ def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
|
||||
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,
|
||||
},
|
||||
total_cpu_millis=1_000,
|
||||
total_memory_bytes=1_024,
|
||||
)
|
||||
assert table.version == before
|
||||
assert table.schema.names == ["x"]
|
||||
@@ -6414,3 +6966,24 @@ def test_fts_exist_ok_matches_quoted_default_name(mem_db):
|
||||
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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -51,21 +51,42 @@ class MockPermutationServer:
|
||||
the server, which is the part that has to stay compatible.
|
||||
"""
|
||||
|
||||
def __init__(self, name="remote_data", num_rows=8, vary_scan_order=False):
|
||||
def __init__(
|
||||
self, name="remote_data", num_rows=8, vary_scan_order=False, latest_version=1
|
||||
):
|
||||
self.name = name
|
||||
self.num_rows = num_rows
|
||||
self.latest_version = latest_version
|
||||
self.version_rows = {1: list(range(num_rows))}
|
||||
self.describe_bodies = []
|
||||
self.query_bodies = []
|
||||
# Stand in for a distributed scan that answers in no fixed order.
|
||||
self.vary_scan_order = vary_scan_order
|
||||
self.scan_calls = 0
|
||||
|
||||
def publish_version(self, version, row_ids):
|
||||
"""Advance the mock's latest version without changing its schema."""
|
||||
self.latest_version = version
|
||||
self.version_rows[version] = list(row_ids)
|
||||
|
||||
def _rows_for_version(self, requested_version):
|
||||
version = (
|
||||
self.latest_version if requested_version is None else requested_version
|
||||
)
|
||||
return self.version_rows.get(version, self.version_rows[1])
|
||||
|
||||
def __call__(self, request):
|
||||
path = request.path
|
||||
if path == f"/v1/table/{self.name}/describe/":
|
||||
body = self._read_body(request)
|
||||
self.describe_bodies.append(body)
|
||||
version = (
|
||||
self.latest_version if body.get("version") is None else body["version"]
|
||||
)
|
||||
return self._json(
|
||||
request,
|
||||
{
|
||||
"version": 1,
|
||||
"version": version,
|
||||
"schema": {
|
||||
"fields": [
|
||||
{"name": "id", "type": {"type": "int64"}, "nullable": False}
|
||||
@@ -78,8 +99,8 @@ class MockPermutationServer:
|
||||
# Null spec: this table has no RTE write path.
|
||||
return self._json(request, {"rte_spec": None})
|
||||
if path == f"/v1/table/{self.name}/count_rows/":
|
||||
self._read_body(request)
|
||||
return self._json(request, self.num_rows)
|
||||
body = self._read_body(request)
|
||||
return self._json(request, len(self._rows_for_version(body.get("version"))))
|
||||
if path == f"/v1/table/{self.name}/query/":
|
||||
return self._query(request, self._read_body(request))
|
||||
|
||||
@@ -124,10 +145,15 @@ class MockPermutationServer:
|
||||
|
||||
def _query(self, request, body):
|
||||
self.query_bodies.append(body)
|
||||
version_rows = self._rows_for_version(body.get("version"))
|
||||
|
||||
if is_row_id_take(body):
|
||||
# A row-id take. Answer ascending, so tests prove the client reorders.
|
||||
row_ids = sorted(parse_in_list(body["filter"]))
|
||||
row_ids = sorted(
|
||||
row_id
|
||||
for row_id in parse_in_list(body["filter"])
|
||||
if row_id in version_rows
|
||||
)
|
||||
return self._arrow(
|
||||
request,
|
||||
pa.table(
|
||||
@@ -140,7 +166,7 @@ class MockPermutationServer:
|
||||
|
||||
if body.get("columns") == ["_rowid"]:
|
||||
# The permutation build scan: row ids and nothing else.
|
||||
row_ids = list(range(self.num_rows))
|
||||
row_ids = list(version_rows)
|
||||
if self.vary_scan_order and self.scan_calls % 2:
|
||||
row_ids.reverse()
|
||||
self.scan_calls += 1
|
||||
|
||||
+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,
|
||||
)))
|
||||
}
|
||||
|
||||
+222
-8
@@ -20,6 +20,7 @@ use arrow::{
|
||||
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
|
||||
};
|
||||
use lancedb::{
|
||||
BasePath,
|
||||
connection::Connection as LanceConnection,
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
@@ -30,9 +31,9 @@ use lancedb::{
|
||||
};
|
||||
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(
|
||||
@@ -56,6 +57,139 @@ fn materialized_view_builder(
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
@@ -241,19 +375,29 @@ impl Connection {
|
||||
self.get_inner().map(|inner| inner.uri().to_string())
|
||||
}
|
||||
|
||||
#[pyo3(signature = (query, *, default_namespace_path=None, parameters=None))]
|
||||
#[pyo3(signature = (query, *, default_namespace_path=None, parameters=None, timeout=None, read_timeout=None, cancel_on_drop=false))]
|
||||
pub fn execute_query_async<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
query: String,
|
||||
default_namespace_path: Option<Bound<'_, PyAny>>,
|
||||
parameters: Option<PyArrowType<RecordBatch>>,
|
||||
timeout: Option<Duration>,
|
||||
read_timeout: Option<Duration>,
|
||||
cancel_on_drop: bool,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let default_namespace_path = parse_default_namespace_path(default_namespace_path)?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut operation = inner
|
||||
.execute_query_async(query)
|
||||
.default_namespace_path(default_namespace_path);
|
||||
.default_namespace_path(default_namespace_path)
|
||||
.cancel_on_drop(cancel_on_drop);
|
||||
if let Some(timeout) = timeout {
|
||||
operation = operation.timeout(timeout);
|
||||
}
|
||||
if let Some(timeout) = read_timeout {
|
||||
operation = operation.read_timeout(timeout);
|
||||
}
|
||||
if let Some(PyArrowType(parameters)) = parameters {
|
||||
operation = operation.parameters(parameters);
|
||||
}
|
||||
@@ -311,7 +455,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,
|
||||
@@ -321,11 +465,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)?);
|
||||
@@ -333,6 +480,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);
|
||||
@@ -359,7 +512,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,
|
||||
@@ -369,11 +522,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)?;
|
||||
|
||||
@@ -382,6 +537,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);
|
||||
@@ -507,7 +665,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[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))]
|
||||
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None, *, query=None, exist_ok=false))]
|
||||
pub fn create_materialized_view(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
@@ -518,6 +676,12 @@ impl Connection {
|
||||
with_no_data: bool,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
|
||||
query: Option<String>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
@@ -537,6 +701,22 @@ impl Connection {
|
||||
if let Some(seconds) = auto_refresh_interval_seconds {
|
||||
builder = builder.auto_refresh_interval_seconds(seconds);
|
||||
}
|
||||
if let Some(value) = total_cpu_millis {
|
||||
builder = builder.total_cpu_millis(value);
|
||||
}
|
||||
if let Some(value) = total_memory_bytes {
|
||||
builder = builder.total_memory_bytes(value);
|
||||
}
|
||||
if let Some(value) = total_gpu_count {
|
||||
builder = builder.total_gpu_count(value);
|
||||
}
|
||||
if let Some(value) = gpu_class {
|
||||
builder = builder.gpu_class(value);
|
||||
}
|
||||
if let Some(value) = gpu_count {
|
||||
builder = builder.gpu_count(value);
|
||||
}
|
||||
|
||||
if let Some(projections) = projections {
|
||||
builder = builder.select(projections);
|
||||
}
|
||||
@@ -553,7 +733,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[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))]
|
||||
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None, *, query=None, exist_ok=false))]
|
||||
pub fn create_materialized_view_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
@@ -564,6 +744,12 @@ impl Connection {
|
||||
with_no_data: bool,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<f64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
total_memory_bytes: Option<u64>,
|
||||
total_gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
|
||||
query: Option<String>,
|
||||
exist_ok: bool,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
@@ -583,6 +769,22 @@ impl Connection {
|
||||
if let Some(seconds) = auto_refresh_interval_seconds {
|
||||
builder = builder.auto_refresh_interval_seconds(seconds);
|
||||
}
|
||||
if let Some(value) = total_cpu_millis {
|
||||
builder = builder.total_cpu_millis(value);
|
||||
}
|
||||
if let Some(value) = total_memory_bytes {
|
||||
builder = builder.total_memory_bytes(value);
|
||||
}
|
||||
if let Some(value) = total_gpu_count {
|
||||
builder = builder.total_gpu_count(value);
|
||||
}
|
||||
if let Some(value) = gpu_class {
|
||||
builder = builder.gpu_class(value);
|
||||
}
|
||||
if let Some(value) = gpu_count {
|
||||
builder = builder.gpu_count(value);
|
||||
}
|
||||
|
||||
if let Some(projections) = projections {
|
||||
builder = builder.select(projections);
|
||||
}
|
||||
@@ -902,6 +1104,18 @@ impl Connection {
|
||||
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("cleanup") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CleanupResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
Some("compact") => Ok(crate::job::Job::new_typed(
|
||||
job.into_typed::<lancedb::table::CompactionResult>()
|
||||
.infer_error()?,
|
||||
)),
|
||||
_ => Ok(crate::job::Job::new(job)),
|
||||
}
|
||||
})
|
||||
|
||||
+17
-2
@@ -10,7 +10,7 @@ use lancedb::index::{
|
||||
Index as LanceDbIndex,
|
||||
scalar::{
|
||||
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
|
||||
ZoneMapIndexBuilder,
|
||||
RTreeIndexBuilder, ZoneMapIndexBuilder,
|
||||
},
|
||||
};
|
||||
use pyo3::IntoPyObject;
|
||||
@@ -119,6 +119,16 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
"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 {
|
||||
@@ -293,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, ZoneMap, 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
|
||||
))),
|
||||
}
|
||||
@@ -327,6 +337,11 @@ struct FtsParams {
|
||||
index_operators: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
struct RTreeParams {
|
||||
page_size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
struct IvfFlatParams {
|
||||
distance_type: String,
|
||||
|
||||
+178
-4
@@ -2,16 +2,20 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::runtime::future_into_py;
|
||||
use arrow::{
|
||||
datatypes::Schema,
|
||||
pyarrow::{IntoPyArrow, Table as PyArrowTable},
|
||||
};
|
||||
use lancedb::job::JobEventsRequest;
|
||||
use lancedb::job::{
|
||||
FunctionProfile, FunctionProfileKind, FunctionProfileOptions, FunctionProfileWaitOptions,
|
||||
JobEventsRequest,
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, Py, PyAny, PyRef, PyResult, Python,
|
||||
exceptions::PyValueError,
|
||||
exceptions::{PyTimeoutError, PyValueError},
|
||||
pyclass, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods},
|
||||
};
|
||||
@@ -21,6 +25,17 @@ use crate::error::PythonErrorExt;
|
||||
|
||||
const REPR_INDENT: &str = " ";
|
||||
|
||||
fn profile_json(result: lancedb::Result<FunctionProfile>) -> PyResult<String> {
|
||||
let profile = result.infer_error()?;
|
||||
serde_json::to_string(&profile)
|
||||
.map_err(|error| PyValueError::new_err(format!("invalid profile metadata: {error}")))
|
||||
}
|
||||
|
||||
fn profile_duration(seconds: f64) -> PyResult<Duration> {
|
||||
Duration::try_from_secs_f64(seconds)
|
||||
.map_err(|_| PyValueError::new_err("profile durations must be finite and nonnegative"))
|
||||
}
|
||||
|
||||
/// Parse a stored JSON payload into Python data. The bindings carry these as
|
||||
/// strings because that is what crosses the boundary cheaply; the public
|
||||
/// Python surface is the parsed form.
|
||||
@@ -81,6 +96,43 @@ impl Job {
|
||||
self.inner.id().map(str::to_string)
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn job_id(&self) -> Option<String> {
|
||||
self.inner.job_id()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn operation_id(&self) -> Option<String> {
|
||||
self.inner.operation_id()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn attempt(&self) -> Option<u32> {
|
||||
self.inner.attempt()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn retry_of(&self) -> Option<String> {
|
||||
self.inner.retry_of()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn lifecycle_state(&self) -> Option<String> {
|
||||
self.inner
|
||||
.lifecycle_state()
|
||||
.map(|state| state.as_str().to_string())
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn source_table_version(&self) -> Option<u64> {
|
||||
self.inner.source_table_version()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn execution_epoch(&self) -> Option<i64> {
|
||||
self.inner.execution_epoch()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
pub fn job_type(&self) -> Option<String> {
|
||||
self.inner.job_type()
|
||||
@@ -132,6 +184,15 @@ impl Job {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn retry(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
Ok(Self {
|
||||
inner: Arc::new(inner.retry().await.infer_error()?),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn refresh(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -159,19 +220,98 @@ impl Job {
|
||||
})
|
||||
}
|
||||
|
||||
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())
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (worker_id, *, kind="cpu", duration_seconds=None, session_slot=0))]
|
||||
pub fn capture_profile<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
worker_id: String,
|
||||
kind: &str,
|
||||
duration_seconds: Option<f64>,
|
||||
session_slot: usize,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let kind: FunctionProfileKind = serde_json::from_value(serde_json::json!(kind))
|
||||
.map_err(|_| PyValueError::new_err("kind must be 'cpu', 'memory' or 'gpu'"))?;
|
||||
let mut options = FunctionProfileOptions::new(kind).session_slot(session_slot);
|
||||
if let Some(seconds) = duration_seconds {
|
||||
options = options.duration(profile_duration(seconds)?);
|
||||
}
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
profile_json(inner.capture_profile(worker_id, options).await)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn profile_status(
|
||||
self_: PyRef<'_, Self>,
|
||||
profile_id: String,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
profile_json(inner.profile_status(profile_id).await)
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (profile_id, *, timeout_seconds=None, poll_interval_seconds=None))]
|
||||
pub fn wait_for_profile(
|
||||
self_: PyRef<'_, Self>,
|
||||
profile_id: String,
|
||||
timeout_seconds: Option<f64>,
|
||||
poll_interval_seconds: Option<f64>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut options = FunctionProfileWaitOptions::new();
|
||||
if let Some(seconds) = timeout_seconds {
|
||||
options = options.timeout(profile_duration(seconds)?);
|
||||
}
|
||||
if let Some(seconds) = poll_interval_seconds {
|
||||
options = options.poll_interval(profile_duration(seconds)?);
|
||||
}
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
match inner.wait_for_profile(profile_id, options).await {
|
||||
Err(lancedb::Error::Timeout { message }) => Err(PyTimeoutError::new_err(message)),
|
||||
result => profile_json(result),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn profile_artifact(
|
||||
self_: PyRef<'_, Self>,
|
||||
profile_id: String,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
Ok(inner
|
||||
.profile_artifact(profile_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))]
|
||||
#[pyo3(signature = (*, limit=None, filter=None, page_token=None))]
|
||||
pub fn events(
|
||||
self_: PyRef<'_, Self>,
|
||||
limit: Option<u32>,
|
||||
filter: Option<String>,
|
||||
page_token: Option<String>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
let request = JobEventsRequest { limit, filter };
|
||||
let request = JobEventsRequest {
|
||||
limit,
|
||||
filter,
|
||||
page_token,
|
||||
};
|
||||
future_into_py(self_.py(), async move {
|
||||
let batches = inner.events(request).await.infer_error()?;
|
||||
Python::attach(|py| {
|
||||
@@ -196,6 +336,18 @@ pub struct JobInfo {
|
||||
job_type: String,
|
||||
state: String,
|
||||
created_at_millis: i64,
|
||||
/// Terminal timestamp in milliseconds since the epoch, when known.
|
||||
completed_at_millis: Option<i64>,
|
||||
/// Creation-to-completion wall time, including queueing and pauses.
|
||||
duration_millis: Option<i64>,
|
||||
/// Affected columns; empty when unavailable or not column-scoped.
|
||||
columns: Vec<String>,
|
||||
/// Pinned Function catalog name, with namespace segments joined by `$`.
|
||||
function_name: Option<String>,
|
||||
/// Pinned Function version, when known.
|
||||
function_version: Option<String>,
|
||||
/// Durable failure summary, when available.
|
||||
failure: Option<JobFailureInfo>,
|
||||
_progress_json: Option<String>,
|
||||
paused: bool,
|
||||
}
|
||||
@@ -232,6 +384,12 @@ impl From<lancedb::database::JobInfo> for JobInfo {
|
||||
job_type: info.job_type,
|
||||
state: info.state,
|
||||
created_at_millis: info.created_at_millis,
|
||||
completed_at_millis: info.completed_at_millis,
|
||||
duration_millis: info.duration_millis,
|
||||
columns: info.columns,
|
||||
function_name: info.function_name,
|
||||
function_version: info.function_version,
|
||||
failure: info.failure.map(Into::into),
|
||||
_progress_json: Some(progress),
|
||||
paused: info.paused,
|
||||
}
|
||||
@@ -294,6 +452,13 @@ impl JobFailureInfo {
|
||||
#[derive(Clone)]
|
||||
pub struct JobDescription {
|
||||
job_id: String,
|
||||
attempt_job_id: Option<String>,
|
||||
operation_id: Option<String>,
|
||||
attempt: Option<u32>,
|
||||
retry_of: Option<String>,
|
||||
lifecycle_state: Option<String>,
|
||||
source_table_version: Option<u64>,
|
||||
execution_epoch: Option<i64>,
|
||||
job_type: String,
|
||||
state: String,
|
||||
creation_ms: i64,
|
||||
@@ -356,6 +521,15 @@ impl From<lancedb::database::JobDescription> for JobDescription {
|
||||
let progress_json = description.progress_snapshot().to_string();
|
||||
Self {
|
||||
job_id: description.job_id,
|
||||
attempt_job_id: description.attempt_job_id,
|
||||
operation_id: description.operation_id,
|
||||
attempt: description.attempt,
|
||||
retry_of: description.retry_of,
|
||||
lifecycle_state: description
|
||||
.lifecycle_state
|
||||
.map(|state| state.as_str().to_string()),
|
||||
source_table_version: description.source_table_version,
|
||||
execution_epoch: description.execution_epoch,
|
||||
job_type: description.job_type,
|
||||
state: description.state,
|
||||
creation_ms: description.creation_ms,
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod query;
|
||||
pub mod runtime;
|
||||
pub mod session;
|
||||
pub mod sql;
|
||||
mod sync_stream;
|
||||
pub mod table;
|
||||
pub mod util;
|
||||
|
||||
@@ -97,6 +98,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(catalog::connect_catalog, m)?)?;
|
||||
m.add_class::<Session>()?;
|
||||
m.add_class::<Table>()?;
|
||||
m.add_class::<table::TableDelta>()?;
|
||||
m.add_class::<crate::oauth::PyOAuthSession>()?;
|
||||
m.add_class::<crate::oauth::PySessionStatus>()?;
|
||||
m.add_class::<crate::oauth::PySessionLogout>()?;
|
||||
@@ -113,6 +115,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<HybridQuery>()?;
|
||||
m.add_class::<VectorQuery>()?;
|
||||
m.add_class::<RecordBatchStream>()?;
|
||||
m.add_class::<sync_stream::SyncRecordBatchStream>()?;
|
||||
m.add_class::<AddColumnsResult>()?;
|
||||
m.add_class::<RefreshColumnResult>()?;
|
||||
m.add_class::<FunctionErrors>()?;
|
||||
|
||||
@@ -9,7 +9,10 @@ use crate::{
|
||||
use arrow::pyarrow::{PyArrowType, ToPyArrow};
|
||||
use lancedb::{
|
||||
dataloader::permutation::{
|
||||
builder::{PermutationBuilder as LancePermutationBuilder, ShuffleStrategy},
|
||||
builder::{
|
||||
PermutationBuilder as LancePermutationBuilder, PermutationPersistMode,
|
||||
PermutationPersistOptions, ShuffleStrategy,
|
||||
},
|
||||
reader::PermutationReader,
|
||||
split::{SplitSizes, SplitStrategy},
|
||||
},
|
||||
@@ -17,7 +20,7 @@ use lancedb::{
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, PyAny, PyRef, PyRefMut, PyResult, Python,
|
||||
exceptions::PyRuntimeError,
|
||||
exceptions::{PyRuntimeError, PyValueError},
|
||||
pyclass, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods, PyType},
|
||||
};
|
||||
@@ -123,14 +126,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 {
|
||||
@@ -246,6 +250,37 @@ impl PyAsyncPermutationBuilder {
|
||||
slf.modify(|builder| builder.with_filter(filter))
|
||||
}
|
||||
|
||||
/// Store the permutation table in a database.
|
||||
///
|
||||
/// This is only supported for embedded databases. The destination table is
|
||||
/// created in the selected namespace, and an existing table is replaced only
|
||||
/// when ``mode="overwrite"`` is explicit.
|
||||
#[pyo3(signature = (db, table_name, *, namespace_path=None, mode="create"))]
|
||||
pub fn persist(
|
||||
slf: PyRefMut<'_, Self>,
|
||||
db: PyRef<'_, crate::connection::Connection>,
|
||||
table_name: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
mode: &str,
|
||||
) -> PyResult<Self> {
|
||||
let mode = match mode {
|
||||
"create" => PermutationPersistMode::Create,
|
||||
"overwrite" => PermutationPersistMode::Overwrite,
|
||||
other => {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"Invalid mode {other}; expected 'create' or 'overwrite'"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let database = db.database()?;
|
||||
let options = PermutationPersistOptions {
|
||||
namespace_path: namespace_path.unwrap_or_default(),
|
||||
mode,
|
||||
};
|
||||
|
||||
slf.modify(|builder| builder.persist_with_options(database, table_name, options))
|
||||
}
|
||||
|
||||
pub fn execute(slf: PyRefMut<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut state = slf.state.lock().unwrap();
|
||||
let builder = state
|
||||
|
||||
+167
-7
@@ -7,6 +7,7 @@ use std::time::Duration;
|
||||
|
||||
use crate::expr::PyExpr;
|
||||
use crate::runtime::future_into_py;
|
||||
use crate::sync_stream::SyncRecordBatchStream;
|
||||
use crate::util::parse_distance_type;
|
||||
use crate::{arrow::RecordBatchStream, util::PyLanceDB};
|
||||
use crate::{error::PythonErrorExt, index::class_name};
|
||||
@@ -33,6 +34,7 @@ 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;
|
||||
@@ -65,6 +67,34 @@ 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()))
|
||||
}
|
||||
|
||||
fn query_execution_options(
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> QueryExecutionOptions {
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
if let Some(max_batch_length) = max_batch_length {
|
||||
options.max_batch_length = max_batch_length;
|
||||
}
|
||||
if let Some(timeout) = timeout {
|
||||
options.timeout = Some(timeout);
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
|
||||
type Error = PyErr;
|
||||
|
||||
@@ -357,6 +387,7 @@ pub struct PyQueryRequest {
|
||||
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,
|
||||
@@ -380,6 +411,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 {
|
||||
@@ -390,6 +422,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
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
|
||||
@@ -417,12 +450,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),
|
||||
@@ -449,6 +484,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,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -667,6 +703,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();
|
||||
@@ -684,18 +724,58 @@ impl Query {
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut opts = QueryExecutionOptions::default();
|
||||
if let Some(max_batch_length) = max_batch_length {
|
||||
opts.max_batch_length = max_batch_length;
|
||||
}
|
||||
if let Some(timeout) = timeout {
|
||||
opts.timeout = Some(timeout);
|
||||
}
|
||||
let opts = query_execution_options(max_batch_length, timeout);
|
||||
let inner_stream = inner.execute_with_options(opts).await.infer_error()?;
|
||||
Ok(RecordBatchStream::new(inner_stream))
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this local query and return a pull-driven synchronous iterator.
|
||||
///
|
||||
/// The query is started once. Each `__next__` fetches exactly one batch
|
||||
/// from the caller's thread while the GIL is released. `None` keeps the
|
||||
/// core's default 1024-row output cap, `0` lets the engine choose, and a
|
||||
/// positive value caps each returned batch.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
py: Python<'_>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<SyncRecordBatchStream> {
|
||||
let inner = self_.inner.clone();
|
||||
let opts = query_execution_options(max_batch_length, timeout);
|
||||
let stream = py.detach(move || {
|
||||
crate::runtime::block_on_interruptible(async move {
|
||||
inner.execute_with_options(opts).await.infer_error()
|
||||
})
|
||||
})?;
|
||||
Ok(SyncRecordBatchStream::new(stream))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -751,6 +831,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);
|
||||
}
|
||||
@@ -784,6 +868,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 {
|
||||
@@ -909,6 +1007,45 @@ 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
|
||||
@@ -1148,6 +1285,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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
//! A pull-driven synchronous reader over a query's record batch stream.
|
||||
//!
|
||||
//! The synchronous Python API used to drive one future per batch through the
|
||||
//! shared background event loop. This reader keeps the stream in Rust and
|
||||
//! fetches exactly one batch from the caller's thread for each `__next__`,
|
||||
//! while the caller's GIL is released.
|
||||
//!
|
||||
//! The stream is stored only while the reader is idle. Taking it out for a
|
||||
//! poll means an error, EOF, interrupt, or a dropped last owner releases the
|
||||
//! execution plan immediately instead of leaving a reader task behind. A
|
||||
//! successful batch puts the stream back so an early `break` can resume
|
||||
//! reading from the same cursor.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use arrow::datatypes::SchemaRef;
|
||||
use arrow::pyarrow::{IntoPyArrow, ToPyArrow};
|
||||
use arrow::record_batch::RecordBatch;
|
||||
use futures::StreamExt;
|
||||
use lancedb::arrow::SendableRecordBatchStream;
|
||||
use pyo3::{Py, PyAny, PyRef, PyResult, Python, pyclass, pymethods};
|
||||
|
||||
use crate::error::PythonErrorExt;
|
||||
use crate::runtime::block_on_interruptible;
|
||||
|
||||
/// Synchronous iterator over the batches of one query execution.
|
||||
///
|
||||
/// Python wraps this in [`pyarrow.RecordBatchReader.from_batches`] so the
|
||||
/// public return type, schema capsule, and exception types stay the same as
|
||||
/// the existing sync reader. Creating the iterator does not poll the stream;
|
||||
/// the first `__next__` starts any configured query timeout.
|
||||
#[pyclass]
|
||||
pub struct SyncRecordBatchStream {
|
||||
schema: SchemaRef,
|
||||
stream: Mutex<Option<SendableRecordBatchStream>>,
|
||||
}
|
||||
|
||||
impl SyncRecordBatchStream {
|
||||
pub fn new(stream: SendableRecordBatchStream) -> Self {
|
||||
let schema = stream.schema();
|
||||
Self {
|
||||
schema,
|
||||
stream: Mutex::new(Some(stream)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the stream and hand it to one owned, one-shot read future.
|
||||
///
|
||||
/// The future owns the stream so an interrupt aborts it and drops the
|
||||
/// execution plan with the future. A successful batch returns the stream
|
||||
/// to the slot, which keeps an early `break` resumable. EOF and read
|
||||
/// errors drop the stream before returning. The lock is held only while
|
||||
/// taking or storing the stream, never while waiting, so another Python
|
||||
/// thread cannot deadlock against a read that needs the GIL.
|
||||
fn pull(&mut self) -> PyResult<Option<RecordBatch>> {
|
||||
match self.pull_with(|mut stream| {
|
||||
block_on_interruptible(async move {
|
||||
let next = stream.next().await;
|
||||
Ok::<_, pyo3::PyErr>((stream, next))
|
||||
})
|
||||
})? {
|
||||
Some(Ok(batch)) => Ok(Some(batch)),
|
||||
Some(Err(error)) => Err(into_py_error(error)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared state machine for one pull, with the wait injected for tests.
|
||||
fn pull_with<F>(
|
||||
&mut self,
|
||||
fetch: F,
|
||||
) -> Result<Option<Result<RecordBatch, lancedb::Error>>, pyo3::PyErr>
|
||||
where
|
||||
F: FnOnce(
|
||||
SendableRecordBatchStream,
|
||||
) -> PyResult<(
|
||||
SendableRecordBatchStream,
|
||||
Option<Result<RecordBatch, lancedb::Error>>,
|
||||
)>,
|
||||
{
|
||||
let Some(stream) = self
|
||||
.stream
|
||||
.lock()
|
||||
.expect("sync reader mutex poisoned")
|
||||
.take()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (stream, next) = fetch(stream)?;
|
||||
match next {
|
||||
Some(Ok(batch)) => {
|
||||
*self.stream.lock().expect("sync reader mutex poisoned") = Some(stream);
|
||||
Ok(Some(Ok(batch)))
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
drop(stream);
|
||||
Ok(Some(Err(error)))
|
||||
}
|
||||
None => {
|
||||
drop(stream);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
*self.stream.lock().expect("sync reader mutex poisoned") = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl SyncRecordBatchStream {
|
||||
#[getter]
|
||||
pub fn schema(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
(*self.schema)
|
||||
.clone()
|
||||
.into_pyarrow(py)
|
||||
.map(|obj| obj.unbind())
|
||||
}
|
||||
|
||||
fn __iter__(self_: PyRef<'_, Self>) -> PyRef<'_, Self> {
|
||||
self_
|
||||
}
|
||||
|
||||
fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
|
||||
let batch = py.detach(|| self.pull())?;
|
||||
let Some(batch) = batch else {
|
||||
return Ok(None);
|
||||
};
|
||||
let batch = match batch.to_pyarrow(py) {
|
||||
Ok(batch) => batch,
|
||||
Err(error) => {
|
||||
self.release();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
// A signal arriving after the fetch still terminates the reader, so
|
||||
// no execution plan outlives the KeyboardInterrupt.
|
||||
if let Err(error) = py.check_signals() {
|
||||
self.release();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(Some(batch.unbind()))
|
||||
}
|
||||
}
|
||||
|
||||
fn into_py_error(error: lancedb::Error) -> pyo3::PyErr {
|
||||
match Err::<(), _>(error).infer_error() {
|
||||
Ok(()) => unreachable!("infer_error returned Ok for an Err value"),
|
||||
Err(error) => error,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::VecDeque;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use arrow::array::Int32Array;
|
||||
use arrow::datatypes::{DataType, Field, Schema};
|
||||
use futures::Stream;
|
||||
use lancedb::arrow::RecordBatchStream as LanceRecordBatchStream;
|
||||
|
||||
use super::*;
|
||||
|
||||
struct TestStream {
|
||||
schema: SchemaRef,
|
||||
batches: VecDeque<Result<RecordBatch, lancedb::Error>>,
|
||||
polls: Arc<AtomicUsize>,
|
||||
dropped: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl TestStream {
|
||||
fn new(batches: Vec<Result<RecordBatch, lancedb::Error>>) -> Self {
|
||||
let schema = test_schema();
|
||||
Self {
|
||||
schema,
|
||||
batches: batches.into(),
|
||||
polls: Arc::new(AtomicUsize::new(0)),
|
||||
dropped: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for TestStream {
|
||||
type Item = Result<RecordBatch, lancedb::Error>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
self.polls.fetch_add(1, Ordering::SeqCst);
|
||||
Poll::Ready(self.batches.pop_front())
|
||||
}
|
||||
}
|
||||
|
||||
impl LanceRecordBatchStream for TestStream {
|
||||
fn schema(&self) -> SchemaRef {
|
||||
Arc::clone(&self.schema)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestStream {
|
||||
fn drop(&mut self) {
|
||||
self.dropped.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn test_schema() -> SchemaRef {
|
||||
Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]))
|
||||
}
|
||||
|
||||
fn test_batch(value: i32) -> RecordBatch {
|
||||
RecordBatch::try_new(test_schema(), vec![Arc::new(Int32Array::from(vec![value]))]).unwrap()
|
||||
}
|
||||
|
||||
fn boxed(stream: TestStream) -> SendableRecordBatchStream {
|
||||
Box::pin(stream)
|
||||
}
|
||||
|
||||
fn pull_fake(
|
||||
reader: &mut SyncRecordBatchStream,
|
||||
) -> Result<Option<Result<RecordBatch, lancedb::Error>>, pyo3::PyErr> {
|
||||
reader.pull_with(|mut stream| {
|
||||
let next = futures::executor::block_on(stream.next());
|
||||
Ok((stream, next))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_does_not_poll() {
|
||||
let stream = TestStream::new(vec![Ok(test_batch(1))]);
|
||||
let polls = Arc::clone(&stream.polls);
|
||||
let _reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_pull_reads_one_batch_and_keeps_the_stream_resumable() {
|
||||
let stream = TestStream::new(vec![
|
||||
Ok(test_batch(1)),
|
||||
Ok(test_batch(2)),
|
||||
Ok(test_batch(3)),
|
||||
]);
|
||||
let polls = Arc::clone(&stream.polls);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let mut reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok());
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 1);
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok());
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 2);
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eof_drops_the_stream_before_returning() {
|
||||
let stream = TestStream::new(vec![Ok(test_batch(1))]);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let mut reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_ok());
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
assert!(pull_fake(&mut reader).unwrap().is_none());
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert!(pull_fake(&mut reader).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_drops_the_stream_before_returning() {
|
||||
let stream = TestStream::new(vec![Err(lancedb::Error::Runtime {
|
||||
message: "read failed".to_string(),
|
||||
})]);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let mut reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
assert!(pull_fake(&mut reader).unwrap().unwrap().is_err());
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert!(pull_fake(&mut reader).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_an_unread_reader_drops_the_stream_without_polling() {
|
||||
let stream = TestStream::new(vec![Ok(test_batch(1))]);
|
||||
let polls = Arc::clone(&stream.polls);
|
||||
let dropped = Arc::clone(&stream.dropped);
|
||||
let reader = SyncRecordBatchStream::new(boxed(stream));
|
||||
|
||||
drop(reader);
|
||||
assert_eq!(polls.load(Ordering::SeqCst), 0);
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
}
|
||||
+530
-122
File diff suppressed because it is too large
Load Diff
Generated
+9
-12
@@ -2147,7 +2147,7 @@ requires-dist = [
|
||||
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
|
||||
{ name = "pydantic", specifier = ">=2.7.4,<3" },
|
||||
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b25" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b26" },
|
||||
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
|
||||
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
|
||||
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
|
||||
@@ -4301,24 +4301,21 @@ crypto = [
|
||||
|
||||
[[package]]
|
||||
name = "pylance"
|
||||
version = "15.0.0b25"
|
||||
version = "15.0.0b26"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
dependencies = [
|
||||
{ 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_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" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2bYWOD/pylance-15.0.0b26-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc68ef8edeb6e29f01542f0bfaa7973978f416a8eeec344427b255dd652db13a" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_aF5wV/pylance-15.0.0b26-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27d4f4c18ab682052931e70c4f5d4491288c99c69f465ed806084f40b3924367" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2axp3c/pylance-15.0.0b26-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fb0b9c33f85ff9c52633488b5b696fa1a35036ae899827aceb94212a2ef746df" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_oCJRc/pylance-15.0.0b26-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7c5ca0afb4988206518b1cb801bb1a1a3cc09527828ae51109b2071e549a4486" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1Lg63I/pylance-15.0.0b26-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:32a986146e7b4f2e7b23974bb8718f293939f43f088e5585c38b1ae5b162d46c" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_FOT84/pylance-15.0.0b26-cp310-abi3-win_amd64.whl", hash = "sha256:904fd37f8212f00c1affc917b421e4ac4fc051c4c3d3c98cd7adbb33537a3ce3" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_A4Kru/pylance-15.0.0b26-cp310-abi3-win_arm64.whl", hash = "sha256:39dbf4b02b3bbaf916b38f1b924da2a534cdb1e32eb8e3f58fb720ef9b92331a" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user