mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-28 05:24:00 +00:00
Merge remote-tracking branch 'origin/main' into gatekeeper/fix-4842-1
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
|
||||
|
||||
import os
|
||||
import warnings
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
from typing import Dict, Optional, Union, Any, List, Iterable, Literal, TYPE_CHECKING
|
||||
@@ -16,9 +17,18 @@ __version__ = str(_Version(_native_version))
|
||||
|
||||
from ._lancedb import connect as lancedb_connect
|
||||
from ._lancedb import FtsToken
|
||||
from ._lancedb import (
|
||||
FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus,
|
||||
)
|
||||
from ._lancedb import (
|
||||
FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob,
|
||||
)
|
||||
from ._lancedb import FunctionColumnStatus as FunctionColumnStatus
|
||||
from ._lancedb import (
|
||||
FunctionColumnVersionStatus as FunctionColumnVersionStatus,
|
||||
)
|
||||
from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
|
||||
from ._lancedb import FunctionErrorRecord as FunctionErrorRecord
|
||||
from ._lancedb import FunctionErrors as FunctionErrors
|
||||
from ._lancedb import GpuClass as GpuClass
|
||||
from ._lancedb import RTEWriteSpec
|
||||
from ._lancedb import tokenize as _tokenize
|
||||
@@ -28,23 +38,34 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection
|
||||
from .remote import ClientConfig
|
||||
from .remote.db import RemoteDBConnection
|
||||
from .expr import Expr, col, lit, func
|
||||
from .schema import blob, vector
|
||||
from .schema import BasePath, blob, blob_uri_array, vector
|
||||
from ._blob_reader import BlobReader as BlobReader
|
||||
from .job import AsyncJob, Job
|
||||
from .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,
|
||||
FunctionBinding as FunctionBinding,
|
||||
FunctionDefinition as FunctionDefinition,
|
||||
FunctionEnvironment as FunctionEnvironment,
|
||||
FunctionRegistrationRequest as FunctionRegistrationRequest,
|
||||
FunctionRetryPolicy as FunctionRetryPolicy,
|
||||
FunctionVersion as FunctionVersion,
|
||||
HuggingFaceModel as HuggingFaceModel,
|
||||
PythonRuntimeSpec as PythonRuntimeSpec,
|
||||
ResolvedEnvironment as ResolvedEnvironment,
|
||||
ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance,
|
||||
ResolvedPackage as ResolvedPackage,
|
||||
RefreshColumnResult as RefreshColumnResult,
|
||||
UdfDefinition as UdfDefinition,
|
||||
function as function,
|
||||
udf as udf,
|
||||
)
|
||||
from .secrets import EnvVarSecret as EnvVarSecret
|
||||
@@ -58,6 +79,7 @@ from .materialized_view import (
|
||||
from .view import ViewDescription as ViewDescription
|
||||
from .graph import PropertyGraph, PropertyGraphDescription
|
||||
from .table import AsyncTable, CompactionOptions, Table
|
||||
from .query import ColumnOrdering as ColumnOrdering
|
||||
from .types import BaseTokenizerType
|
||||
from ._lancedb import Session
|
||||
from .namespace import (
|
||||
@@ -77,6 +99,7 @@ from .catalog import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lance.blob import BlobType as BlobType
|
||||
from .functions import UdfDefinition as UdfDefinition
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
@@ -85,6 +108,13 @@ def __getattr__(name: str):
|
||||
|
||||
globals()["BlobType"] = BlobType
|
||||
return BlobType
|
||||
if name == "UdfDefinition":
|
||||
from . import functions
|
||||
|
||||
warnings.warn(
|
||||
functions.UDF_DEFINITION_DEPRECATION, DeprecationWarning, stacklevel=2
|
||||
)
|
||||
return functions.FunctionDefinition
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
|
||||
@@ -649,6 +679,15 @@ __all__ = [
|
||||
"AsyncTable",
|
||||
"CompactionOptions",
|
||||
"FtsToken",
|
||||
"FunctionColumnAutoRefreshStatus",
|
||||
"FunctionColumnLastRefreshJob",
|
||||
"FunctionColumnStatus",
|
||||
"FunctionColumnVersionStatus",
|
||||
"FunctionErrors",
|
||||
"AsyncFunctionErrors",
|
||||
"FunctionErrorGroup",
|
||||
"FunctionProvenance",
|
||||
"FunctionValueProvenance",
|
||||
"col",
|
||||
"Expr",
|
||||
"func",
|
||||
@@ -657,9 +696,12 @@ __all__ = [
|
||||
"sanitize_uri",
|
||||
"blob",
|
||||
"BlobType",
|
||||
"BasePath",
|
||||
"blob_uri_array",
|
||||
"vector",
|
||||
"DBConnection",
|
||||
"Job",
|
||||
"JobState",
|
||||
"QueryDescription",
|
||||
"SqlQuery",
|
||||
"LanceDBConnection",
|
||||
|
||||
+114
-10
@@ -1,19 +1,25 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Blob fetch API and v2 projection helpers."""
|
||||
"""Blob fetch API and projection helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import operator
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Optional, Union
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
from .expr import Expr
|
||||
from .schema import blob_column_paths, row_addressable_blob_v2_paths
|
||||
from .schema import (
|
||||
blob_column_paths,
|
||||
row_addressable_blob_paths,
|
||||
row_addressable_blob_v2_paths,
|
||||
)
|
||||
from .types import BlobMode, QueryProjection, QueryProjectionSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -26,10 +32,56 @@ BLOB_MODE_TO_HANDLING = {
|
||||
}
|
||||
|
||||
ROW_ID_FIELD_NAME = "_lance_row_id"
|
||||
QUERY_VERSION_METADATA_KEY = b"lancedb:query_version"
|
||||
QUERY_SNAPSHOT_METADATA_KEY = b"lancedb:query_snapshot"
|
||||
|
||||
FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
|
||||
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
|
||||
|
||||
_POSITION_HELP = (
|
||||
"If you only have row positions, call "
|
||||
"table.take_offsets(offsets, with_row_id=True) first and pass the resulting "
|
||||
"'_rowid' values."
|
||||
)
|
||||
|
||||
|
||||
def _remote_blob_snapshot(
|
||||
schema: pa.Schema, *, operation: str = "blob_mode='bytes'"
|
||||
) -> tuple[int, str]:
|
||||
"""Validate the snapshot metadata a remote query attaches to its result."""
|
||||
value = (schema.metadata or {}).get(QUERY_VERSION_METADATA_KEY, b"")
|
||||
if not value.isdigit() or not 0 < int(value) < 2**64:
|
||||
raise NotImplementedError(
|
||||
f"{operation} requires a stable table snapshot: the query response "
|
||||
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
|
||||
"Upgrade the server and use a table without Realtime/MemWAL, or use "
|
||||
"blob_mode='descriptions'."
|
||||
)
|
||||
identity = (schema.metadata or {}).get(QUERY_SNAPSHOT_METADATA_KEY, b"")
|
||||
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
|
||||
raise NotImplementedError(
|
||||
f"{operation} requires a trustworthy query snapshot identity: "
|
||||
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
|
||||
"on every serving node, or use blob_mode='descriptions'."
|
||||
)
|
||||
return int(value), identity.decode("ascii")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _BlobRowIdSelection:
|
||||
row_ids: list[int]
|
||||
version: Optional[int] = None
|
||||
snapshot_identity: Optional[str] = None
|
||||
|
||||
|
||||
def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
|
||||
if size is None:
|
||||
return None
|
||||
size = operator.index(size)
|
||||
if size < 0:
|
||||
raise ValueError("buffer_size must be non-negative")
|
||||
return size
|
||||
|
||||
|
||||
def _normalize_blob_descriptor(value):
|
||||
if isinstance(value, pa.Scalar):
|
||||
@@ -54,6 +106,16 @@ class BlobFile(io.RawIOBase):
|
||||
def __init__(self, inner) -> None:
|
||||
self._inner = inner
|
||||
|
||||
def set_buffer_size(self, size: int) -> None:
|
||||
"""Set sequential read-ahead bytes (default 512 KiB); 0 disables it.
|
||||
|
||||
Changing the size discards unused prefetched bytes without moving the
|
||||
cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead.
|
||||
"""
|
||||
if self.closed:
|
||||
raise ValueError("set_buffer_size of closed file")
|
||||
self._inner.set_buffer_size(_validate_blob_buffer_size(size))
|
||||
|
||||
async def aread(self) -> bytes:
|
||||
if self.closed:
|
||||
raise ValueError("read of closed file")
|
||||
@@ -165,6 +227,25 @@ def blob_v2_projection_sources(
|
||||
return _project_blob_paths(row_addressable_blob_v2_paths(schema), projection)
|
||||
|
||||
|
||||
def blob_projection_sources(
|
||||
schema: pa.Schema,
|
||||
projection: QueryProjection,
|
||||
*,
|
||||
include_legacy: bool = False,
|
||||
) -> dict[str, str]:
|
||||
"""Map projected blob outputs to row-addressable source columns.
|
||||
|
||||
Legacy v1 columns are included only when the caller can safely fetch them
|
||||
through the same row-id path as v2.
|
||||
"""
|
||||
paths = (
|
||||
row_addressable_blob_paths(schema)
|
||||
if include_legacy
|
||||
else row_addressable_blob_v2_paths(schema)
|
||||
)
|
||||
return _project_blob_paths(paths, projection)
|
||||
|
||||
|
||||
def reject_unfetchable_blob_columns(
|
||||
schema: pa.Schema, projection: QueryProjection, blob_sources: dict[str, str]
|
||||
) -> None:
|
||||
@@ -177,8 +258,9 @@ def reject_unfetchable_blob_columns(
|
||||
if unfetchable:
|
||||
raise ValueError(
|
||||
f"blob_mode='bytes' cannot fetch blob columns {unfetchable}. Bytes are "
|
||||
"fetched by row id, which covers blob v2 columns with one blob per "
|
||||
"row but not legacy blob columns or blobs inside lists. Use "
|
||||
"fetched by row id for legacy and v2 columns in local plain scans, "
|
||||
"but not for blobs inside lists or query shapes whose result columns "
|
||||
"cannot be matched back to the source. Use "
|
||||
"blob_mode='descriptions' or remove these columns from the projection."
|
||||
)
|
||||
|
||||
@@ -269,7 +351,7 @@ def finalize_blob_query_table(
|
||||
return stash_auto_row_ids(tbl, blob_paths)
|
||||
|
||||
|
||||
async def replace_v2_blob_columns_with_bytes(
|
||||
async def replace_blob_columns_with_bytes(
|
||||
tbl: pa.Table,
|
||||
blob_sources: dict[str, str],
|
||||
fetch_blobs: FetchBlobsAsync,
|
||||
@@ -289,7 +371,7 @@ async def replace_v2_blob_columns_with_bytes(
|
||||
return tbl
|
||||
|
||||
|
||||
def replace_v2_blob_columns_with_bytes_sync(
|
||||
def replace_blob_columns_with_bytes_sync(
|
||||
tbl: pa.Table,
|
||||
blob_sources: dict[str, str],
|
||||
fetch_blobs: FetchBlobsSync,
|
||||
@@ -333,7 +415,7 @@ def _hit_row_ids(tbl: pa.Table, blob_sources: dict[str, str]) -> list[int]:
|
||||
raise ValueError(
|
||||
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
|
||||
f"field on blob columns {list(blob_sources)}. Call .with_row_id(True) "
|
||||
"to fetch blob bytes for this query."
|
||||
f"to fetch blob bytes for this query. {_POSITION_HELP}"
|
||||
)
|
||||
|
||||
|
||||
@@ -374,7 +456,8 @@ def read_row_ids_from_hits(hits: pa.Table, blob_column: str) -> list[int]:
|
||||
raise ValueError(
|
||||
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
|
||||
f"field on blob column '{blob_column}'. Pass fresh blob query "
|
||||
"results, call .with_row_id(True), or pass a list of row ids."
|
||||
f"results, call .with_row_id(True), or pass a list of row ids. "
|
||||
f"{_POSITION_HELP}"
|
||||
)
|
||||
|
||||
|
||||
@@ -595,11 +678,31 @@ def _walk_struct_fields(
|
||||
return data_type
|
||||
|
||||
|
||||
def _query_snapshot_for_blob_fetch(
|
||||
schema: pa.Schema,
|
||||
) -> Optional[tuple[int, str]]:
|
||||
"""Use the query snapshot when a result table carries one.
|
||||
|
||||
A table without either metadata key came from a local table or a server
|
||||
that cannot pin deferred reads, so row ids keep their existing
|
||||
current-snapshot behavior.
|
||||
"""
|
||||
metadata = schema.metadata or {}
|
||||
if not any(
|
||||
key in metadata
|
||||
for key in (QUERY_VERSION_METADATA_KEY, QUERY_SNAPSHOT_METADATA_KEY)
|
||||
):
|
||||
return None
|
||||
return _remote_blob_snapshot(schema, operation="fetching blobs for a query result")
|
||||
|
||||
|
||||
def _normalize_blob_row_ids(
|
||||
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], blob_column: str
|
||||
) -> list[int]:
|
||||
) -> _BlobRowIdSelection:
|
||||
snapshot = None
|
||||
if isinstance(row_ids, pa.Table):
|
||||
values = read_row_ids_from_hits(row_ids, blob_column)
|
||||
snapshot = _query_snapshot_for_blob_fetch(row_ids.schema)
|
||||
elif isinstance(row_ids, (pa.Array, pa.ChunkedArray)):
|
||||
if not pa.types.is_integer(row_ids.type):
|
||||
raise ValueError(
|
||||
@@ -619,7 +722,8 @@ def _normalize_blob_row_ids(
|
||||
if row_id < 0:
|
||||
raise ValueError("row ids must be non-negative")
|
||||
normalized.append(row_id)
|
||||
return normalized
|
||||
version, snapshot_identity = snapshot if snapshot else (None, None)
|
||||
return _BlobRowIdSelection(normalized, version, snapshot_identity)
|
||||
|
||||
|
||||
def _wrap_blob_files(handles: Iterable[object]) -> list[Optional[BlobFile]]:
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Streaming Blob output for Enterprise Functions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
from .schema import blob
|
||||
|
||||
_BLOB_WRITER_METADATA_KEY = b"lance.function.blob_writer"
|
||||
_REFRESH_REQUIRED = (
|
||||
"BlobWriter is available only during a LanceDB Enterprise computed column refresh"
|
||||
)
|
||||
|
||||
|
||||
def _mark_blob_writer(field: pa.Field) -> pa.Field:
|
||||
metadata: dict[bytes | str, bytes | str] = {
|
||||
key: value for key, value in (field.metadata or {}).items()
|
||||
}
|
||||
metadata[_BLOB_WRITER_METADATA_KEY] = b"true"
|
||||
return field.with_metadata(metadata)
|
||||
|
||||
|
||||
class BlobWriter:
|
||||
"""Write one Blob v2 value in chunks during a computed column refresh.
|
||||
|
||||
Annotate a scalar Function's return value with ``BlobWriter`` to declare a
|
||||
Blob v2 result. For named or nested results, use :meth:`field` for each
|
||||
writer-capable field in the output schema. A vectorized Function returns
|
||||
a row-aligned list or tuple of results.
|
||||
|
||||
Open one writer per Blob value. Writes are sequential and block for
|
||||
capacity. Closing the writer seals the result, including an empty Blob.
|
||||
A context manager seals on normal exit and aborts on exceptional exit.
|
||||
A discarded writer still uses one entry in the batch's cumulative
|
||||
descriptor allowance. Explicit writers and implicit uploads of returned
|
||||
``bytes`` share this allowance.
|
||||
|
||||
Return the sealed writer once at its declared Blob v2 output field during
|
||||
the same invocation. Unclosed or reused writers are invalid results.
|
||||
|
||||
The worker provides the implementation when it runs the packaged Function.
|
||||
|
||||
Examples
|
||||
--------
|
||||
```python
|
||||
from lancedb.functions import BlobWriter, function
|
||||
|
||||
@function
|
||||
def render(text: str) -> BlobWriter:
|
||||
with BlobWriter.open() as output:
|
||||
for line in text.splitlines():
|
||||
output.write(line.encode("utf-8"))
|
||||
output.write(b"\\n")
|
||||
return output
|
||||
```
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
raise RuntimeError(_REFRESH_REQUIRED)
|
||||
|
||||
@classmethod
|
||||
def open(cls) -> BlobWriter:
|
||||
"""Open a sequential writer for one Blob in the active invocation."""
|
||||
raise RuntimeError(_REFRESH_REQUIRED)
|
||||
|
||||
def write(self, data) -> int:
|
||||
"""Write a bytes-like object and return the accepted byte count."""
|
||||
raise RuntimeError(_REFRESH_REQUIRED)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Seal the Blob so the writer can be returned as a result."""
|
||||
raise RuntimeError(_REFRESH_REQUIRED)
|
||||
|
||||
def __enter__(self) -> BlobWriter:
|
||||
raise RuntimeError(_REFRESH_REQUIRED)
|
||||
|
||||
def __exit__(self, exc_type, exc, traceback) -> None:
|
||||
raise RuntimeError(_REFRESH_REQUIRED)
|
||||
|
||||
@staticmethod
|
||||
def field(name: str, nullable: bool = True) -> pa.Field:
|
||||
"""Declare a writer-capable Blob v2 field in a Function output schema.
|
||||
|
||||
A marked field also accepts ordinary ``bytes`` and, if nullable,
|
||||
``None``. Use this helper for Function output schemas and use
|
||||
[``lancedb.blob``][lancedb.blob] for table schemas.
|
||||
"""
|
||||
return _mark_blob_writer(blob(name, nullable=nullable))
|
||||
@@ -25,6 +25,9 @@ from .index import (
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -116,7 +119,7 @@ class PyExpr:
|
||||
|
||||
def expr_col(name: str) -> PyExpr: ...
|
||||
def expr_lit(
|
||||
value: Union[bool, int, float, str, bytes, date, datetime, Decimal],
|
||||
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
|
||||
) -> PyExpr: ...
|
||||
def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ...
|
||||
|
||||
@@ -184,12 +187,20 @@ class Connection(object):
|
||||
limit: Optional[int],
|
||||
) -> list[str]: ... # Deprecated: Use list_tables instead
|
||||
async def open_job(self, job_id: str) -> Job: ...
|
||||
async def server_info(self) -> str: ...
|
||||
async def list_gpu_classes(self) -> list[GpuClass]: ...
|
||||
async def create_function_async(
|
||||
self, request_json: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
request_json: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> Job: ...
|
||||
async def get_function(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
version: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> str: ...
|
||||
def list_functions(
|
||||
self,
|
||||
@@ -201,6 +212,9 @@ class Connection(object):
|
||||
async def drop_function(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
) -> bool: ...
|
||||
async def _drop_function_with_warnings(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Tuple[bool, list[str]]: ...
|
||||
async def drop_function_async(
|
||||
self, name: str, version: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Tuple[bool, Job]: ...
|
||||
@@ -221,7 +235,12 @@ class Connection(object):
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> None: ...
|
||||
async def create_secret(
|
||||
self, name: str, value: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
value: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> None: ...
|
||||
async def alter_secret(
|
||||
self, name: str, value: str, namespace_path: Optional[List[str]] = None
|
||||
@@ -240,7 +259,12 @@ class Connection(object):
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Tuple[str, int, int]: ...
|
||||
async def create_view(
|
||||
self, name: str, query: str, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
query: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ...
|
||||
async def describe_view(
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
@@ -278,7 +302,19 @@ class Connection(object):
|
||||
page_limit: Optional[int] = None,
|
||||
) -> NameListing: ...
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> JobListing: ...
|
||||
async def cancel_job(self, job_id: str) -> bool: ...
|
||||
async def pause_job(self, job_id: str) -> str: ...
|
||||
@@ -289,6 +325,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(
|
||||
@@ -299,6 +338,9 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table: ...
|
||||
async def create_empty_table(
|
||||
self,
|
||||
@@ -308,6 +350,8 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
) -> Table: ...
|
||||
async def open_table(
|
||||
self,
|
||||
@@ -325,6 +369,8 @@ class Connection(object):
|
||||
source_version: Optional[int] = None,
|
||||
source_tag: Optional[str] = None,
|
||||
is_shallow: bool = True,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
) -> Table: ...
|
||||
async def rename_table(
|
||||
self,
|
||||
@@ -336,24 +382,40 @@ class Connection(object):
|
||||
async def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: str,
|
||||
source: Optional[str] = None,
|
||||
projections: Optional[List[Tuple[str, str]]] = None,
|
||||
filter: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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,
|
||||
) -> Table: ...
|
||||
async def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: str,
|
||||
source: Optional[str] = None,
|
||||
projections: Optional[List[Tuple[str, str]]] = None,
|
||||
filter: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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,
|
||||
) -> Job: ...
|
||||
def list_materialized_views(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
@@ -385,11 +447,26 @@ class BlobFile:
|
||||
def seek(self, position: int) -> None: ...
|
||||
def tell(self) -> int: ...
|
||||
def size(self) -> int: ...
|
||||
def set_buffer_size(self, size: int) -> None: ...
|
||||
def read_range(self, offset: int, length: int) -> bytes: ...
|
||||
def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ...
|
||||
def read_up_to(self, length: int) -> bytes: ...
|
||||
|
||||
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
|
||||
@@ -404,12 +481,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:
|
||||
@@ -424,6 +523,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: ...
|
||||
@@ -465,11 +576,27 @@ class JobFailureInfo:
|
||||
@property
|
||||
def message(self) -> Optional[str]: ...
|
||||
@property
|
||||
def traceback(self) -> Optional[str]:
|
||||
"""User-code traceback, possibly truncated by the server."""
|
||||
...
|
||||
@property
|
||||
def retryable(self) -> Optional[bool]: ...
|
||||
@property
|
||||
def sql_job_id(self) -> Optional[str]: ...
|
||||
|
||||
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
|
||||
@@ -494,6 +621,8 @@ class JobDescription:
|
||||
class SqlQuery:
|
||||
@property
|
||||
def id(self) -> UUID: ...
|
||||
@property
|
||||
def job_id(self) -> Optional[str]: ...
|
||||
async def describe(self) -> QueryDescription: ...
|
||||
async def reader(self) -> RecordBatchStream: ...
|
||||
async def cancel(self) -> None: ...
|
||||
@@ -502,6 +631,8 @@ class QueryDescription:
|
||||
@property
|
||||
def id(self) -> UUID: ...
|
||||
@property
|
||||
def job_id(self) -> Optional[str]: ...
|
||||
@property
|
||||
def status(self) -> str: ...
|
||||
@property
|
||||
def progress(self) -> Optional[float]: ...
|
||||
@@ -515,6 +646,7 @@ class Table:
|
||||
def _is_native(self) -> bool: ...
|
||||
def close(self) -> None: ...
|
||||
async def schema(self) -> pa.Schema: ...
|
||||
def schema_sync(self) -> pa.Schema: ...
|
||||
async def add(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
@@ -522,7 +654,14 @@ class Table:
|
||||
progress: Optional[Any] = None,
|
||||
write_parallelism: Optional[int] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
retries: Optional[int] = None,
|
||||
) -> AddResult: ...
|
||||
async def execute_merge_insert(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
parameters: Dict[str, Any],
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult: ...
|
||||
async def update(
|
||||
self, updates: Dict[str, str], where: Optional[str]
|
||||
) -> UpdateResult: ...
|
||||
@@ -542,6 +681,9 @@ class Table:
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -549,6 +691,7 @@ class Table:
|
||||
*,
|
||||
name: Optional[str],
|
||||
train: Optional[bool],
|
||||
exist_ok: bool = False,
|
||||
): ...
|
||||
async def create_index_async(
|
||||
self,
|
||||
@@ -565,6 +708,9 @@ class Table:
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -572,14 +718,37 @@ class Table:
|
||||
*,
|
||||
name: Optional[str],
|
||||
train: Optional[bool],
|
||||
exist_ok: bool = False,
|
||||
) -> Job: ...
|
||||
async def list_versions(self) -> List[Dict[str, Any]]: ...
|
||||
async def version(self) -> int: ...
|
||||
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,
|
||||
@@ -598,41 +767,138 @@ class Table:
|
||||
columns: list[tuple[str, str]],
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: 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,
|
||||
) -> AddColumnsResult: ...
|
||||
async def add_function_columns(
|
||||
self,
|
||||
application_json: str,
|
||||
output_name: Optional[str],
|
||||
bindings: list[tuple[str, Optional[str]]],
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: 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,
|
||||
) -> AddColumnsResult: ...
|
||||
async def refresh_column(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
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,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
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,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[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,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
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]: ...
|
||||
async def column_status(self, column: str) -> FunctionColumnStatus: ...
|
||||
async def wait_column_fresh(
|
||||
self, column: str, timeout: Optional[timedelta] = None
|
||||
) -> FunctionColumnStatus: ...
|
||||
async def refresh_materialized_view(
|
||||
self, source_version: Optional[int] = None, *, full: bool = False
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
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
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
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: ...
|
||||
@@ -642,6 +908,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,
|
||||
*,
|
||||
@@ -677,7 +948,12 @@ class Table:
|
||||
def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ...
|
||||
async def blob_columns(self) -> list[str]: ...
|
||||
async def fetch_blobs(
|
||||
self, column: str, row_ids: list[int]
|
||||
self,
|
||||
column: str,
|
||||
row_ids: list[int],
|
||||
*,
|
||||
version: Optional[int] = None,
|
||||
snapshot_identity: Optional[str] = None,
|
||||
) -> pa.LargeBinaryArray: ...
|
||||
async def fetch_blob_ranges(
|
||||
self,
|
||||
@@ -685,15 +961,23 @@ class Table:
|
||||
requests: Sequence[Sequence[int]],
|
||||
) -> pa.LargeBinaryArray: ...
|
||||
async def fetch_blob_files(
|
||||
self, column: str, row_ids: list[int]
|
||||
self,
|
||||
column: str,
|
||||
row_ids: list[int],
|
||||
buffer_size: Optional[int] = None,
|
||||
*,
|
||||
version: Optional[int] = None,
|
||||
snapshot_identity: Optional[str] = None,
|
||||
) -> list[Optional[BlobFile]]: ...
|
||||
async def open_blob_file(self, descriptor: str) -> BlobFile: ...
|
||||
async def open_blob_file(
|
||||
self, descriptor: str, buffer_size: Optional[int] = None
|
||||
) -> BlobFile: ...
|
||||
def vector_search(self) -> VectorQuery: ...
|
||||
|
||||
class Tags:
|
||||
async def list(self) -> Dict[str, Tag]: ...
|
||||
async def get_version(self, tag: str) -> int: ...
|
||||
async def create(self, tag: str, version: int): ...
|
||||
async def create(self, tag: str, version: Optional[int] = None): ...
|
||||
async def delete(self, tag: str): ...
|
||||
async def update(self, tag: str, version: int): ...
|
||||
|
||||
@@ -704,6 +988,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: ...
|
||||
@@ -764,11 +1050,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): ...
|
||||
@@ -784,10 +1085,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
|
||||
@@ -797,9 +1108,13 @@ class Query:
|
||||
class TakeQuery:
|
||||
def select(self, columns: List[str]): ...
|
||||
def with_row_id(self): ...
|
||||
def preserve_order(self): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -821,10 +1136,17 @@ class FTSQuery:
|
||||
def add_query_vector(self, query_vec: pa.Array) -> None: ...
|
||||
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
async def count_rows(self) -> int: ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -834,6 +1156,12 @@ class FTSQuery:
|
||||
class VectorQuery:
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def where(self, filter: str): ...
|
||||
def where_expr(self, expr: PyExpr): ...
|
||||
def select(self, columns: List[Tuple[str, str]]): ...
|
||||
@@ -893,6 +1221,8 @@ class PyQueryRequest:
|
||||
limit: Optional[int]
|
||||
offset: Optional[int]
|
||||
take_offsets: Optional[List[int]]
|
||||
take_row_ids: Optional[List[int]]
|
||||
preserve_order: Optional[bool]
|
||||
filter: Optional[Union[str, bytes]]
|
||||
full_text_search: Optional[FullTextQuery]
|
||||
select: Optional[Union[str, List[str]]]
|
||||
@@ -916,6 +1246,7 @@ class PyQueryRequest:
|
||||
postfilter: Optional[bool]
|
||||
norm: Optional[str]
|
||||
order_by: Optional[List[ColumnOrdering]]
|
||||
scan_in_order: Optional[bool]
|
||||
|
||||
class CompactionStats:
|
||||
fragments_removed: int
|
||||
@@ -1003,9 +1334,16 @@ 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]
|
||||
row_address: Optional[int]
|
||||
column: str
|
||||
function: str
|
||||
@@ -1013,6 +1351,8 @@ class FunctionErrorRecord:
|
||||
table_version: int
|
||||
error_type: str
|
||||
error_message: str
|
||||
traceback: Optional[str]
|
||||
"""User-code traceback, possibly truncated by the server."""
|
||||
created_at_millis: int
|
||||
|
||||
class FunctionErrorFragment:
|
||||
@@ -1022,10 +1362,54 @@ 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
|
||||
|
||||
class FunctionColumnVersionStatus:
|
||||
name: str
|
||||
namespace_path: list[str]
|
||||
object_id: str
|
||||
location: str
|
||||
version: str
|
||||
manifest_digest: str
|
||||
|
||||
class FunctionColumnLastRefreshJob:
|
||||
job_id: str
|
||||
state: str
|
||||
automatic: Optional[bool]
|
||||
completed_at_millis: Optional[int]
|
||||
failure: Optional[JobFailureInfo]
|
||||
|
||||
class FunctionColumnAutoRefreshStatus:
|
||||
enabled: bool
|
||||
interval_seconds: Optional[int]
|
||||
active_job_id: Optional[str]
|
||||
state: str
|
||||
failure_streak: int
|
||||
effective_cooldown_millis: Optional[int]
|
||||
blocked_reason: Optional[str]
|
||||
next_run_at_millis: Optional[int]
|
||||
next_run_at_reason: Optional[str]
|
||||
|
||||
class FunctionColumnStatus:
|
||||
column: str
|
||||
binding_id: str
|
||||
function: FunctionColumnVersionStatus
|
||||
table_version: int
|
||||
rows: int
|
||||
fresh: int
|
||||
stale: int
|
||||
never_computed: int
|
||||
failed: int
|
||||
last_refresh_job: Optional[FunctionColumnLastRefreshJob]
|
||||
last_failure_job: Optional[FunctionColumnLastRefreshJob]
|
||||
auto_refresh: FunctionColumnAutoRefreshStatus
|
||||
|
||||
class RefreshMaterializedViewResult:
|
||||
@staticmethod
|
||||
def from_json(value: str) -> RefreshMaterializedViewResult: ...
|
||||
@@ -1054,7 +1438,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,
|
||||
@@ -1077,6 +1466,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(
|
||||
@@ -1117,6 +1514,7 @@ async def connect_catalog(
|
||||
sql_host_override: Optional[str] = None,
|
||||
read_consistency_interval: Optional[float] = None,
|
||||
oauth_config: Optional[Any] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
) -> Catalog: ...
|
||||
|
||||
class NameListing:
|
||||
@@ -1198,3 +1596,6 @@ class AuthzObject:
|
||||
) -> AuthzObject: ...
|
||||
def __str__(self) -> str: ...
|
||||
def __repr__(self) -> str: ...
|
||||
|
||||
def validate_function_retry_policy(json: str) -> None: ...
|
||||
def _validate_conda_requirement(requirement: str) -> None: ...
|
||||
|
||||
@@ -13,22 +13,51 @@ class BackgroundEventLoop:
|
||||
A background event loop that can run futures.
|
||||
|
||||
Used to bridge sync and async code, without messing with users event loops.
|
||||
|
||||
The loop and its thread are created by the first call to :meth:`run`, not
|
||||
by constructing this object, so importing lancedb does not leave an idle
|
||||
background thread behind.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._start()
|
||||
self.loop: asyncio.AbstractEventLoop | None = None
|
||||
self.thread: threading.Thread | None = None
|
||||
self._start_lock = threading.Lock()
|
||||
|
||||
def _start(self):
|
||||
self.loop = asyncio.new_event_loop()
|
||||
self.thread = threading.Thread(
|
||||
target=self.loop.run_forever,
|
||||
name="LanceDBBackgroundEventLoop",
|
||||
daemon=True,
|
||||
)
|
||||
self.thread.start()
|
||||
def _start(self) -> asyncio.AbstractEventLoop:
|
||||
loop = self.loop
|
||||
if loop is not None:
|
||||
return loop
|
||||
with self._start_lock:
|
||||
loop = self.loop
|
||||
if loop is not None:
|
||||
return loop
|
||||
loop = asyncio.new_event_loop()
|
||||
thread = threading.Thread(
|
||||
target=loop.run_forever,
|
||||
name="LanceDBBackgroundEventLoop",
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
# Publish the loop first and the thread last. Callers that reach
|
||||
# _start while this is in progress wait on _start_lock, so they
|
||||
# cannot observe a half-initialized loop/thread pair.
|
||||
self.loop = loop
|
||||
self.thread = thread
|
||||
return loop
|
||||
|
||||
def _reset_after_fork(self):
|
||||
# Threads do not survive fork(). Reset to the unstarted state without
|
||||
# calling into the inherited loop or thread: the thread is gone, and
|
||||
# it may have held _start_lock when the fork happened. A fresh lock
|
||||
# lets the child start a new loop on its first run().
|
||||
self.loop = None
|
||||
self.thread = None
|
||||
self._start_lock = threading.Lock()
|
||||
|
||||
def run(self, future):
|
||||
concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop)
|
||||
loop = self._start()
|
||||
concurrent_future = asyncio.run_coroutine_threadsafe(future, loop)
|
||||
try:
|
||||
return concurrent_future.result()
|
||||
except BaseException:
|
||||
@@ -60,12 +89,15 @@ _FORK_WARNED = False
|
||||
|
||||
|
||||
def _reset_after_fork():
|
||||
# Threads do not survive fork(), so the asyncio loop in LOOP.thread is
|
||||
# dead in the child. Re-initialize the singleton in place so existing
|
||||
# Threads do not survive fork(), so the loop in LOOP.thread is dead in
|
||||
# the child. Reset the singleton in place so existing
|
||||
# `from .background_loop import LOOP` references in other modules see
|
||||
# the new state. The Rust-side tokio runtime is reset analogously by a
|
||||
# pthread_atfork hook installed in the _lancedb extension.
|
||||
LOOP._start()
|
||||
# the unstarted state and create a fresh loop on their first run(). Do
|
||||
# not restart it here: the child may never use LanceDB, and the at-fork
|
||||
# handler must not touch the vanished thread or acquire inherited locks.
|
||||
# The Rust-side tokio runtime is reset analogously by a pthread_atfork
|
||||
# hook installed in the _lancedb extension.
|
||||
LOOP._reset_after_fork()
|
||||
# The embedding executor's worker threads are dead in the child as well.
|
||||
# Replace it with a fresh pool (threads are spawned lazily, so this is
|
||||
# cheap); we don't shut down the old one, since joining its dead workers
|
||||
|
||||
@@ -3,13 +3,17 @@
|
||||
|
||||
"""Remote catalogs manage databases."""
|
||||
|
||||
from functools import cached_property
|
||||
import os
|
||||
import warnings
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
from functools import cached_property
|
||||
from typing import Any, AsyncIterator, Iterator, Optional, Union
|
||||
|
||||
from . import _lancedb
|
||||
from .background_loop import LOOP
|
||||
from .authz import AsyncAuthorization, Authorization
|
||||
from .common import URI, sanitize_uri
|
||||
from .db import AsyncConnection, DBConnection
|
||||
from .remote import ClientConfig, OAuthConfig
|
||||
from .remote.db import RemoteDBConnection
|
||||
@@ -163,12 +167,14 @@ class Catalog:
|
||||
client_config=None,
|
||||
sql_host_override: Optional[str] = None,
|
||||
oauth_config: Optional[OAuthConfig] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
):
|
||||
self._inner = inner
|
||||
self._api_key = api_key
|
||||
self._client_config = client_config
|
||||
self._sql_host_override = sql_host_override
|
||||
self._oauth_config = oauth_config
|
||||
self._storage_options = storage_options
|
||||
|
||||
@cached_property
|
||||
def authz(self) -> Authorization:
|
||||
@@ -198,6 +204,7 @@ class Catalog:
|
||||
self._client_config,
|
||||
self._oauth_config,
|
||||
self._sql_host_override,
|
||||
self._storage_options,
|
||||
)
|
||||
|
||||
def list_databases(
|
||||
@@ -227,28 +234,71 @@ class Catalog:
|
||||
|
||||
|
||||
async def connect_catalog_async(
|
||||
endpoint: str,
|
||||
uri: Optional[URI] = None,
|
||||
*,
|
||||
api_key: Optional[str] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
region: Optional[str] = None,
|
||||
host_override: Optional[str] = None,
|
||||
sql_host_override: Optional[str] = None,
|
||||
read_consistency_interval: Optional[timedelta] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
session: Optional[_lancedb.Session] = None,
|
||||
manifest_enabled: bool = False,
|
||||
namespace_client_properties: Optional[dict[str, str]] = None,
|
||||
oauth_config: Optional[OAuthConfig] = None,
|
||||
) -> AsyncCatalog:
|
||||
"""Connect to an HTTP(S) server's root catalog.
|
||||
"""Connect to a server's root catalog using database connection settings.
|
||||
|
||||
``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise
|
||||
``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with
|
||||
[connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's
|
||||
database is ignored and requests target the root catalog.
|
||||
|
||||
``region`` is ignored with a warning when supplied. Catalog connections use
|
||||
the explicit endpoint rather than a region-derived Cloud (legacy) endpoint.
|
||||
``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable.
|
||||
Embedded-only ``session``, ``manifest_enabled`` and
|
||||
``namespace_client_properties`` are not supported.
|
||||
|
||||
Root requests omit database-selection headers. API key, client configuration,
|
||||
OAuth, and table read consistency settings are inherited by opened databases.
|
||||
OAuth, storage options, and table read consistency settings are inherited by
|
||||
opened databases.
|
||||
Database names containing slashes remain single logical names.
|
||||
Set ``sql_host_override`` to the SQL service endpoint to execute SQL through
|
||||
returned connections when the catalog endpoint uses HTTPS.
|
||||
"""
|
||||
if region is not None:
|
||||
warnings.warn(
|
||||
"region is ignored by connect_catalog_async; the catalog endpoint "
|
||||
"is selected by host_override or uri.",
|
||||
UserWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
for name, value in (
|
||||
("session", session),
|
||||
("manifest_enabled", manifest_enabled or None),
|
||||
("namespace_client_properties", namespace_client_properties),
|
||||
):
|
||||
if value is not None:
|
||||
raise NotImplementedError(
|
||||
f"{name} is not supported for catalog connections"
|
||||
)
|
||||
endpoint = host_override if host_override is not None else uri
|
||||
if endpoint is None:
|
||||
raise ValueError("uri or host_override is required for catalog connections")
|
||||
if isinstance(client_config, dict):
|
||||
client_config = ClientConfig(**client_config)
|
||||
if client_config is None:
|
||||
client_config = ClientConfig()
|
||||
if (
|
||||
api_key is None
|
||||
and oauth_config is None
|
||||
and client_config.header_provider is None
|
||||
):
|
||||
api_key = os.environ.get("LANCEDB_API_KEY")
|
||||
inner = await _lancedb.connect_catalog(
|
||||
endpoint,
|
||||
sanitize_uri(endpoint),
|
||||
api_key=api_key,
|
||||
client_config=client_config,
|
||||
sql_host_override=sql_host_override,
|
||||
@@ -258,32 +308,115 @@ async def connect_catalog_async(
|
||||
else None
|
||||
),
|
||||
oauth_config=oauth_config,
|
||||
storage_options=storage_options,
|
||||
)
|
||||
return AsyncCatalog(inner)
|
||||
|
||||
|
||||
def connect_catalog(
|
||||
endpoint: str,
|
||||
uri: Optional[URI] = None,
|
||||
*,
|
||||
api_key: Optional[str] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
region: Optional[str] = None,
|
||||
host_override: Optional[str] = None,
|
||||
sql_host_override: Optional[str] = None,
|
||||
read_consistency_interval: Optional[timedelta] = None,
|
||||
request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
|
||||
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
|
||||
storage_options: Optional[dict[str, str]] = None,
|
||||
session: Optional[_lancedb.Session] = None,
|
||||
manifest_enabled: bool = False,
|
||||
namespace_client_impl: Optional[str] = None,
|
||||
namespace_client_properties: Optional[dict[str, str]] = None,
|
||||
namespace_client_pushdown_operations: Optional[list[str]] = None,
|
||||
oauth_config: Optional[OAuthConfig] = None,
|
||||
**kwargs: Any,
|
||||
) -> Catalog:
|
||||
"""Connect synchronously to an HTTP(S) server's root catalog.
|
||||
"""Connect synchronously to a root catalog using database connection settings.
|
||||
|
||||
See [connect_catalog_async][lancedb.connect_catalog_async] for options.
|
||||
The inputs match [connect][lancedb.connect]; ``region`` is ignored with a
|
||||
warning when supplied. Namespace client options and embedded session settings
|
||||
are not supported. ``request_thread_pool`` is deprecated and unused, as in
|
||||
``connect``.
|
||||
Local filesystem and object-store catalogs are not supported.
|
||||
|
||||
Examples
|
||||
--------
|
||||
```python
|
||||
settings = {"api_key": "secret", "host_override": "https://my-server.example"}
|
||||
catalog = lancedb.connect_catalog("db://analytics", **settings)
|
||||
db = lancedb.connect("db://analytics", **settings)
|
||||
```
|
||||
"""
|
||||
unknown_kwargs = {
|
||||
key: value
|
||||
for key, value in kwargs.items()
|
||||
if key not in ("connection_timeout", "read_timeout")
|
||||
}
|
||||
if unknown_kwargs:
|
||||
raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}")
|
||||
for name, value in (
|
||||
("namespace_client_impl", namespace_client_impl),
|
||||
("namespace_client_pushdown_operations", namespace_client_pushdown_operations),
|
||||
):
|
||||
if value is not None:
|
||||
raise NotImplementedError(
|
||||
f"{name} is not supported for catalog connections"
|
||||
)
|
||||
if region is not None:
|
||||
warnings.warn(
|
||||
"region is ignored by connect_catalog; the catalog endpoint "
|
||||
"is selected by host_override or uri.",
|
||||
UserWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if request_thread_pool is not None:
|
||||
warnings.warn(
|
||||
"request_thread_pool is no longer used and will be removed in "
|
||||
"a future release.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if isinstance(client_config, dict):
|
||||
client_config = ClientConfig(**client_config)
|
||||
if client_config is None:
|
||||
client_config = ClientConfig()
|
||||
for name, field in (
|
||||
("connection_timeout", "connect_timeout"),
|
||||
("read_timeout", "read_timeout"),
|
||||
):
|
||||
if kwargs.get(name) is not None:
|
||||
warnings.warn(
|
||||
f"{name} is deprecated and will be removed in a future release. "
|
||||
f"Please use client_config.timeout_config.{field} instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
setattr(
|
||||
client_config.timeout_config,
|
||||
field,
|
||||
timedelta(seconds=kwargs[name]),
|
||||
)
|
||||
if (
|
||||
api_key is None
|
||||
and oauth_config is None
|
||||
and client_config.header_provider is None
|
||||
):
|
||||
api_key = os.environ.get("LANCEDB_API_KEY")
|
||||
return Catalog(
|
||||
LOOP.run(
|
||||
connect_catalog_async(
|
||||
endpoint,
|
||||
uri,
|
||||
api_key=api_key,
|
||||
host_override=host_override,
|
||||
client_config=client_config,
|
||||
sql_host_override=sql_host_override,
|
||||
read_consistency_interval=read_consistency_interval,
|
||||
storage_options=storage_options,
|
||||
session=session,
|
||||
manifest_enabled=manifest_enabled,
|
||||
namespace_client_properties=namespace_client_properties,
|
||||
oauth_config=oauth_config,
|
||||
)
|
||||
),
|
||||
@@ -291,4 +424,5 @@ def connect_catalog(
|
||||
client_config=client_config,
|
||||
sql_host_override=sql_host_override,
|
||||
oauth_config=oauth_config,
|
||||
storage_options=storage_options,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,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})
|
||||
+794
-101
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@ from .base import (
|
||||
TextEmbeddingFunction,
|
||||
UntrustedEmbeddingConfigError,
|
||||
)
|
||||
from .bedrock import BedRockText
|
||||
from .bedrock import BedrockImage, BedRockText
|
||||
from .cohere import CohereEmbeddingFunction
|
||||
from .gemini_text import GeminiText
|
||||
from .instructor import InstructorEmbeddingFunction
|
||||
@@ -45,6 +45,7 @@ __all__ = [
|
||||
"NvidiaEmbeddings",
|
||||
"OpenClipEmbeddings",
|
||||
"BedRockText",
|
||||
"BedrockImage",
|
||||
"CohereEmbeddingFunction",
|
||||
"GeminiText",
|
||||
"GteEmbeddings",
|
||||
|
||||
@@ -2,21 +2,66 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
from functools import cached_property
|
||||
from typing import List, Union
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, List, Literal, Union
|
||||
|
||||
import numpy as np
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from ..util import attempt_import_or_raise
|
||||
from .base import TextEmbeddingFunction
|
||||
from .base import EmbeddingFunction, TextEmbeddingFunction
|
||||
from .registry import register
|
||||
from .utils import TEXT
|
||||
from .utils import IMAGES, TEXT, retry_with_exponential_backoff
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from PIL.Image import Image
|
||||
|
||||
|
||||
class _BedrockEmbeddingFunction(EmbeddingFunction):
|
||||
name: str
|
||||
region: str = "us-east-1"
|
||||
|
||||
model_config = ConfigDict(ignored_types=(cached_property,))
|
||||
|
||||
def _invoke_model(self, body: str, *, max_retries: int = 0) -> dict:
|
||||
invoke = self.client.invoke_model
|
||||
if max_retries > 0:
|
||||
invoke = retry_with_exponential_backoff(invoke, max_retries=max_retries)
|
||||
response = invoke(
|
||||
body=body,
|
||||
modelId=self.name,
|
||||
accept="application/json",
|
||||
contentType="application/json",
|
||||
)
|
||||
return json.loads(response["body"].read())
|
||||
|
||||
@cached_property
|
||||
def client(self):
|
||||
"""The boto3 Bedrock Runtime client."""
|
||||
boto3 = attempt_import_or_raise("boto3")
|
||||
return self._runtime_client(boto3.Session())
|
||||
|
||||
def _runtime_client(self, session, **credentials):
|
||||
botocore = attempt_import_or_raise("botocore")
|
||||
retry_config = botocore.config.Config(
|
||||
region_name=self.region,
|
||||
# The embedding function handles retries.
|
||||
retries={"max_attempts": 0, "mode": "standard"},
|
||||
)
|
||||
return session.client(
|
||||
service_name="bedrock-runtime",
|
||||
config=retry_config,
|
||||
region_name=self.region,
|
||||
**credentials,
|
||||
)
|
||||
|
||||
|
||||
@register("bedrock-text")
|
||||
class BedRockText(TextEmbeddingFunction):
|
||||
class BedRockText(_BedrockEmbeddingFunction, TextEmbeddingFunction):
|
||||
"""
|
||||
Parameters
|
||||
----------
|
||||
@@ -59,14 +104,35 @@ class BedRockText(TextEmbeddingFunction):
|
||||
"""
|
||||
|
||||
name: str = "amazon.titan-embed-text-v1"
|
||||
region: str = "us-east-1"
|
||||
assumed_role: Union[str, None] = None
|
||||
profile_name: Union[str, None] = None
|
||||
role_session_name: str = "lancedb-embeddings"
|
||||
source_input_type: str = "search_document"
|
||||
query_input_type: str = "search_query"
|
||||
|
||||
model_config = ConfigDict(ignored_types=(cached_property,))
|
||||
@cached_property
|
||||
def client(self):
|
||||
"""The boto3 Bedrock Runtime client."""
|
||||
boto3 = attempt_import_or_raise("boto3")
|
||||
session = (
|
||||
boto3.Session(region_name=self.region, profile_name=self.profile_name)
|
||||
if self.profile_name
|
||||
else boto3.Session()
|
||||
)
|
||||
if not self.assumed_role:
|
||||
return self._runtime_client(session)
|
||||
|
||||
sts = session.client("sts")
|
||||
credentials = sts.assume_role(
|
||||
RoleArn=self.assumed_role,
|
||||
RoleSessionName=self.role_session_name,
|
||||
)["Credentials"]
|
||||
return self._runtime_client(
|
||||
session,
|
||||
aws_access_key_id=credentials["AccessKeyId"],
|
||||
aws_secret_access_key=credentials["SecretAccessKey"],
|
||||
aws_session_token=credentials["SessionToken"],
|
||||
)
|
||||
|
||||
def ndims(self):
|
||||
# return len(self._generate_embedding("test"))
|
||||
@@ -145,16 +211,7 @@ class BedRockText(TextEmbeddingFunction):
|
||||
body = json.dumps(input_body)
|
||||
|
||||
try:
|
||||
# invoke bedrock API
|
||||
response = self.client.invoke_model(
|
||||
body=body,
|
||||
modelId=self.name,
|
||||
accept="application/json",
|
||||
contentType="application/json",
|
||||
)
|
||||
|
||||
# format output based on provider
|
||||
response_body = json.loads(response.get("body").read())
|
||||
response_body = self._invoke_model(body)
|
||||
if provider == "cohere":
|
||||
return response_body.get("embeddings")[0]
|
||||
else:
|
||||
@@ -170,50 +227,155 @@ class BedRockText(TextEmbeddingFunction):
|
||||
"""
|
||||
raise ValueError(f"Error raised by boto3 client: {e}. \n {help_txt}")
|
||||
|
||||
@cached_property
|
||||
def client(self):
|
||||
"""Create a boto3 client for Amazon Bedrock service
|
||||
|
||||
Returns
|
||||
-------
|
||||
boto3.client
|
||||
The boto3 client for Amazon Bedrock service
|
||||
"""
|
||||
botocore = attempt_import_or_raise("botocore")
|
||||
boto3 = attempt_import_or_raise("boto3")
|
||||
@register("bedrock-image")
|
||||
class BedrockImage(_BedrockEmbeddingFunction):
|
||||
"""Embed images and search them by text or Pillow image using Amazon Bedrock.
|
||||
|
||||
session_kwargs = {"region_name": self.region}
|
||||
client_kwargs = {**session_kwargs}
|
||||
Install `boto3` and `pillow` to use this embedding function. Use a binary
|
||||
source column (`bytes`) for encoded image bytes or a string
|
||||
source column (`str`) for file paths readable by the process that adds rows.
|
||||
Pillow detects the image format from the file contents. Null source values
|
||||
produce null embeddings.
|
||||
|
||||
if self.profile_name:
|
||||
session_kwargs["profile_name"] = self.profile_name
|
||||
Both models accept PNG and JPEG sources. `cohere.embed-v4:0` also accepts
|
||||
WebP and GIF. For queries, pass a text string or a Pillow image. Images
|
||||
used as queries are encoded in RGB PNG format before calling Bedrock. With
|
||||
[AsyncTable.search][lancedb.table.AsyncTable.search], pass
|
||||
`query_type="vector"` for Pillow image queries.
|
||||
|
||||
retry_config = botocore.config.Config(
|
||||
region_name=self.region,
|
||||
retries={
|
||||
"max_attempts": 0, # disable this as retries retries are handled
|
||||
"mode": "standard",
|
||||
},
|
||||
)
|
||||
session = (
|
||||
boto3.Session(**session_kwargs) if self.profile_name else boto3.Session()
|
||||
)
|
||||
if self.assumed_role: # if not using default credentials
|
||||
sts = session.client("sts")
|
||||
response = sts.assume_role(
|
||||
RoleArn=str(self.assumed_role),
|
||||
RoleSessionName=self.role_session_name,
|
||||
This function uses the boto3 default credential chain configured by your
|
||||
application, including `AWS_PROFILE` or the application's IAM role.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str, default "amazon.titan-embed-image-v1"
|
||||
Model ID to invoke on Amazon Bedrock. `amazon.titan-embed-image-v1`
|
||||
returns 1024 dimensions. `cohere.embed-v4:0` returns 1536 dimensions.
|
||||
region : str, default "us-east-1"
|
||||
AWS Region where the model is available.
|
||||
max_retries : int, default 7
|
||||
Maximum retries per Bedrock request. Set to `0` to disable retries.
|
||||
|
||||
Examples
|
||||
--------
|
||||
```python
|
||||
from pathlib import Path
|
||||
|
||||
import lancedb
|
||||
from lancedb.embeddings import get_registry
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
from PIL import Image
|
||||
|
||||
model = get_registry().get("bedrock-image").create()
|
||||
|
||||
class Photo(LanceModel):
|
||||
image: bytes = model.SourceField()
|
||||
vector: Vector(model.ndims()) = model.VectorField()
|
||||
|
||||
db = lancedb.connect("photos_db")
|
||||
table = db.create_table("photos", schema=Photo)
|
||||
table.add([{"image": Path("sunset.jpg").read_bytes()}])
|
||||
|
||||
matches = table.search("sunset over the ocean").limit(5).to_list()
|
||||
with Image.open("query.png") as query:
|
||||
similar = table.search(query).limit(5).to_list()
|
||||
```
|
||||
"""
|
||||
|
||||
# Table metadata can select a model and region. Credentials come from the
|
||||
# application, so reject settings such as a profile name or role ARN.
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: Literal["amazon.titan-embed-image-v1", "cohere.embed-v4:0"] = (
|
||||
"amazon.titan-embed-image-v1"
|
||||
)
|
||||
|
||||
def ndims(self) -> int:
|
||||
return 1024 if self.name == "amazon.titan-embed-image-v1" else 1536
|
||||
|
||||
def compute_source_embeddings(self, images: IMAGES) -> list[list[float] | None]:
|
||||
return self._embed_sources(images, max_retries=0)
|
||||
|
||||
def compute_query_embeddings(self, query: "str | Image") -> list[list[float]]:
|
||||
return self._embed_query(query, max_retries=0)
|
||||
|
||||
# A transient failure can retry its own request without replaying earlier
|
||||
# images or repeating local image encoding and response parsing.
|
||||
def compute_source_embeddings_with_retry(
|
||||
self, images: IMAGES, *args, **kwargs
|
||||
) -> list[list[float] | None]:
|
||||
return self._embed_sources(images, max_retries=self.max_retries)
|
||||
|
||||
def compute_query_embeddings_with_retry(
|
||||
self, query: "str | Image", *args, **kwargs
|
||||
) -> list[list[float]]:
|
||||
return self._embed_query(query, max_retries=self.max_retries)
|
||||
|
||||
def _embed_sources(
|
||||
self, images: IMAGES, *, max_retries: int
|
||||
) -> list[list[float] | None]:
|
||||
values = [images] if isinstance(images, bytes) else self.sanitize_input(images)
|
||||
embeddings = []
|
||||
for image in values:
|
||||
if image is None:
|
||||
embeddings.append(None)
|
||||
continue
|
||||
image_bytes = Path(image).read_bytes() if isinstance(image, str) else image
|
||||
image_module = attempt_import_or_raise("PIL.Image", "pillow")
|
||||
with image_module.open(io.BytesIO(image_bytes)) as decoded:
|
||||
payload = self._image_payload(image_bytes, decoded.format)
|
||||
embeddings.append(
|
||||
self._embed(
|
||||
payload, input_type="search_document", max_retries=max_retries
|
||||
)
|
||||
)
|
||||
client_kwargs["aws_access_key_id"] = response["Credentials"]["AccessKeyId"]
|
||||
client_kwargs["aws_secret_access_key"] = response["Credentials"][
|
||||
"SecretAccessKey"
|
||||
]
|
||||
client_kwargs["aws_session_token"] = response["Credentials"]["SessionToken"]
|
||||
return embeddings
|
||||
|
||||
service_name = "bedrock-runtime"
|
||||
def _embed_query(
|
||||
self, query: "str | Image", *, max_retries: int
|
||||
) -> list[list[float]]:
|
||||
if isinstance(query, str):
|
||||
payload = (
|
||||
{"inputText": query}
|
||||
if self.name == "amazon.titan-embed-image-v1"
|
||||
else {"texts": [query]}
|
||||
)
|
||||
else:
|
||||
image_module = attempt_import_or_raise("PIL.Image", "pillow")
|
||||
if not isinstance(query, image_module.Image):
|
||||
raise TypeError("Bedrock image queries must be text or a Pillow image")
|
||||
with io.BytesIO() as buffer:
|
||||
query.convert("RGB").save(buffer, format="PNG")
|
||||
payload = self._image_payload(buffer.getvalue(), "PNG")
|
||||
return [
|
||||
self._embed(payload, input_type="search_query", max_retries=max_retries)
|
||||
]
|
||||
|
||||
bedrock_client = session.client(
|
||||
service_name=service_name, config=retry_config, **client_kwargs
|
||||
)
|
||||
def _image_payload(self, image_bytes: bytes, image_format: str | None) -> dict:
|
||||
encoded = base64.b64encode(image_bytes).decode("ascii")
|
||||
if self.name == "amazon.titan-embed-image-v1":
|
||||
if image_format not in ("JPEG", "PNG"):
|
||||
raise ValueError(
|
||||
"Titan Multimodal Embeddings accepts PNG and JPEG images"
|
||||
)
|
||||
return {"inputImage": encoded}
|
||||
|
||||
return bedrock_client
|
||||
if image_format not in ("JPEG", "PNG", "WEBP", "GIF"):
|
||||
raise ValueError("Cohere Embed v4 accepts PNG, JPEG, WebP, and GIF images")
|
||||
return {"images": [f"data:image/{image_format.lower()};base64,{encoded}"]}
|
||||
|
||||
def _embed(
|
||||
self, payload: dict, *, input_type: str, max_retries: int
|
||||
) -> list[float]:
|
||||
is_cohere = self.name == "cohere.embed-v4:0"
|
||||
if is_cohere:
|
||||
payload["input_type"] = input_type
|
||||
payload["embedding_types"] = ["float"]
|
||||
|
||||
response = self._invoke_model(json.dumps(payload), max_retries=max_retries)
|
||||
if is_cohere:
|
||||
return response["embeddings"]["float"][0]
|
||||
if response.get("message"):
|
||||
raise ValueError(response["message"])
|
||||
return response["embedding"]
|
||||
|
||||
@@ -3,27 +3,48 @@
|
||||
|
||||
|
||||
import os
|
||||
from typing import ClassVar, List, Union
|
||||
from functools import cached_property
|
||||
from importlib.metadata import version
|
||||
from typing import ClassVar, List, Literal, Optional, Union
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import numpy as np
|
||||
from packaging.version import Version
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from ..util import attempt_import_or_raise
|
||||
from .base import TextEmbeddingFunction
|
||||
from .registry import register
|
||||
from .utils import api_key_not_found_help, TEXT
|
||||
from .utils import (
|
||||
TEXT,
|
||||
_get_http_status,
|
||||
api_key_not_found_help,
|
||||
retry_with_exponential_backoff,
|
||||
)
|
||||
|
||||
|
||||
_COHERE_V2_MIN_VERSION = "5.15.0"
|
||||
_COHERE_V2_MAX_TEXTS = 96
|
||||
|
||||
|
||||
def _is_redirect_error(error: Exception) -> bool:
|
||||
status = _get_http_status(error)
|
||||
return status is not None and 300 <= status < 400
|
||||
|
||||
|
||||
@register("cohere")
|
||||
class CohereEmbeddingFunction(TextEmbeddingFunction):
|
||||
"""
|
||||
An embedding function that uses the Cohere API
|
||||
An embedding function for Cohere text models, including Cohere Embed v4
|
||||
deployed on Azure AI Foundry through the native Cohere Embed API v2.
|
||||
|
||||
https://docs.cohere.com/docs/multilingual-language-models
|
||||
https://docs.cohere.com/v2/reference/embed
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str, default "embed-multilingual-v3.0"
|
||||
The name of the model to use. List of acceptable models:
|
||||
The model name. For a custom ``base_url``, supply the deployed model name
|
||||
explicitly. The default Cohere API supports these models:
|
||||
|
||||
* embed-english-v3.0
|
||||
* embed-multilingual-v3.0
|
||||
@@ -41,7 +62,24 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
|
||||
The input type for the source column in the database
|
||||
|
||||
query_input_type : str, default "search_query"
|
||||
The input type for the query column in the database
|
||||
The input type for the query column in the database.
|
||||
|
||||
base_url : str, optional
|
||||
Native Cohere API v2 base URL. For Foundry, use
|
||||
``https://<resource>.services.ai.azure.com/providers/cohere``. The Cohere
|
||||
SDK appends ``/v2/embed``. This path requires ``cohere>=5.15.0`` and uses
|
||||
``search_document`` and ``search_query`` for text retrieval.
|
||||
|
||||
output_dimension : int, optional
|
||||
Required with ``base_url``. Choose an output dimension supported by the
|
||||
deployed model. This also sets the vector column dimension.
|
||||
|
||||
api_key : str, optional
|
||||
Required with ``base_url``. Use a registry variable reference such as
|
||||
``$var:foundry-cohere-key`` and set its value with ``registry.set_var``.
|
||||
To restore a table in a new process, set the variable again and trust
|
||||
the endpoint with
|
||||
[allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint].
|
||||
|
||||
Notes
|
||||
-----
|
||||
@@ -89,8 +127,68 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
|
||||
source_input_type: str = "search_document"
|
||||
query_input_type: str = "search_query"
|
||||
client: ClassVar = None
|
||||
base_url: Optional[str] = None
|
||||
output_dimension: Optional[int] = Field(default=None, gt=0)
|
||||
api_key: Optional[str] = Field(default=None, repr=False)
|
||||
|
||||
@classmethod
|
||||
def create(cls, **kwargs):
|
||||
api_key = kwargs.get("api_key")
|
||||
if (
|
||||
isinstance(api_key, str)
|
||||
and api_key.startswith("$var:")
|
||||
and ":" in api_key[len("$var:") :]
|
||||
):
|
||||
raise ValueError(
|
||||
"Cohere api_key must use a registry variable without a default"
|
||||
)
|
||||
return super().create(**kwargs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_endpoint_config(self):
|
||||
if self.base_url is None:
|
||||
if self.output_dimension is not None or self.api_key is not None:
|
||||
raise ValueError("Cohere output_dimension and api_key require base_url")
|
||||
return self
|
||||
|
||||
url = urlsplit(self.base_url)
|
||||
if (
|
||||
url.scheme not in ("http", "https")
|
||||
or not url.hostname
|
||||
or url.username is not None
|
||||
or url.query
|
||||
or url.fragment
|
||||
):
|
||||
raise ValueError(
|
||||
"Cohere base_url must be an HTTP(S) URL without credentials, "
|
||||
"a query string, or a fragment"
|
||||
)
|
||||
if "name" not in self.model_fields_set or not self.name.strip():
|
||||
raise ValueError(
|
||||
"Set name to the deployed Cohere model when using base_url"
|
||||
)
|
||||
if self.output_dimension is None or not self.api_key:
|
||||
raise ValueError("Cohere base_url requires output_dimension and api_key")
|
||||
if (
|
||||
self.source_input_type != "search_document"
|
||||
or self.query_input_type != "search_query"
|
||||
):
|
||||
raise ValueError(
|
||||
"Cohere base_url requires search_document for sources "
|
||||
"and search_query for queries"
|
||||
)
|
||||
return self
|
||||
|
||||
@staticmethod
|
||||
def sensitive_keys() -> List[str]:
|
||||
return ["api_key"]
|
||||
|
||||
def endpoints(self) -> List[str]:
|
||||
return [] if self.base_url is None else [self.base_url]
|
||||
|
||||
def ndims(self):
|
||||
if self.output_dimension is not None:
|
||||
return self.output_dimension
|
||||
# TODO: fix hardcoding
|
||||
if self.name in [
|
||||
"embed-english-v3.0",
|
||||
@@ -108,6 +206,8 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
|
||||
raise ValueError(f"Model {self.name} not supported")
|
||||
|
||||
def compute_query_embeddings(self, query: str, *args, **kwargs) -> List[np.array]:
|
||||
if self.base_url is not None:
|
||||
return self._embed_v2(query, "search_query")
|
||||
return self.compute_source_embeddings(query, input_type=self.query_input_type)
|
||||
|
||||
def compute_source_embeddings(self, texts: TEXT, *args, **kwargs) -> List[np.array]:
|
||||
@@ -128,6 +228,8 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
|
||||
texts: list[str] or np.ndarray (of str)
|
||||
The texts to embed
|
||||
"""
|
||||
if self.base_url is not None:
|
||||
return self._embed_v2(texts, "search_document")
|
||||
self._init_client()
|
||||
rs = CohereEmbeddingFunction.client.embed(
|
||||
texts=texts, model=self.name, **kwargs
|
||||
@@ -135,6 +237,81 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
|
||||
|
||||
return [emb for emb in rs.embeddings]
|
||||
|
||||
def compute_source_embeddings_with_retry(self, texts: TEXT, *args, **kwargs):
|
||||
if self.base_url is None:
|
||||
return super().compute_source_embeddings_with_retry(texts, *args, **kwargs)
|
||||
return self._embed_v2(texts, "search_document", max_retries=self.max_retries)
|
||||
|
||||
def compute_query_embeddings_with_retry(self, query: str, *args, **kwargs):
|
||||
if self.base_url is None:
|
||||
return super().compute_query_embeddings_with_retry(query, *args, **kwargs)
|
||||
return self._embed_v2(query, "search_query", max_retries=self.max_retries)
|
||||
|
||||
def _embed_v2(
|
||||
self,
|
||||
texts: TEXT,
|
||||
input_type: Literal["search_document", "search_query"],
|
||||
*,
|
||||
max_retries: int = 0,
|
||||
) -> List[List[float]]:
|
||||
texts = self.sanitize_input(texts)
|
||||
if any(not isinstance(text, str) for text in texts):
|
||||
raise ValueError("Cohere API v2 text retrieval requires string inputs")
|
||||
if len(texts) == 0:
|
||||
return []
|
||||
|
||||
# Retry each HTTP request without resending earlier successful batches.
|
||||
# The client refuses redirects, so repeating a redirected request cannot help.
|
||||
request = self._v2_client.embed
|
||||
if max_retries > 0:
|
||||
request = retry_with_exponential_backoff(
|
||||
request, max_retries=max_retries, do_not_retry=_is_redirect_error
|
||||
)
|
||||
embeddings = []
|
||||
for start in range(0, len(texts), _COHERE_V2_MAX_TEXTS):
|
||||
batch = list(texts[start : start + _COHERE_V2_MAX_TEXTS])
|
||||
response = request(
|
||||
texts=batch,
|
||||
model=self.name,
|
||||
input_type=input_type,
|
||||
output_dimension=self.ndims(),
|
||||
embedding_types=["float"],
|
||||
request_options={"max_retries": 0},
|
||||
)
|
||||
vectors = response.embeddings.float
|
||||
if vectors is None or len(vectors) != len(batch):
|
||||
raise ValueError(
|
||||
"Cohere API v2 returned an unexpected number of vectors"
|
||||
)
|
||||
if any(len(vector) != self.ndims() for vector in vectors):
|
||||
raise ValueError(
|
||||
f"Cohere API v2 returned a vector with an unexpected dimension "
|
||||
f"(expected {self.ndims()})"
|
||||
)
|
||||
embeddings.extend(vectors)
|
||||
return embeddings
|
||||
|
||||
@cached_property
|
||||
def _v2_client(self):
|
||||
cohere = attempt_import_or_raise(
|
||||
"cohere", mitigation=f"cohere>={_COHERE_V2_MIN_VERSION}"
|
||||
)
|
||||
if Version(version("cohere")) < Version(_COHERE_V2_MIN_VERSION):
|
||||
raise ImportError(
|
||||
f"Cohere base_url requires cohere>={_COHERE_V2_MIN_VERSION}"
|
||||
)
|
||||
httpx = attempt_import_or_raise("httpx")
|
||||
# Older SDK versions override the HTTPX client's timeout on each request.
|
||||
timeout = 300
|
||||
# The registry trusts only this endpoint. The SDK follows redirects by
|
||||
# default, including redirects that can resend the document or query.
|
||||
return cohere.ClientV2(
|
||||
base_url=self.base_url,
|
||||
api_key=self.api_key,
|
||||
timeout=timeout,
|
||||
httpx_client=httpx.Client(follow_redirects=False, timeout=timeout),
|
||||
)
|
||||
|
||||
def _init_client(self):
|
||||
cohere = attempt_import_or_raise("cohere")
|
||||
if CohereEmbeddingFunction.client is None:
|
||||
|
||||
@@ -99,8 +99,6 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
||||
texts: list[str] or np.ndarray (of str)
|
||||
The texts to embed
|
||||
"""
|
||||
openai = attempt_import_or_raise("openai")
|
||||
|
||||
valid_texts = []
|
||||
valid_indices = []
|
||||
for idx, text in enumerate(texts):
|
||||
@@ -108,6 +106,11 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
||||
valid_texts.append(text)
|
||||
valid_indices.append(idx)
|
||||
|
||||
if not valid_texts:
|
||||
return [None] * len(texts)
|
||||
|
||||
openai = attempt_import_or_raise("openai")
|
||||
|
||||
# TODO retry, rate limit, token limit
|
||||
def embed_batch(texts_batch, indices_batch):
|
||||
kwargs = {
|
||||
|
||||
@@ -242,6 +242,8 @@ def retry_with_exponential_backoff(
|
||||
jitter: bool = True,
|
||||
max_retries: int = 7,
|
||||
max_delay: float = 60,
|
||||
*,
|
||||
do_not_retry: Callable[[Exception], bool] | None = None,
|
||||
):
|
||||
"""Retry a function with exponential backoff.
|
||||
|
||||
@@ -265,6 +267,7 @@ def retry_with_exponential_backoff(
|
||||
max_retries (int): Maximum number of retries (default is 7).
|
||||
max_delay (float): Maximum delay between two attempts, in seconds
|
||||
(default is 60).
|
||||
do_not_retry: Optional predicate for additional permanent failures.
|
||||
|
||||
Returns:
|
||||
function: The decorated function.
|
||||
@@ -286,7 +289,9 @@ def retry_with_exponential_backoff(
|
||||
except Exception as e: # noqa: PERF203
|
||||
# Don't retry permanent failures (e.g., OpenAI 401 or 404). They
|
||||
# won't be fixed by retrying and would only delay the real error.
|
||||
if _is_non_retryable_error(e):
|
||||
if _is_non_retryable_error(e) or (
|
||||
do_not_retry is not None and do_not_retry(e)
|
||||
):
|
||||
raise
|
||||
|
||||
num_retries += 1
|
||||
|
||||
@@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func
|
||||
|
||||
__all__ = ["Expr", "col", "lit", "func"]
|
||||
|
||||
_NOT_LITERAL = object()
|
||||
|
||||
_STR_TO_PA_TYPE: dict = {
|
||||
"bool": pa.bool_(),
|
||||
"boolean": pa.bool_(),
|
||||
@@ -92,9 +94,16 @@ class Expr:
|
||||
# for dict keys / set membership.
|
||||
__hash__ = None # type: ignore[assignment]
|
||||
|
||||
def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
inner: PyExpr,
|
||||
*,
|
||||
column_path: str | None = None,
|
||||
literal_value: object = _NOT_LITERAL,
|
||||
) -> None:
|
||||
self._inner = inner
|
||||
self._column_path = column_path
|
||||
self._literal_value = literal_value
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
# An Expr describes a predicate that the query engine evaluates per row,
|
||||
@@ -301,14 +310,16 @@ def col(name: str) -> Expr:
|
||||
return Expr(expr_col(name), column_path=name)
|
||||
|
||||
|
||||
def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr:
|
||||
def lit(
|
||||
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
|
||||
) -> Expr:
|
||||
"""Create a literal (constant) value expression.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
value:
|
||||
A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``,
|
||||
``datetime``, or ``Decimal``.
|
||||
``datetime``, ``Decimal``, or ``None`` for SQL NULL.
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) ->
|
||||
>>> col("price") * lit(1.1)
|
||||
Expr((price * 1.1))
|
||||
"""
|
||||
if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)):
|
||||
if value is not None and not isinstance(
|
||||
value, (bool, int, float, str, bytes, date, datetime, Decimal)
|
||||
):
|
||||
raise TypeError(f"Unsupported literal type: {type(value).__name__}")
|
||||
|
||||
return Expr(expr_lit(value))
|
||||
return Expr(expr_lit(value), literal_value=value)
|
||||
|
||||
|
||||
def func(name: str, *args: ExprLike) -> Expr:
|
||||
|
||||
+1927
-287
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,8 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Literal, Optional
|
||||
import json
|
||||
from typing import Any, Dict, List, Literal, Optional, Union
|
||||
|
||||
from ._lancedb import (
|
||||
IndexConfig,
|
||||
@@ -130,6 +131,140 @@ class NGram:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZoneMap:
|
||||
"""Describe a ZoneMap index configuration.
|
||||
|
||||
A `ZoneMap` index stores compact min and max summaries for contiguous
|
||||
ranges (zones) of rows. During a scan it skips any zone whose summary
|
||||
cannot satisfy the predicate, so it accelerates range and equality
|
||||
filters such as `col > 10`, `col BETWEEN a AND b`, and `col = x`,
|
||||
without changing the results.
|
||||
|
||||
It suits large numeric or temporal columns whose values are correlated
|
||||
with row order (for example `timestamp`, `price`, `id`).
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class RTree:
|
||||
"""Describe an RTree index configuration.
|
||||
|
||||
`RTree` is a scalar index on a GeoArrow geometry column, that is, a column
|
||||
whose Arrow field metadata sets ``ARROW:extension:name`` to a GeoArrow type
|
||||
such as ``geoarrow.point``, ``geoarrow.polygon`` or ``geoarrow.wkb``. It
|
||||
stores the bounding box of each geometry and accelerates spatial filters
|
||||
passed to ``where()``.
|
||||
|
||||
The index accelerates ``ST_Intersects``, ``ST_Contains``, ``ST_Within``,
|
||||
``ST_Touches``, ``ST_Crosses``, ``ST_Overlaps``, ``ST_Covers`` and
|
||||
``ST_CoveredBy`` between the indexed column and a constant geometry, in
|
||||
either argument order, for example
|
||||
``ST_Within(geom, ST_GeomFromText('POLYGON ((...))'))``, as well as
|
||||
``geom IS NULL``. These filters can be combined with other conditions
|
||||
using ``AND``.
|
||||
|
||||
See the R-tree section of <https://docs.lancedb.com/indexing/scalar-index>
|
||||
for storing geometry, the other spatial functions, and spatial filters on
|
||||
vector search.
|
||||
|
||||
Remote tables send the ``RTREE`` index type to the server, which must
|
||||
support it.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> config = RTree(page_size=1024)
|
||||
|
||||
Attributes
|
||||
----------
|
||||
page_size : int, optional
|
||||
The maximum number of entries in each R-tree page. Must be at least 2.
|
||||
``None`` uses Lance's default of 4096.
|
||||
"""
|
||||
|
||||
page_size: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScalarPlugin:
|
||||
"""Configure a scalar index of a type recognized by a registered database plugin.
|
||||
|
||||
Use this for index types without a dedicated configuration class.
|
||||
Prefer a dedicated class, such as [BTree][lancedb.index.BTree], when one
|
||||
is available.
|
||||
|
||||
An unknown plugin name or invalid parameters cause index creation to fail.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> from lancedb.index import ScalarPlugin
|
||||
>>> ScalarPlugin("bloomfilter", params={"number_of_items": 4096})
|
||||
ScalarPlugin(index_type='bloomfilter', params={'number_of_items': 4096})
|
||||
|
||||
Pass it as ``config`` to ``create_index``:
|
||||
|
||||
>>> table.create_index( # doctest: +SKIP
|
||||
... "id",
|
||||
... config=ScalarPlugin("bloomfilter", '{"probability": 0.01}'),
|
||||
... )
|
||||
|
||||
Attributes
|
||||
----------
|
||||
index_type: str
|
||||
The index type, case-insensitive. Surrounding whitespace is ignored.
|
||||
Must not be empty.
|
||||
params: dict or str, optional
|
||||
The index parameters, as a dict or as a string holding a JSON object.
|
||||
They are passed as given. Each plugin defines its parameters and
|
||||
defaults; refer to the plugin's documentation for guidance.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If ``index_type`` is empty, or ``params`` is a string that is not a
|
||||
JSON object.
|
||||
TypeError
|
||||
If ``index_type`` is not a string, or ``params`` is not a dict, a
|
||||
string or None.
|
||||
"""
|
||||
|
||||
index_type: str
|
||||
params: Optional[Union[Dict[str, Any], str]] = None
|
||||
|
||||
def __post_init__(self):
|
||||
if not isinstance(self.index_type, str):
|
||||
raise TypeError(
|
||||
"ScalarPlugin index_type must be a str, got "
|
||||
+ type(self.index_type).__name__
|
||||
)
|
||||
if not self.index_type.strip():
|
||||
raise ValueError("ScalarPlugin index_type must not be empty")
|
||||
if isinstance(self.params, str):
|
||||
try:
|
||||
parsed = json.loads(self.params)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"ScalarPlugin params are not valid JSON: {e}") from e
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError(
|
||||
"ScalarPlugin params must be a JSON object, got "
|
||||
+ type(parsed).__name__
|
||||
)
|
||||
elif self.params is not None and not isinstance(self.params, dict):
|
||||
raise TypeError(
|
||||
"ScalarPlugin params must be a dict, a JSON string or None, got "
|
||||
+ type(self.params).__name__
|
||||
)
|
||||
|
||||
@property
|
||||
def _params_json(self) -> Optional[str]:
|
||||
# Read by the native layer, which checks again that this is an object.
|
||||
if self.params is None or isinstance(self.params, str):
|
||||
return self.params
|
||||
return json.dumps(self.params)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FTS:
|
||||
"""Describe a FTS index configuration.
|
||||
@@ -984,4 +1119,6 @@ __all__ = [
|
||||
"LabelList",
|
||||
"Fm",
|
||||
"NGram",
|
||||
"RTree",
|
||||
"ScalarPlugin",
|
||||
]
|
||||
|
||||
+858
-88
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
|
||||
from collections import deque
|
||||
from itertools import islice
|
||||
from operator import index
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Callable,
|
||||
Generic,
|
||||
Iterator,
|
||||
Optional,
|
||||
TypeVar,
|
||||
overload,
|
||||
)
|
||||
|
||||
from .background_loop import LOOP
|
||||
|
||||
@@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]):
|
||||
print(name)
|
||||
|
||||
Use ``list(connection.list_views())`` to collect all results.
|
||||
|
||||
Indexes and slices refer to the remaining items and do not consume them.
|
||||
A bounded forward slice, such as ``listing[:5]``, fetches only enough pages
|
||||
to reach its stop. ``len(listing)``, negative indexes, and open-ended or
|
||||
reverse slices fetch and cache all remaining results. Iteration then drains
|
||||
that cache. These operations may perform requests and raise request errors.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: AsyncListing[T]):
|
||||
self._inner = inner
|
||||
self._buffer: deque[T] = deque()
|
||||
|
||||
def __iter__(self) -> Listing[T]:
|
||||
return self
|
||||
|
||||
def __next__(self) -> T:
|
||||
if self._buffer:
|
||||
return self._buffer.popleft()
|
||||
try:
|
||||
return LOOP.run(self._inner.__anext__())
|
||||
except StopAsyncIteration:
|
||||
raise StopIteration from None
|
||||
|
||||
def _fill(self, count: Optional[int]) -> None:
|
||||
while count is None or len(self._buffer) < count:
|
||||
try:
|
||||
item = LOOP.run(self._inner.__anext__())
|
||||
except StopAsyncIteration:
|
||||
return
|
||||
self._buffer.append(item)
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""Fetch and cache every remaining item, returning the remaining count."""
|
||||
self._fill(None)
|
||||
return len(self._buffer)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
self._fill(1)
|
||||
return bool(self._buffer)
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: int) -> T: ...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: slice) -> list[T]: ...
|
||||
|
||||
def __getitem__(self, key: int | slice) -> T | list[T]:
|
||||
"""Read remaining items without consuming them; bounded slices stay lazy."""
|
||||
if isinstance(key, slice):
|
||||
start = 0 if key.start is None else index(key.start)
|
||||
stop = None if key.stop is None else index(key.stop)
|
||||
step = 1 if key.step is None else index(key.step)
|
||||
if step == 0:
|
||||
raise ValueError("slice step cannot be zero")
|
||||
if start >= 0 and stop is not None and stop >= 0 and step > 0:
|
||||
if start >= stop:
|
||||
return []
|
||||
self._fill(stop)
|
||||
start, stop, step = key.indices(len(self._buffer))
|
||||
return list(
|
||||
islice(self._buffer, start, stop, min(step, len(self._buffer) + 1))
|
||||
)
|
||||
self._fill(None)
|
||||
return list(self._buffer)[key]
|
||||
position = index(key)
|
||||
self._fill(None if position < 0 else position + 1)
|
||||
return self._buffer[position]
|
||||
|
||||
def num_page_results(self) -> int:
|
||||
"""Return the number of cached items available without another request."""
|
||||
return self._inner.num_page_results()
|
||||
return len(self._buffer) + self._inner.num_page_results()
|
||||
|
||||
def page_token(self) -> Optional[str]:
|
||||
"""Return the next request's token.
|
||||
|
||||
See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token]
|
||||
for initial, cached, final-page, and error behavior.
|
||||
Indexing, slicing, and counting can also advance this token; drain all
|
||||
``num_page_results()`` cached items before resuming from it.
|
||||
"""
|
||||
return self._inner.page_token()
|
||||
|
||||
@@ -175,6 +243,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]):
|
||||
class AsyncTableListing(_AsyncPagedNameListing):
|
||||
"""Awaitable table iterator; awaiting loads one page.
|
||||
|
||||
Iteration fetches all pages. The ``tables`` attribute contains only the
|
||||
current page, so use ``await db.table_exists([name])`` for existence checks.
|
||||
|
||||
For example::
|
||||
|
||||
page = await db.list_tables(limit=20)
|
||||
@@ -229,6 +300,10 @@ class _PagedNameListing(Iterator[str]):
|
||||
class TableListing(_PagedNameListing):
|
||||
"""Table iterator retaining the current page as a list.
|
||||
|
||||
Iteration fetches all pages. The ``tables`` attribute contains only the
|
||||
current page, so use ``db.table_exists([name])`` or ``name in db`` for
|
||||
existence checks. Use ``list(db.list_tables())`` to collect all names.
|
||||
|
||||
For example::
|
||||
|
||||
page = db.list_tables(limit=20)
|
||||
@@ -239,6 +314,7 @@ class TableListing(_PagedNameListing):
|
||||
|
||||
@property
|
||||
def tables(self) -> list[str]:
|
||||
"""A copy of the table names in the most recently fetched page."""
|
||||
return self._inner.tables
|
||||
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ from dataclasses import dataclass
|
||||
|
||||
from .background_loop import LOOP
|
||||
from .job import AsyncJob, Job, _typed_job
|
||||
from .resources import _resource_options
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pyarrow as pa
|
||||
@@ -133,6 +134,16 @@ def _quote_identifier(name: str) -> str:
|
||||
return f"`{escaped}`"
|
||||
|
||||
|
||||
def _validate_create_materialized_view(source, query, select, where, limit):
|
||||
if query is not None:
|
||||
if any(value is not None for value in (source, select, where, limit)):
|
||||
raise ValueError(
|
||||
"query cannot be combined with source, select, where or limit"
|
||||
)
|
||||
elif source is None:
|
||||
raise ValueError("either source or query must be provided")
|
||||
|
||||
|
||||
def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
|
||||
"""``select`` items may be a column name, an ``(alias, expression)`` pair,
|
||||
or a dict of the same. A bare name projects itself and is quoted, so any
|
||||
@@ -156,6 +167,19 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
|
||||
return normalized
|
||||
|
||||
|
||||
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}
|
||||
|
||||
|
||||
class AsyncMaterializedView:
|
||||
"""A handle on a materialized view: its table plus its definition.
|
||||
|
||||
@@ -185,7 +209,15 @@ class AsyncMaterializedView:
|
||||
return _definition_from_json(raw)
|
||||
|
||||
async def refresh(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
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.
|
||||
|
||||
@@ -194,16 +226,43 @@ class AsyncMaterializedView:
|
||||
and ``source_version`` selects a source version instead of the latest.
|
||||
LanceDB Enterprise SQL refreshes do not support source-version pinning.
|
||||
|
||||
``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.
|
||||
|
||||
LanceDB Enterprise results leave ``mode``, ``rows_written``, and
|
||||
``source_version`` as ``None`` because the SQL job adapter does not expose
|
||||
these metrics.
|
||||
"""
|
||||
return await self._table._inner.refresh_materialized_view(
|
||||
source_version=source_version, full=full
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
)
|
||||
|
||||
async def refresh_async(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: 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.
|
||||
|
||||
@@ -221,7 +280,15 @@ class AsyncMaterializedView:
|
||||
|
||||
return _typed_job(
|
||||
await self._table._inner.refresh_materialized_view_async(
|
||||
source_version=source_version, full=full
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
),
|
||||
RefreshMaterializedViewResult.from_json,
|
||||
)
|
||||
@@ -253,14 +320,42 @@ class MaterializedView:
|
||||
return LOOP.run(self._async.definition())
|
||||
|
||||
def refresh(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
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]."""
|
||||
return LOOP.run(self._async.refresh(full=full, source_version=source_version))
|
||||
return LOOP.run(
|
||||
self._async.refresh(
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
def refresh_async(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: 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.
|
||||
|
||||
@@ -269,6 +364,16 @@ class MaterializedView:
|
||||
"""
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._async.refresh_async(full=full, source_version=source_version)
|
||||
self._async.refresh_async(
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object):
|
||||
on_bad_vectors: str = "error",
|
||||
fill_value: float = 0.0,
|
||||
timeout: Optional[timedelta] = None,
|
||||
*,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeInsertResult:
|
||||
"""
|
||||
Executes the merge insert operation
|
||||
@@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object):
|
||||
first attempt will not be cancelled.
|
||||
|
||||
When this is set, the timeout is enforced on all attempts, including
|
||||
the first.
|
||||
the first. For remote tables it is sent as a server execution timeout;
|
||||
it does not extend HTTP read or proxy idle timeouts, or prove that a
|
||||
failed request did not commit.
|
||||
retries: int, optional
|
||||
Override the remote retry budget for this execution only (0 to 255).
|
||||
Use ``execute(new_data, retries=0)`` to disable even retries after
|
||||
precommit conflicts (409) or rate limits (429). This does not change
|
||||
connection-wide/read budgets or local transaction conflict retries.
|
||||
|
||||
By default, remote calls use the connection's
|
||||
[RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set
|
||||
through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within
|
||||
the retry budget; it never permits replay of ambiguous merge outcomes.
|
||||
In particular, 502, ordinary 503, and 504 are never replayed, even if
|
||||
configured. Reconcile table contents before manually repeating a merge
|
||||
whose commit outcome is unknown.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object):
|
||||
"""
|
||||
if timeout is not None:
|
||||
self._timeout = timeout
|
||||
return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
|
||||
return self._table._do_merge(
|
||||
self, new_data, on_bad_vectors, fill_value, retries=retries
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ through a namespace abstraction.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
from typing import Any, Dict, Iterable, List, Optional, Union
|
||||
@@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import (
|
||||
QueryTableRequestVector,
|
||||
)
|
||||
from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery
|
||||
from lance_namespace_urllib3_client.models.structured_fts_query import (
|
||||
StructuredFtsQuery,
|
||||
)
|
||||
from lance_namespace.errors import (
|
||||
NamespaceNotEmptyError,
|
||||
NamespaceNotFoundError,
|
||||
@@ -78,6 +82,7 @@ from lancedb.materialized_view import (
|
||||
SelectArg,
|
||||
)
|
||||
from lancedb.table import AsyncTable, LanceTable, Table
|
||||
from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery
|
||||
from lancedb.util import validate_table_name
|
||||
from lancedb.common import DATA
|
||||
from lancedb.pydantic import LanceModel
|
||||
@@ -178,6 +183,26 @@ def _query_to_namespace_request(
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
string_query=StringFtsQuery(query=fts_query)
|
||||
)
|
||||
elif getattr(fts_query, "operator", None) is not None:
|
||||
columns = fts_query.columns or []
|
||||
text = fts_query.query
|
||||
if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
|
||||
if len(columns) > 1:
|
||||
raise ValueError(
|
||||
"Phrase queries cannot be used with multiple columns."
|
||||
)
|
||||
structured = PhraseQuery(text[1:-1], columns[0] if columns else None)
|
||||
elif len(columns) > 1:
|
||||
structured = MultiMatchQuery(text, columns, operator=fts_query.operator)
|
||||
else:
|
||||
structured = MatchQuery(
|
||||
text, columns[0] if columns else None, operator=fts_query.operator
|
||||
)
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
structured_query=StructuredFtsQuery.from_dict(
|
||||
{"query": json.loads(structured.to_json())}
|
||||
)
|
||||
)
|
||||
elif hasattr(fts_query, "query"):
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
string_query=StringFtsQuery(
|
||||
@@ -484,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
Supported values:
|
||||
|
||||
- "QueryTable": Execute queries on the namespace server via
|
||||
namespace.query_table() instead of locally.
|
||||
namespace.query_table() instead of locally. Queries with a
|
||||
nonempty ``order_by`` or an explicit ``scan_in_order(True)``
|
||||
execute on the client and require access to the table storage.
|
||||
- "CreateTable": Execute table creation on the namespace server via
|
||||
namespace.create_table() instead of using declare_table + local write.
|
||||
|
||||
@@ -559,7 +586,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
"storage_options": self.storage_options or None,
|
||||
"read_consistency_interval_seconds": (
|
||||
self.read_consistency_interval.total_seconds()
|
||||
if self.read_consistency_interval
|
||||
if self.read_consistency_interval is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
@@ -579,12 +606,15 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
If limit is None, return all table names; zero returns an empty list.
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`list_tables` instead, which provides proper pagination support.
|
||||
Iterate over :meth:`list_tables` to get all names, or use
|
||||
:meth:`table_exists` to check for a particular table. The listing's
|
||||
``tables`` attribute contains only one page.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"table_names() is deprecated, use list_tables() instead",
|
||||
"table_names() is deprecated, iterate list_tables() for all names "
|
||||
"or use table_exists([name]) to check existence",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -612,6 +642,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
@@ -633,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
embedding_functions=embedding_functions,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -640,6 +674,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self,
|
||||
name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
namespace_client=self._namespace_client,
|
||||
pushdown_operations=self._namespace_client_pushdown_operations,
|
||||
route_pushdown_to_rust=self._route_pushdown_to_rust,
|
||||
@@ -678,6 +713,7 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self,
|
||||
name,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
namespace_client=self._namespace_client,
|
||||
pushdown_operations=self._namespace_client_pushdown_operations,
|
||||
route_pushdown_to_rust=self._route_pushdown_to_rust,
|
||||
@@ -693,14 +729,21 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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.
|
||||
See
|
||||
@@ -712,12 +755,19 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
self._inner.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
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
|
||||
)
|
||||
@@ -727,25 +777,39 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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(
|
||||
self._inner.create_materialized_view_async(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
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)
|
||||
@@ -1015,6 +1079,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
bool
|
||||
True if the table exists, False otherwise.
|
||||
"""
|
||||
if self._route_pushdown_to_rust:
|
||||
return LOOP.run(self._inner.table_exists(table_id))
|
||||
request = TableExistsRequest(id=table_id)
|
||||
try:
|
||||
self._namespace_client.table_exists(request)
|
||||
@@ -1030,7 +1096,11 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
limit: Optional[int] = None,
|
||||
) -> TableListing:
|
||||
"""
|
||||
List all tables in this database with pagination support.
|
||||
Iterate over all tables in this database, fetching pages as needed.
|
||||
|
||||
The ``tables`` attribute contains only the current page (100 names by
|
||||
default). Iterate over the listing to visit all pages, or use
|
||||
``table_exists([name])`` to check for a particular table.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -1090,6 +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,
|
||||
@@ -1163,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.
|
||||
|
||||
@@ -1227,12 +1300,15 @@ class AsyncLanceNamespaceDBConnection:
|
||||
If limit is None, return all table names; zero returns an empty list.
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`list_tables` instead, which provides proper pagination support.
|
||||
Iterate over :meth:`list_tables` to get all names, or use
|
||||
:meth:`table_exists` to check for a particular table. The listing's
|
||||
``tables`` attribute contains only one page.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"table_names() is deprecated, use list_tables() instead",
|
||||
"table_names() is deprecated, iterate list_tables() for all names "
|
||||
"or use table_exists([name]) to check existence",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -1257,6 +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:
|
||||
@@ -1278,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,
|
||||
@@ -1327,25 +1407,39 @@ class AsyncLanceNamespaceDBConnection:
|
||||
async def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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."""
|
||||
view = await self._inner.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
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.
|
||||
@@ -1354,25 +1448,39 @@ class AsyncLanceNamespaceDBConnection:
|
||||
async def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: "SelectArg" = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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."""
|
||||
return await self._inner.create_materialized_view_async(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
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":
|
||||
@@ -1614,6 +1722,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
bool
|
||||
True if the table exists, False otherwise.
|
||||
"""
|
||||
if self._route_pushdown_to_rust:
|
||||
return await self._inner.table_exists(table_id)
|
||||
request = TableExistsRequest(id=table_id)
|
||||
try:
|
||||
self._namespace_client.table_exists(request)
|
||||
@@ -1628,7 +1738,11 @@ class AsyncLanceNamespaceDBConnection:
|
||||
limit: Optional[int] = None,
|
||||
) -> AsyncTableListing:
|
||||
"""
|
||||
List all tables in this database with pagination support.
|
||||
Iterate over all tables in this database, fetching pages as needed.
|
||||
|
||||
The ``tables`` attribute contains only the current page (100 names by
|
||||
default). Iterate over the listing to visit all pages, or use
|
||||
``table_exists([name])`` to check for a particular table.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -1658,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(
|
||||
@@ -1672,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.
|
||||
|
||||
@@ -1681,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:
|
||||
@@ -1749,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.
|
||||
|
||||
@@ -1840,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())
|
||||
|
||||
@@ -405,11 +512,100 @@ class Transforms:
|
||||
# HuggingFace uses 10 which is pretty small
|
||||
DEFAULT_BATCH_SIZE = 100
|
||||
|
||||
_MAP_FORMAT_ERROR = (
|
||||
"map cannot be combined with with_format or with_transform; convert the "
|
||||
"output inside the map callback or in the DataLoader collate_fn instead"
|
||||
)
|
||||
|
||||
|
||||
def _map_rows(data: Any, num_rows: int) -> list[dict[str, Any]]:
|
||||
"""Return the data flowing through a map chain as a list of row dicts."""
|
||||
if isinstance(data, pa.RecordBatch):
|
||||
return data.to_pylist()
|
||||
if isinstance(data, dict):
|
||||
return [
|
||||
{name: values[i] for name, values in data.items()} for i in range(num_rows)
|
||||
]
|
||||
return data
|
||||
|
||||
|
||||
def _map_columns(data: Any) -> dict[str, Any]:
|
||||
"""Return the data flowing through a map chain as a dict of columns."""
|
||||
if isinstance(data, pa.RecordBatch):
|
||||
return data.to_pydict()
|
||||
if isinstance(data, list):
|
||||
names = data[0].keys()
|
||||
if any(row.keys() != names for row in data):
|
||||
raise ValueError(
|
||||
"Cannot pass rows to a batched map callback because the previous "
|
||||
"callback did not return the same keys for every row"
|
||||
)
|
||||
return {name: [row[name] for row in data] for name in names}
|
||||
return data
|
||||
|
||||
|
||||
class _MapTransform:
|
||||
"""
|
||||
The transform installed by [map][lancedb.permutation.Permutation.map]
|
||||
|
||||
Each step is a ``(fn, batched)`` pair. This is a module-level class, and not a
|
||||
closure, so that a mapped permutation pickles whenever its callbacks do.
|
||||
"""
|
||||
|
||||
def __init__(self, steps: tuple[tuple[Callable, bool], ...]):
|
||||
self.steps = steps
|
||||
|
||||
def __call__(self, batch: pa.RecordBatch) -> list[dict[str, Any]]:
|
||||
num_rows = batch.num_rows
|
||||
if num_rows == 0:
|
||||
return []
|
||||
|
||||
# The layout is only converted when a callback needs the other one
|
||||
data = batch
|
||||
for fn, batched in self.steps:
|
||||
if batched:
|
||||
data = fn(_map_columns(data))
|
||||
if not isinstance(data, dict):
|
||||
raise TypeError(
|
||||
"A batched map callback must return a dict of columns, "
|
||||
f"got {type(data).__name__}"
|
||||
)
|
||||
for name, values in data.items():
|
||||
# A str or dict can be indexed but is not a column of values
|
||||
if isinstance(values, (str, bytes, dict)) or not hasattr(
|
||||
values, "__getitem__"
|
||||
):
|
||||
raise TypeError(
|
||||
"A batched map callback must return a list of values "
|
||||
f"for column `{name}`, got {type(values).__name__}"
|
||||
)
|
||||
if len(values) != num_rows:
|
||||
raise ValueError(
|
||||
f"A batched map callback returned {len(values)} values "
|
||||
f"for column `{name}` but the batch has {num_rows} rows"
|
||||
)
|
||||
else:
|
||||
data = [fn(row) for row in _map_rows(data, num_rows)]
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
raise TypeError(
|
||||
"A map callback must return a dict for each row, "
|
||||
f"got {type(row).__name__}"
|
||||
)
|
||||
return _map_rows(data, num_rows)
|
||||
|
||||
|
||||
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 +614,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 +635,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 +686,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
|
||||
@@ -495,10 +701,16 @@ class Permutation:
|
||||
self.split = split
|
||||
self.selection = selection
|
||||
self.transform_fn = transform_fn
|
||||
# Whether the default transform was replaced, by with_format, by
|
||||
# with_transform, or by a caller passing its own transform here
|
||||
self._explicit_transform = transform_fn is not Transforms.arrow2python
|
||||
self.batch_size = batch_size
|
||||
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 +850,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 +868,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 +891,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 +913,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,37 +925,59 @@ 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,
|
||||
"transform_fn": self.transform_fn,
|
||||
"explicit_transform": self._explicit_transform,
|
||||
"offset": self.offset,
|
||||
"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,27 +1009,99 @@ 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"]
|
||||
self.transform_fn = state["transform_fn"]
|
||||
# Pickles written before this flag existed still carry their transform.
|
||||
# Anything but the default must have been set explicitly.
|
||||
self._explicit_transform = state.get(
|
||||
"explicit_transform", self.transform_fn is not Transforms.arrow2python
|
||||
)
|
||||
self.offset = state["offset"]
|
||||
self.limit = state["limit"]
|
||||
self.connection_factory = connection_factory
|
||||
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 +1331,7 @@ class Permutation:
|
||||
"pandas",
|
||||
"arrow",
|
||||
"torch",
|
||||
"torch_dict",
|
||||
"torch_row",
|
||||
"torch_col",
|
||||
"polars",
|
||||
@@ -1019,34 +1343,68 @@ 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
|
||||
overrides this method.
|
||||
|
||||
A format cannot be combined with
|
||||
[map][lancedb.permutation.Permutation.map], which always yields a list
|
||||
of dicts. Doing so raises a ValueError.
|
||||
"""
|
||||
assert format is not None, "format is required"
|
||||
# Checked before with_transform does, so that a format with an optional
|
||||
# dependency cannot fail on its import first
|
||||
if isinstance(self.transform_fn, _MapTransform):
|
||||
raise ValueError(_MAP_FORMAT_ERROR)
|
||||
if format == "python":
|
||||
return self.with_transform(Transforms.arrow2python)
|
||||
if format == "python_col":
|
||||
@@ -1059,6 +1417,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":
|
||||
@@ -1077,10 +1437,109 @@ class Permutation:
|
||||
|
||||
Note: transforms are not invoked in parallel. This method is not a good place
|
||||
for expensive operations such as image decoding.
|
||||
|
||||
For a higher-level API that works with Python dicts, see
|
||||
[map][lancedb.permutation.Permutation.map]. A transform cannot be combined
|
||||
with ``map``. Doing so raises a ValueError.
|
||||
"""
|
||||
assert transform is not None, "transform is required"
|
||||
if isinstance(self.transform_fn, _MapTransform):
|
||||
raise ValueError(_MAP_FORMAT_ERROR)
|
||||
new = copy.copy(self)
|
||||
new.transform_fn = transform
|
||||
new._explicit_transform = True
|
||||
return new
|
||||
|
||||
def map(
|
||||
self,
|
||||
fn: Callable[[dict[str, Any]], dict[str, Any]],
|
||||
*,
|
||||
batched: bool = False,
|
||||
) -> "Permutation":
|
||||
"""
|
||||
Apply a function to the rows of the permutation
|
||||
|
||||
This is a dict-based alternative to
|
||||
[with_transform][lancedb.permutation.Permutation.with_transform], loosely
|
||||
modeled after the huggingface ``Dataset.map``. It is lazy: ``fn`` is not
|
||||
called until data is read.
|
||||
|
||||
Calls to ``map`` can be chained. The callbacks run in order and the dict
|
||||
returned by a callback replaces the row entirely, so the next callback only
|
||||
sees what the previous one returned. Unlike the huggingface method, the
|
||||
returned dict is not merged into the row: return every column to keep.
|
||||
|
||||
A mapped permutation always yields a list of dicts (one per row) for each
|
||||
batch, which is the same shape as the default "python" format. ``batched``
|
||||
only controls what ``fn`` receives. Rows keep their position, so a callback
|
||||
cannot add, drop, or reorder rows.
|
||||
|
||||
Since ``map`` decides the output format it cannot be combined with
|
||||
[with_format][lancedb.permutation.Permutation.with_format] or
|
||||
[with_transform][lancedb.permutation.Permutation.with_transform]. Calling
|
||||
one after the other, in either order, raises a ValueError. Convert the
|
||||
mapped rows to tensors in the DataLoader ``collate_fn`` instead.
|
||||
|
||||
[select_columns][lancedb.permutation.Permutation.select_columns],
|
||||
[remove_columns][lancedb.permutation.Permutation.remove_columns],
|
||||
[rename_column][lancedb.permutation.Permutation.rename_column] and
|
||||
[schema][lancedb.permutation.Permutation.schema] describe the columns read
|
||||
from the base table, which are the input of the first callback. They do
|
||||
not describe the output of ``map``, whether they are used before or after it.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
fn: Callable
|
||||
The function to apply. It receives and returns a single row as a dict
|
||||
mapping column names to values. If ``batched`` is True it instead
|
||||
receives and returns a whole batch as a dict mapping column names to
|
||||
lists of values, and every returned column must have one value per
|
||||
input row.
|
||||
|
||||
DataLoader workers started with ``spawn`` or ``forkserver`` receive a
|
||||
pickled copy of the permutation, so ``fn`` must then be picklable.
|
||||
Use a top-level function; lambdas and local functions do not pickle.
|
||||
batched: bool, default False
|
||||
Whether ``fn`` is called once per batch instead of once per row.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory:///")
|
||||
>>> tbl = db.create_table("tbl", data=[{"x": x} for x in range(3)])
|
||||
>>> def add_y(row):
|
||||
... return {**row, "y": row["x"] * 2}
|
||||
>>> def add_z(batch):
|
||||
... return {**batch, "z": [x + y for x, y in zip(batch["x"], batch["y"])]}
|
||||
>>> permutation = Permutation.identity(tbl).map(add_y).map(add_z, batched=True)
|
||||
>>> permutation.take_offsets([0, 1])
|
||||
[{'x': 0, 'y': 0, 'z': 0}, {'x': 1, 'y': 2, 'z': 3}]
|
||||
|
||||
With a PyTorch DataLoader, a ``collate_fn`` turns the mapped rows of each
|
||||
batch into tensors::
|
||||
|
||||
import torch
|
||||
|
||||
def collate(rows):
|
||||
return {
|
||||
"x": torch.tensor([row["x"] for row in rows]),
|
||||
"z": torch.tensor([row["z"] for row in rows]),
|
||||
}
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation, batch_size=32, shuffle=True, collate_fn=collate
|
||||
)
|
||||
"""
|
||||
if not callable(fn):
|
||||
raise TypeError("fn must be callable")
|
||||
if self._explicit_transform:
|
||||
raise ValueError(_MAP_FORMAT_ERROR)
|
||||
|
||||
steps = ((fn, batched),)
|
||||
if isinstance(self.transform_fn, _MapTransform):
|
||||
steps = self.transform_fn.steps + steps
|
||||
new = copy.copy(self)
|
||||
new.transform_fn = _MapTransform(steps)
|
||||
return new
|
||||
|
||||
def take_offsets(self, offsets: list[int]) -> Any:
|
||||
@@ -1088,8 +1547,8 @@ class Permutation:
|
||||
Take rows from the permutation by offset
|
||||
|
||||
The returned value is passed through the permutation's current transform,
|
||||
so `with_format` and `with_transform` affect this method in the same way
|
||||
they affect iteration.
|
||||
so `with_format`, `with_transform`, and `map` affect this method in the
|
||||
same way they affect iteration.
|
||||
"""
|
||||
self._ensure_open()
|
||||
|
||||
|
||||
@@ -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))
|
||||
+1238
-197
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from lancedb.server_info import ServerInfo
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import timedelta
|
||||
import json
|
||||
@@ -37,8 +39,8 @@ import pyarrow as pa
|
||||
|
||||
from ..common import DATA
|
||||
from lancedb.listing import Listing, NamespaceListing, TableListing
|
||||
from ..db import DBConnection, LOOP
|
||||
from ..functions import FunctionVersion, UdfDefinition
|
||||
from ..db import DBConnection, LOOP, _normalize_function_version
|
||||
from ..functions import FunctionVersion, FunctionDefinition
|
||||
from ..graph import EdgeTable, NodeTable, PropertyGraph
|
||||
from ..job import AsyncJob, Job
|
||||
from ..sql import Query as SqlQuery
|
||||
@@ -60,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]:
|
||||
@@ -214,6 +217,7 @@ class RemoteDBConnection(DBConnection):
|
||||
client_config,
|
||||
oauth_config,
|
||||
sql_host_override,
|
||||
storage_options,
|
||||
):
|
||||
config = (
|
||||
ClientConfig(**client_config)
|
||||
@@ -233,7 +237,7 @@ class RemoteDBConnection(DBConnection):
|
||||
result.region = "us-east-1"
|
||||
result.host_override = endpoint
|
||||
result.sql_host_override = sql_host_override
|
||||
result.storage_options = None
|
||||
result.storage_options = storage_options
|
||||
result.client_config = replace(config, extra_headers=headers)
|
||||
result._catalog_oauth = oauth_config is not None
|
||||
result._conn = inner
|
||||
@@ -430,7 +434,11 @@ class RemoteDBConnection(DBConnection):
|
||||
page_token: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> TableListing:
|
||||
"""List a page of tables in this database.
|
||||
"""Iterate over all tables in this database, fetching pages as needed.
|
||||
|
||||
The ``tables`` attribute contains only the current page (100 names by
|
||||
default). Iterate over the listing to visit all pages, or use
|
||||
``table_exists([name])`` to check for a particular table.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -468,7 +476,9 @@ class RemoteDBConnection(DBConnection):
|
||||
"""List the names of all tables in the database.
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`list_tables` instead, which provides proper pagination support.
|
||||
Iterate over :meth:`list_tables` to get all names, or use
|
||||
:meth:`table_exists` to check for a particular table. The listing's
|
||||
``tables`` attribute contains only one page.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -488,7 +498,8 @@ class RemoteDBConnection(DBConnection):
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"table_names() is deprecated, use list_tables() instead",
|
||||
"table_names() is deprecated, iterate list_tables() for all names "
|
||||
"or use table_exists([name]) to check existence",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -566,6 +577,7 @@ class RemoteDBConnection(DBConnection):
|
||||
source_version: Optional[int] = None,
|
||||
source_tag: Optional[str] = None,
|
||||
is_shallow: bool = True,
|
||||
exist_ok: bool = False,
|
||||
) -> Table:
|
||||
"""Clone a table from a source table.
|
||||
|
||||
@@ -585,6 +597,8 @@ class RemoteDBConnection(DBConnection):
|
||||
is_shallow: bool, default True
|
||||
Whether to perform a shallow clone (True) or deep clone (False).
|
||||
Currently only shallow clone is supported.
|
||||
exist_ok: bool, default False
|
||||
Return the existing target unchanged instead of cloning over it.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -602,6 +616,7 @@ class RemoteDBConnection(DBConnection):
|
||||
source_version=source_version,
|
||||
source_tag=source_tag,
|
||||
is_shallow=is_shallow,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
)
|
||||
return RemoteTable(
|
||||
@@ -627,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.
|
||||
|
||||
@@ -672,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
|
||||
-------
|
||||
@@ -747,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"
|
||||
@@ -782,27 +813,48 @@ class RemoteDBConnection(DBConnection):
|
||||
def create_materialized_view(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: SelectArg = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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(
|
||||
self._conn.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
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(
|
||||
@@ -818,25 +870,46 @@ class RemoteDBConnection(DBConnection):
|
||||
def create_materialized_view_async(
|
||||
self,
|
||||
name: str,
|
||||
source: MaterializedViewSource,
|
||||
source: Optional[MaterializedViewSource] = None,
|
||||
*,
|
||||
query: Optional[str] = None,
|
||||
select: SelectArg = None,
|
||||
where: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
with_no_data: bool = False,
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
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,
|
||||
source,
|
||||
query=query,
|
||||
select=select,
|
||||
where=where,
|
||||
limit=limit,
|
||||
with_no_data=with_no_data,
|
||||
exist_ok=exist_ok,
|
||||
auto_refresh_enabled=auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
|
||||
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)
|
||||
@@ -958,6 +1031,13 @@ class RemoteDBConnection(DBConnection):
|
||||
"""
|
||||
return Job(LOOP.run(self._conn.open_job(job_id)))
|
||||
|
||||
@override
|
||||
def server_info(self) -> ServerInfo:
|
||||
"""Read the responding server's build information. See
|
||||
[DBConnection.server_info][lancedb.db.DBConnection.server_info].
|
||||
"""
|
||||
return LOOP.run(self._conn.server_info())
|
||||
|
||||
@override
|
||||
def list_gpu_classes(self) -> List[GpuClass]:
|
||||
"""List configured Function GPU classes. See
|
||||
@@ -968,14 +1048,20 @@ class RemoteDBConnection(DBConnection):
|
||||
@override
|
||||
def create_function_async(
|
||||
self,
|
||||
definition: UdfDefinition,
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
) -> Job[FunctionVersion]:
|
||||
job = LOOP.run(
|
||||
self._conn.create_function_async(
|
||||
definition, secrets=secrets, namespace_path=namespace_path
|
||||
definition,
|
||||
secrets=secrets,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -985,9 +1071,10 @@ class RemoteDBConnection(DBConnection):
|
||||
self,
|
||||
name: str,
|
||||
*,
|
||||
version: str,
|
||||
version: Optional[Union[int, str]] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> FunctionVersion:
|
||||
version = _normalize_function_version(version)
|
||||
return LOOP.run(
|
||||
self._conn.get_function(
|
||||
name, version=version, namespace_path=namespace_path
|
||||
@@ -1024,11 +1111,14 @@ class RemoteDBConnection(DBConnection):
|
||||
version: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> bool:
|
||||
return LOOP.run(
|
||||
self._conn.drop_function(
|
||||
dropped, drop_warnings = LOOP.run(
|
||||
self._conn._drop_function_with_warnings(
|
||||
name, version=version, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
for warning in drop_warnings:
|
||||
warnings.warn(warning, UserWarning, stacklevel=2)
|
||||
return dropped
|
||||
|
||||
@override
|
||||
def drop_function_async(
|
||||
@@ -1060,8 +1150,12 @@ class RemoteDBConnection(DBConnection):
|
||||
azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_storage_account_access_key_secret: Optional[
|
||||
Union[str, SecretReference]
|
||||
] = None,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> StorageIntegrationInfo:
|
||||
return LOOP.run(
|
||||
@@ -1077,8 +1171,10 @@ class RemoteDBConnection(DBConnection):
|
||||
azure_tenant_id_secret=azure_tenant_id_secret,
|
||||
azure_client_id_secret=azure_client_id_secret,
|
||||
azure_client_secret_secret=azure_client_secret_secret,
|
||||
azure_storage_account_access_key_secret=azure_storage_account_access_key_secret,
|
||||
gcp_credentials_json_secret=gcp_credentials_json_secret,
|
||||
huggingface_token_secret=huggingface_token_secret,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
)
|
||||
)
|
||||
@@ -1117,9 +1213,18 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def create_secret(
|
||||
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
value: str,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> None:
|
||||
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
|
||||
LOOP.run(
|
||||
self._conn.create_secret(
|
||||
name, value, exist_ok=exist_ok, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def alter_secret(
|
||||
@@ -1163,10 +1268,17 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def create_view(
|
||||
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
|
||||
self,
|
||||
name: str,
|
||||
query: str,
|
||||
*,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> ViewDescription:
|
||||
return LOOP.run(
|
||||
self._conn.create_view(name, query, namespace_path=namespace_path)
|
||||
self._conn.create_view(
|
||||
name, query, exist_ok=exist_ok, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
@@ -1267,16 +1379,52 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> Listing[JobInfo]:
|
||||
"""List server-side jobs across the database's tables.
|
||||
"""List server-side jobs, optionally filtered before pagination.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
|
||||
``page_token`` resumes from a saved token. Requests and errors occur during
|
||||
iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
``table`` names a table in ``namespace_path`` (the root by default).
|
||||
Listings include all branches of the table. A namespace filter requires
|
||||
``table``.
|
||||
``state`` uses registry states such as ``in_progress``, ``succeeded``,
|
||||
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
|
||||
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
|
||||
Creation-time bounds are Unix milliseconds, inclusive at
|
||||
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
|
||||
Resume a ``page_token`` with the same filters. Requests and errors occur
|
||||
during iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
|
||||
For example, to inspect up to five jobs without fetching all history::
|
||||
|
||||
jobs = db.list_jobs(table="events", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
"""
|
||||
return Listing(
|
||||
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
|
||||
self._conn.list_jobs(
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
table=table,
|
||||
namespace_path=namespace_path,
|
||||
state=state,
|
||||
job_type=job_type,
|
||||
job_types=job_types,
|
||||
created_at_gte_millis=created_at_gte_millis,
|
||||
created_at_lt_millis=created_at_lt_millis,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
@@ -1312,6 +1460,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.
|
||||
|
||||
@@ -1327,6 +1478,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,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -149,6 +149,8 @@ def _http_error_class(
|
||||
return input_class
|
||||
if error_code == "already_exists":
|
||||
return AlreadyExistsError
|
||||
if status_code == 409:
|
||||
return ConflictError
|
||||
if error_code != "not_found" or resource_kind is None:
|
||||
return None
|
||||
return {
|
||||
@@ -268,6 +270,80 @@ class AlreadyExistsError(HttpError):
|
||||
"""A remote resource already exists."""
|
||||
|
||||
|
||||
class ConflictError(HttpError):
|
||||
"""A remote operation conflicts with the current state of a resource.
|
||||
|
||||
For example, deleting a branch whose files are still needed by another
|
||||
branch raises this error. The server's reason is included in the message.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> error = HttpError("main depends on the branch's files", "req-1", 409)
|
||||
>>> isinstance(error, ConflictError)
|
||||
True
|
||||
>>> error.status_code
|
||||
409
|
||||
"""
|
||||
|
||||
|
||||
class ResponseInterruptedError(HttpError):
|
||||
"""A streamed query response stopped before the server finished sending it.
|
||||
|
||||
The batches already returned are valid, but the result is incomplete. The
|
||||
query is not retried automatically, because a new attempt would return those
|
||||
rows a second time. To read the same data in a new attempt, check out
|
||||
``table_version`` first.
|
||||
|
||||
Attributes
|
||||
----------
|
||||
batches: int
|
||||
The number of batches returned before the interruption.
|
||||
rows: int
|
||||
The number of rows in those batches.
|
||||
table_version: int or None
|
||||
The table version the response reflected, if the server reported it.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7)
|
||||
>>> isinstance(error, HttpError)
|
||||
True
|
||||
>>> (error.rows, error.table_version)
|
||||
(2048, 7)
|
||||
"""
|
||||
|
||||
# HttpError.__new__ takes HttpError's arguments, to choose a subclass.
|
||||
def __new__(cls, *args, **kwargs):
|
||||
return RuntimeError.__new__(cls)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
request_id: str,
|
||||
batches: int,
|
||||
rows: int,
|
||||
table_version: Optional[int] = None,
|
||||
is_transport_error: bool = False,
|
||||
):
|
||||
super().__init__(message, request_id, is_transport_error=is_transport_error)
|
||||
self.batches = batches
|
||||
self.rows = rows
|
||||
self.table_version = table_version
|
||||
|
||||
def __reduce__(self) -> tuple[type, tuple]:
|
||||
return (
|
||||
self.__class__,
|
||||
(
|
||||
str(self),
|
||||
self.request_id,
|
||||
self.batches,
|
||||
self.rows,
|
||||
self.table_version,
|
||||
self.is_transport_error,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError):
|
||||
"""A remote table was not found.
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ from typing import (
|
||||
import warnings
|
||||
|
||||
from lancedb import __version__
|
||||
from lancedb.sql import QueryParameters
|
||||
from lancedb._blob import BlobFile
|
||||
|
||||
from lancedb._lancedb import (
|
||||
@@ -34,6 +35,7 @@ from lancedb._lancedb import (
|
||||
DeleteResult,
|
||||
DropColumnsResult,
|
||||
FtsToken,
|
||||
FunctionColumnStatus,
|
||||
IndexConfig,
|
||||
RTEWriteSpec,
|
||||
MergeResult,
|
||||
@@ -47,8 +49,15 @@ 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 FunctionApplication, RefreshColumnResult
|
||||
from lancedb.functions import (
|
||||
FunctionProvenance,
|
||||
FunctionApplication,
|
||||
FunctionRetryPolicy,
|
||||
RefreshColumnResult,
|
||||
)
|
||||
from lancedb.remote.db import LOOP
|
||||
from lancedb.table import IndexConfigType, _maybe_add_fts_error_note
|
||||
import pyarrow as pa
|
||||
@@ -60,6 +69,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry
|
||||
from lancedb.table import _normalize_progress
|
||||
|
||||
from ..query import (
|
||||
FullTextOperator,
|
||||
AnalyzePlanDistributedMetrics,
|
||||
DocumentGranularity,
|
||||
FullTextQuery,
|
||||
@@ -71,9 +81,11 @@ from ..table import (
|
||||
BlobMode,
|
||||
Branches,
|
||||
CompactionOptions,
|
||||
CompactionResult,
|
||||
IndexStatistics,
|
||||
Query,
|
||||
Table,
|
||||
TableDelta,
|
||||
Tags,
|
||||
)
|
||||
from ..types import BaseTokenizerType, ScalarIndexType
|
||||
@@ -276,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)
|
||||
@@ -307,6 +332,16 @@ class RemoteTable(Table):
|
||||
)
|
||||
|
||||
def checkout(self, version: Union[int, str]):
|
||||
"""Check out a version number or tag as a read-only view in place.
|
||||
|
||||
A tag must belong to this handle's current branch. To read a tag on
|
||||
another branch, first obtain that branch's handle with
|
||||
`table.branches.checkout("branch_name")`, then call `checkout(tag)` on
|
||||
that handle. A tag on another branch raises an error without changing
|
||||
the current selection.
|
||||
|
||||
Call `checkout_latest()` to return to the latest version of this branch.
|
||||
"""
|
||||
result = LOOP.run(self._table.checkout(version))
|
||||
self._checkout_version = self.version
|
||||
return result
|
||||
@@ -364,6 +399,7 @@ class RemoteTable(Table):
|
||||
index_type: ScalarIndexType = "BTREE",
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
):
|
||||
"""Create a scalar index on a column.
|
||||
|
||||
@@ -390,6 +426,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -428,6 +465,7 @@ class RemoteTable(Table):
|
||||
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
):
|
||||
"""Create a full-text search index on a column.
|
||||
|
||||
@@ -487,6 +525,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
field_names,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
name=name,
|
||||
wait_timeout=wait_timeout,
|
||||
@@ -511,6 +550,7 @@ class RemoteTable(Table):
|
||||
replace: bool = ...,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
) -> None: ...
|
||||
|
||||
@@ -536,6 +576,7 @@ class RemoteTable(Table):
|
||||
*,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
target_partition_size: Optional[int] = ...,
|
||||
) -> None: ...
|
||||
@@ -567,6 +608,7 @@ class RemoteTable(Table):
|
||||
config: Optional[IndexConfigType] = None,
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
train: bool = True,
|
||||
target_partition_size: Optional[int] = None,
|
||||
):
|
||||
@@ -587,7 +629,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, ScalarPlugin, FTS.
|
||||
replace : bool, default True
|
||||
Whether to replace an existing index on this column.
|
||||
wait_timeout : timedelta, optional
|
||||
@@ -670,6 +712,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -685,6 +728,7 @@ class RemoteTable(Table):
|
||||
replace: Optional[bool] = None,
|
||||
wait_timeout: Optional[timedelta] = None,
|
||||
name: Optional[str] = None,
|
||||
exist_ok: bool = False,
|
||||
train: bool = True,
|
||||
) -> Job:
|
||||
"""Create an index, returning a handle to the indexing job.
|
||||
@@ -697,6 +741,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index_async(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -714,6 +759,7 @@ class RemoteTable(Table):
|
||||
progress: Optional[Union[bool, Callable, Any]] = None,
|
||||
write_parallelism: Optional[int] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
retries: Optional[int] = None,
|
||||
) -> AddResult:
|
||||
"""Add more data to the [Table][lancedb.table.Table].
|
||||
|
||||
@@ -748,6 +794,9 @@ class RemoteTable(Table):
|
||||
using too much memory.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Not supported in LanceDB Enterprise. Setting this raises.
|
||||
retries: int, optional
|
||||
Override the retry budget for this call (0 to 255). Zero disables
|
||||
retries, including multipart parts. Ambiguous commits are never replayed.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -765,6 +814,7 @@ class RemoteTable(Table):
|
||||
progress=progress,
|
||||
write_parallelism=write_parallelism,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
retries=retries,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -779,6 +829,8 @@ class RemoteTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceQueryBuilder:
|
||||
"""Create a search query to find the nearest neighbors
|
||||
of the given query vector. We currently support
|
||||
@@ -837,6 +889,10 @@ class RemoteTable(Table):
|
||||
|
||||
- *default None*, which leaves fast search disabled.
|
||||
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string full-text query; the default is OR.
|
||||
Use ``query_type="fts"`` when the table also has embeddings.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceQueryBuilder
|
||||
@@ -873,6 +929,7 @@ class RemoteTable(Table):
|
||||
ordering_field_name=ordering_field_name,
|
||||
fts_columns=fts_columns or [],
|
||||
fast_search=fast_search,
|
||||
operator=operator,
|
||||
)
|
||||
|
||||
def _execute_query(
|
||||
@@ -895,6 +952,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))
|
||||
|
||||
@@ -925,9 +990,10 @@ class RemoteTable(Table):
|
||||
new_data: DATA,
|
||||
on_bad_vectors: str,
|
||||
fill_value: float,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult:
|
||||
return LOOP.run(
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
|
||||
)
|
||||
|
||||
@_deprecated_keyword("predicate", "where")
|
||||
@@ -1060,7 +1126,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
|
||||
@@ -1075,6 +1142,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,
|
||||
*,
|
||||
@@ -1087,10 +1174,13 @@ class RemoteTable(Table):
|
||||
Enterprise job. Pruning old versions and index optimization are not
|
||||
yet supported remotely, so this call skips them and returns
|
||||
successfully with zeroed pruning statistics once the compaction job
|
||||
has been submitted; it does not wait for that job to finish. Passing
|
||||
a non-default ``compaction_options`` raises ``NotImplementedError``
|
||||
before anything is submitted, since there is no way yet to forward
|
||||
those settings to the server.
|
||||
has been submitted; it does not wait for that job to finish. The
|
||||
per-job options ``target_rows_per_fragment``, ``max_source_rows``,
|
||||
``io_buffer_size``, and ``batch_size`` are supported on compatible
|
||||
servers. Omitted fields inherit table tuning, then deployment/built-in
|
||||
defaults. Other non-default settings raise ``NotImplementedError``
|
||||
before submission. Errors from older servers are propagated without
|
||||
retrying with the settings removed.
|
||||
"""
|
||||
return LOOP.run(
|
||||
self._table.optimize(
|
||||
@@ -1120,6 +1210,9 @@ class RemoteTable(Table):
|
||||
computed: Dict[str, str] | None = None,
|
||||
auto_refresh_enabled: bool | None = None,
|
||||
auto_refresh_interval_seconds: int | None = 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(
|
||||
@@ -1127,6 +1220,9 @@ class RemoteTable(Table):
|
||||
computed=computed,
|
||||
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,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1134,16 +1230,60 @@ class RemoteTable(Table):
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
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,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
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(
|
||||
column,
|
||||
where=where,
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
publication_interval_rows=publication_interval_rows,
|
||||
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,
|
||||
max_failed_rows=max_failed_rows,
|
||||
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,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1151,31 +1291,129 @@ class RemoteTable(Table):
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
max_concurrency: Optional[int] = None,
|
||||
publication_interval_rows: Optional[int] = None,
|
||||
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,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
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(
|
||||
self._table.refresh_column_async(
|
||||
column,
|
||||
where=where,
|
||||
batch_size=batch_size,
|
||||
max_concurrency=max_concurrency,
|
||||
publication_interval_rows=publication_interval_rows,
|
||||
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,
|
||||
max_failed_rows=max_failed_rows,
|
||||
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(
|
||||
self, column: Optional[str] = None
|
||||
) -> list[FunctionColumnStatus]:
|
||||
return LOOP.run(self._table.column_statuses(column=column))
|
||||
|
||||
def column_status(self, column: str) -> FunctionColumnStatus:
|
||||
return LOOP.run(self._table.column_status(column))
|
||||
|
||||
def wait_fresh(
|
||||
self, column: str, timeout: Optional[timedelta] = None
|
||||
) -> FunctionColumnStatus:
|
||||
return LOOP.run(self._table.wait_fresh(column, timeout))
|
||||
|
||||
def alter_columns(
|
||||
self, *alterations: Iterable[Dict[str, str]]
|
||||
) -> AlterColumnsResult:
|
||||
@@ -1210,7 +1448,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]:
|
||||
@@ -1272,7 +1514,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
|
||||
@@ -1280,7 +1529,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
|
||||
@@ -1291,8 +1541,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)
|
||||
@@ -1311,9 +1615,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
|
||||
@@ -1349,13 +1659,20 @@ class RemoteTable(Table):
|
||||
self,
|
||||
column: str,
|
||||
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
|
||||
*,
|
||||
buffer_size: Optional[int] = None,
|
||||
) -> "list[Optional[BlobFile]]":
|
||||
return LOOP.run(self._table.fetch_blob_files(column, row_ids))
|
||||
return LOOP.run(
|
||||
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
|
||||
)
|
||||
|
||||
def open_blob_file(
|
||||
self, descriptor: Union[dict, pa.StructScalar, None]
|
||||
self,
|
||||
descriptor: Union[dict, pa.StructScalar, None],
|
||||
*,
|
||||
buffer_size: Optional[int] = None,
|
||||
) -> Optional[BlobFile]:
|
||||
return LOOP.run(self._table.open_blob_file(descriptor))
|
||||
return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
|
||||
|
||||
def head(self, n=5) -> pa.Table:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,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):
|
||||
@@ -122,6 +195,15 @@ def blob_v2_column_paths(schema: pa.Schema) -> list[str]:
|
||||
return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)]
|
||||
|
||||
|
||||
def row_addressable_blob_paths(schema: pa.Schema) -> list[str]:
|
||||
"""Blob v1 and v2 paths with one blob addressable by table row id."""
|
||||
return [
|
||||
path
|
||||
for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_like_field)
|
||||
if not has_list_ancestor
|
||||
]
|
||||
|
||||
|
||||
def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]:
|
||||
"""Blob v2 paths with one blob addressable by table row id.
|
||||
|
||||
@@ -335,6 +417,132 @@ def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def _blob_uint64(value: object, what: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
|
||||
if value < 0:
|
||||
raise ValueError(f"{what} must be non-negative")
|
||||
if value > _UINT64_MAX:
|
||||
raise OverflowError(f"{what} must fit in a uint64")
|
||||
return value
|
||||
|
||||
|
||||
def blob_uri_array(
|
||||
uris: Iterable[Optional[str]],
|
||||
*,
|
||||
positions: Optional[Iterable[Optional[int]]] = None,
|
||||
sizes: Optional[Iterable[Optional[int]]] = None,
|
||||
) -> pa.ExtensionArray:
|
||||
"""Build a Lance blob v2 extension array from external URIs.
|
||||
|
||||
Produces the standard four-field blob v2 storage (``data=None``, ``uri``,
|
||||
nullable ``position`` and ``size``) without requiring pylance, so the
|
||||
result can be used directly in Arrow record batches and combined with
|
||||
field metadata such as ``lancedb:logical_type="mp4"``.
|
||||
|
||||
A row without ``position`` and ``size`` references the whole object; a
|
||||
row with both reads exactly that byte range. Register the object prefix
|
||||
with [BasePath][lancedb.schema.BasePath] at table creation to store a
|
||||
matched URI relative to a base, or enable
|
||||
``allow_external_blob_outside_bases`` on the write that inserts the row to
|
||||
keep the absolute URI when no base matches. The opt-in covers that one
|
||||
write; a later ``add()`` must enable it again.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
uris:
|
||||
An iterable of absolute URI strings or ``None`` for a null blob. A
|
||||
URI under a registered base is matched and stored in the descriptor
|
||||
relative to that base. An unmatched URI requires the write that
|
||||
inserts the row to opt in with
|
||||
``allow_external_blob_outside_bases``, and must always be a valid
|
||||
absolute URI.
|
||||
positions:
|
||||
Optional byte offsets, one per URI. Provide together with ``sizes``;
|
||||
each entry is an ``int`` or ``None``. A range requires both fields.
|
||||
sizes:
|
||||
Optional range lengths in bytes, one per URI. Must be positive when
|
||||
``position`` is set.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pa.ExtensionArray
|
||||
external blob values ready to use in Arrow tables or record batches.
|
||||
|
||||
Raises
|
||||
------
|
||||
TypeError
|
||||
If a URI, position, or size has the wrong type.
|
||||
ValueError
|
||||
If lengths differ, only one of ``positions``/``sizes`` is given, a
|
||||
range is incomplete, a size is not positive, or a range is given for
|
||||
a null URI.
|
||||
OverflowError
|
||||
If a position or size does not fit in a uint64.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import pyarrow as pa
|
||||
>>> from lancedb.schema import blob, blob_uri_array
|
||||
>>> schema = pa.schema([blob("video")])
|
||||
>>> videos = blob_uri_array(
|
||||
... ["s3://bucket/a.mp4", "hf://datasets/org/repo@abc/b.mp4"],
|
||||
... positions=[0, 8],
|
||||
... sizes=[4, 4],
|
||||
... )
|
||||
>>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
|
||||
>>> batch.num_rows
|
||||
2
|
||||
"""
|
||||
uri_list = list(uris)
|
||||
if positions is None and sizes is None:
|
||||
ranges = [(None, None)] * len(uri_list)
|
||||
elif positions is None or sizes is None:
|
||||
raise ValueError("positions and sizes must be provided together")
|
||||
else:
|
||||
position_list = list(positions)
|
||||
size_list = list(sizes)
|
||||
if len(position_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"positions must have the same length as uris, got "
|
||||
f"{len(position_list)} and {len(uri_list)}"
|
||||
)
|
||||
if len(size_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"sizes must have the same length as uris, got "
|
||||
f"{len(size_list)} and {len(uri_list)}"
|
||||
)
|
||||
ranges = list(zip(position_list, size_list, strict=True))
|
||||
|
||||
descriptors = []
|
||||
for index, (uri, (position, size)) in enumerate(zip(uri_list, ranges, strict=True)):
|
||||
if uri is None:
|
||||
if position is not None or size is not None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] is None but a position or size was provided"
|
||||
)
|
||||
descriptors.append(None)
|
||||
continue
|
||||
if not isinstance(uri, str):
|
||||
raise TypeError(f"uris[{index}] must be a string, got {type(uri).__name__}")
|
||||
if position is None and size is None:
|
||||
descriptors.append({"uri": uri})
|
||||
continue
|
||||
if position is None or size is None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] must set both position and size or neither"
|
||||
)
|
||||
position = _blob_uint64(position, f"positions[{index}]")
|
||||
size = _blob_uint64(size, f"sizes[{index}]")
|
||||
if size == 0:
|
||||
raise ValueError(f"sizes[{index}] must be positive to read a byte range")
|
||||
descriptors.append({"uri": uri, "position": position, "size": size})
|
||||
|
||||
blob_type = _resolve_blob_type()()
|
||||
storage = pa.array(descriptors, type=blob_type.storage_type)
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType:
|
||||
"""A help function to create a vector type.
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ class EnvVarSecret:
|
||||
|
||||
Pass these in the ``secrets`` sequence of
|
||||
[DBConnection.create_function][lancedb.db.DBConnection.create_function]. The
|
||||
Function's source is unchanged by binding: it reads ``OPENAI_API_KEY`` the
|
||||
Function's source is unchanged by binding: it reads ``MODEL_API_KEY`` the
|
||||
way it always did, and the binding is what puts a value there.
|
||||
|
||||
This is a local value. Constructing it contacts no server, so it always
|
||||
@@ -101,10 +101,10 @@ class EnvVarSecret:
|
||||
--------
|
||||
>>> from lancedb import EnvVarSecret
|
||||
>>> binding = EnvVarSecret(
|
||||
... secret_name="openai-prod", env_variable="OPENAI_API_KEY"
|
||||
... secret_name="model-api-key", env_variable="MODEL_API_KEY"
|
||||
... )
|
||||
>>> binding.secret_name, binding.env_variable
|
||||
('openai-prod', 'OPENAI_API_KEY')
|
||||
('model-api-key', 'MODEL_API_KEY')
|
||||
"""
|
||||
|
||||
__slots__ = ("_secret_name", "_env_variable", "_secret_namespace_path")
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Remote server build information returned as JSON-compatible dictionaries."""
|
||||
|
||||
from typing import Optional, TypedDict
|
||||
|
||||
|
||||
class ServerBuildInfo(TypedDict):
|
||||
"""Immutable identity compiled into a server executable."""
|
||||
|
||||
release: str
|
||||
git_sha: str
|
||||
build_date: Optional[str]
|
||||
|
||||
|
||||
class ServerInfo(TypedDict):
|
||||
"""The responding query node and its configured Function runtime.
|
||||
|
||||
``query_node`` can be ``None`` when the executable has no build metadata.
|
||||
``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling
|
||||
upgrade, separate requests can reach different query-node builds.
|
||||
Configured images do not establish the version of a running job.
|
||||
"""
|
||||
|
||||
query_node: Optional[ServerBuildInfo]
|
||||
lance_version: str
|
||||
lancedb_version: str
|
||||
function_worker_protocol_version: int
|
||||
configured_query_node_image: Optional[str]
|
||||
configured_job_worker_image: Optional[str]
|
||||
configured_sql_job_image: Optional[str]
|
||||
configured_gpu_worker_image: Optional[str]
|
||||
@@ -104,6 +104,15 @@ class AsyncQuery:
|
||||
"""The stable identifier scoped to the connection that submitted it."""
|
||||
return self._inner.id
|
||||
|
||||
@property
|
||||
def job_id(self) -> Optional[str]:
|
||||
"""The durable Job Registry id once the server reports this query as a job.
|
||||
|
||||
A running query reports it after :meth:`describe` observes the latest
|
||||
server status. This is separate from the connection-scoped ``id``.
|
||||
"""
|
||||
return self._inner.job_id
|
||||
|
||||
async def describe(self) -> QueryDescription:
|
||||
"""Get a point-in-time description of the query."""
|
||||
return await self._inner.describe()
|
||||
@@ -118,7 +127,12 @@ class AsyncQuery:
|
||||
return AsyncRecordBatchReader(await self._inner.reader())
|
||||
|
||||
async def cancel(self) -> None:
|
||||
"""Request cancellation of the query."""
|
||||
"""Request cancellation of this query's Flight execution.
|
||||
|
||||
A durable server-side job may reject this operation because its Flight
|
||||
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
|
||||
with ``job_id`` to cancel that job.
|
||||
"""
|
||||
await self._inner.cancel()
|
||||
|
||||
|
||||
@@ -133,6 +147,15 @@ class Query:
|
||||
"""The stable identifier scoped to the connection that submitted it."""
|
||||
return self._inner.id
|
||||
|
||||
@property
|
||||
def job_id(self) -> Optional[str]:
|
||||
"""The durable Job Registry id once the server reports this query as a job.
|
||||
|
||||
A running query reports it after :meth:`describe` observes the latest
|
||||
server status. This is separate from the connection-scoped ``id``.
|
||||
"""
|
||||
return self._inner.job_id
|
||||
|
||||
def describe(self) -> QueryDescription:
|
||||
"""Get a point-in-time description of the query."""
|
||||
return LOOP.run(self._inner.describe())
|
||||
@@ -159,7 +182,12 @@ class Query:
|
||||
return pa.RecordBatchReader.from_batches(reader.schema, batches())
|
||||
|
||||
def cancel(self) -> None:
|
||||
"""Request cancellation of the query."""
|
||||
"""Request cancellation of this query's Flight execution.
|
||||
|
||||
A durable server-side job may reject this operation because its Flight
|
||||
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
|
||||
with ``job_id`` to cancel that job.
|
||||
"""
|
||||
LOOP.run(self._inner.cancel())
|
||||
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ class StorageIntegrationInfo:
|
||||
azure_client_secret_secret: Optional[SecretReference] = None
|
||||
gcp_credentials_json_secret: Optional[SecretReference] = None
|
||||
huggingface_token_secret: Optional[SecretReference] = None
|
||||
azure_storage_account_access_key_secret: Optional[SecretReference] = None
|
||||
|
||||
def __post_init__(self):
|
||||
for field in (
|
||||
@@ -58,6 +59,7 @@ class StorageIntegrationInfo:
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
"azure_storage_account_access_key_secret",
|
||||
"gcp_credentials_json_secret",
|
||||
"huggingface_token_secret",
|
||||
):
|
||||
|
||||
+1010
-126
File diff suppressed because it is too large
Load Diff
+2453
-159
File diff suppressed because it is too large
Load Diff
@@ -52,6 +52,7 @@ IndexType = Literal[
|
||||
"BITMAP",
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
"RTREE",
|
||||
"IVF_RQ",
|
||||
]
|
||||
|
||||
|
||||
+332
-32
@@ -8,9 +8,11 @@ import importlib
|
||||
import math
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import warnings
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from functools import singledispatch
|
||||
from typing import Tuple, Union, Optional, Any, List
|
||||
from urllib.parse import urlparse
|
||||
@@ -328,7 +330,7 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]:
|
||||
|
||||
|
||||
def infer_vector_column_name(
|
||||
schema: pa.Schema,
|
||||
schema: Optional[pa.Schema],
|
||||
query_type: str,
|
||||
query: Optional[Any], # inferred later in query builder
|
||||
vector_column_name: Optional[str],
|
||||
@@ -348,6 +350,8 @@ def infer_vector_column_name(
|
||||
# nothing to infer.
|
||||
return None
|
||||
|
||||
if schema is None:
|
||||
raise ValueError("schema is required to infer a vector column")
|
||||
vector_column_name = inf_vector_column_query(schema, dim=_query_vector_dim(query))
|
||||
|
||||
if vector_column_name is None:
|
||||
@@ -382,7 +386,8 @@ def _(value: bytes):
|
||||
|
||||
@value_to_sql.register(int)
|
||||
def _(value: int):
|
||||
return str(value)
|
||||
# int() first: str() of an int-valued Enum member is its name, e.g. "P.HIGH".
|
||||
return str(int(value))
|
||||
|
||||
|
||||
@value_to_sql.register(float)
|
||||
@@ -394,7 +399,7 @@ def _(value: float):
|
||||
return (
|
||||
"CAST('Infinity' AS DOUBLE)" if value > 0 else "CAST('-Infinity' AS DOUBLE)"
|
||||
)
|
||||
return str(value)
|
||||
return str(float(value))
|
||||
|
||||
|
||||
@value_to_sql.register(Decimal)
|
||||
@@ -415,6 +420,12 @@ def _(value: type(None)):
|
||||
return "NULL"
|
||||
|
||||
|
||||
@value_to_sql.register(Enum)
|
||||
def _(value: Enum):
|
||||
# Write the member's value, as model_to_dict does for a LanceModel field.
|
||||
return value_to_sql(value.value)
|
||||
|
||||
|
||||
@value_to_sql.register(datetime)
|
||||
def _(value: datetime):
|
||||
return f"'{value.isoformat()}'"
|
||||
@@ -601,15 +612,253 @@ def tbl_to_tensor(tbl: pa.Table):
|
||||
return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)])
|
||||
|
||||
|
||||
_BFLOAT16_EXTENSION_NAME = "lance.bfloat16"
|
||||
_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name"
|
||||
|
||||
|
||||
def _field_metadata_value(field: pa.Field, key: str):
|
||||
metadata = field.metadata or {}
|
||||
value = metadata.get(key.encode()) or metadata.get(key)
|
||||
if isinstance(value, bytes):
|
||||
return value.decode()
|
||||
return value
|
||||
|
||||
|
||||
def _field_extension_name(field: pa.Field) -> Optional[str]:
|
||||
extension_name = _field_metadata_value(field, _ARROW_EXTENSION_NAME_KEY)
|
||||
if extension_name is not None:
|
||||
return extension_name
|
||||
if isinstance(field.type, pa.ExtensionType):
|
||||
return field.type.extension_name
|
||||
return None
|
||||
|
||||
|
||||
def _field_storage_type(field: pa.Field) -> pa.DataType:
|
||||
if isinstance(field.type, pa.ExtensionType):
|
||||
return field.type.storage_type
|
||||
return field.type
|
||||
|
||||
|
||||
def _is_bfloat16_field(field: pa.Field) -> bool:
|
||||
if _field_extension_name(field) != _BFLOAT16_EXTENSION_NAME:
|
||||
return False
|
||||
storage_type = _field_storage_type(field)
|
||||
return pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
|
||||
|
||||
|
||||
def _check_torch_nulls(array: pa.Array, column_name: str) -> None:
|
||||
if array.null_count:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` to a torch tensor because it "
|
||||
f"contains {array.null_count} null value(s). Drop or fill nulls before "
|
||||
"using a torch format."
|
||||
)
|
||||
|
||||
|
||||
def _bfloat16_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
storage = array.storage if isinstance(array.type, pa.ExtensionType) else array
|
||||
storage_type = storage.type
|
||||
if not (
|
||||
pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
|
||||
):
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` is marked as {_BFLOAT16_EXTENSION_NAME!r} but "
|
||||
f"has storage type {storage_type}. The lance.bfloat16 extension requires "
|
||||
"fixed_size_binary[2] storage."
|
||||
)
|
||||
_check_torch_nulls(storage, column_name)
|
||||
if len(storage) == 0:
|
||||
return torch.empty((0,), dtype=torch.bfloat16)
|
||||
|
||||
buffer = storage.buffers()[1]
|
||||
if buffer is None:
|
||||
return torch.empty((0,), dtype=torch.bfloat16)
|
||||
offset = storage.offset * 2
|
||||
byte_length = len(storage) * 2
|
||||
if buffer.size < offset + byte_length:
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` has a truncated bfloat16 value buffer."
|
||||
)
|
||||
|
||||
# Arrow stores bfloat16 as two little-endian bytes. Copy only on big-endian
|
||||
# hosts before viewing the same bits as torch.bfloat16.
|
||||
values = np.frombuffer(
|
||||
buffer, dtype=np.dtype("<u2"), count=len(storage), offset=offset
|
||||
)
|
||||
if sys.byteorder != "little":
|
||||
values = values.astype(np.uint16)
|
||||
# Older torch releases cannot create a tensor from np.uint16, so view the
|
||||
# same bits as signed 16-bit values before interpreting them as bfloat16.
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message="The given NumPy array is not writable",
|
||||
category=UserWarning,
|
||||
)
|
||||
return torch.from_numpy(values.view(np.int16)).view(torch.bfloat16)
|
||||
|
||||
|
||||
def _leaf_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
if _is_bfloat16_field(field):
|
||||
return _bfloat16_to_tensor(array, torch, column_name)
|
||||
|
||||
data_type = array.type
|
||||
if isinstance(data_type, pa.ExtensionType):
|
||||
raise ValueError(
|
||||
f"Unsupported PyTorch column type {data_type} for column "
|
||||
f"`{column_name}`. Supported extension types are "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r} and arrow.fixed_shape_tensor."
|
||||
)
|
||||
if (
|
||||
pa.types.is_boolean(data_type)
|
||||
or pa.types.is_integer(data_type)
|
||||
or pa.types.is_floating(data_type)
|
||||
):
|
||||
# Arrow packs booleans as bits while torch uses one byte per value, so
|
||||
# boolean columns always need a copy. Other numeric columns share the
|
||||
# Arrow buffer.
|
||||
zero_copy_only = not pa.types.is_boolean(data_type)
|
||||
try:
|
||||
numpy_values = array.to_numpy(zero_copy_only=zero_copy_only)
|
||||
except pa.ArrowInvalid as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` of type {data_type} to a "
|
||||
f"torch tensor without copying: {err}"
|
||||
) from err
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message="The given NumPy array is not writable",
|
||||
category=UserWarning,
|
||||
)
|
||||
return torch.from_numpy(numpy_values)
|
||||
except (TypeError, RuntimeError) as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` of type {data_type} to a "
|
||||
f"torch tensor: {err}"
|
||||
) from err
|
||||
if pa.types.is_fixed_size_binary(data_type) and data_type.byte_width == 2:
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` has type fixed_size_binary[2] but is not "
|
||||
f"marked with {_ARROW_EXTENSION_NAME_KEY!r} = "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r}. An unmarked binary column is not "
|
||||
"treated as bfloat16."
|
||||
)
|
||||
raise ValueError(
|
||||
f"Unsupported PyTorch column type {data_type} for column `{column_name}`. "
|
||||
"Supported leaf types are boolean, integer, floating point, and "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r} fixed_size_binary[2] values."
|
||||
)
|
||||
|
||||
|
||||
def _fixed_size_list_to_tensor(array: pa.FixedSizeListArray, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
width = array.type.list_size
|
||||
values = array.values.slice(array.offset * width, len(array) * width)
|
||||
child_tensor = _arrow_column_to_tensor(
|
||||
values, array.type.value_field, torch, column_name
|
||||
)
|
||||
return child_tensor.reshape((len(array), width, *child_tensor.shape[1:]))
|
||||
|
||||
|
||||
def _fixed_shape_tensor_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
tensor_type = array.type
|
||||
storage = array.storage
|
||||
physical_shape = list(tensor_type.shape)
|
||||
permutation = list(getattr(tensor_type, "permutation", None) or [])
|
||||
storage_tensor = _arrow_column_to_tensor(
|
||||
storage, storage.type.value_field, torch, column_name
|
||||
)
|
||||
tensor = storage_tensor.reshape((len(array), *physical_shape))
|
||||
if permutation:
|
||||
# Arrow's ``shape`` is the physical row-major shape, and
|
||||
# ``permutation`` maps a logical axis to its physical axis. Transposing
|
||||
# by it restores the logical shape as a view.
|
||||
tensor = tensor.permute([0] + [axis + 1 for axis in permutation])
|
||||
return tensor
|
||||
|
||||
|
||||
def _arrow_column_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
|
||||
if isinstance(array.type, pa.FixedShapeTensorType):
|
||||
return _fixed_shape_tensor_to_tensor(array, torch, column_name)
|
||||
if pa.types.is_fixed_size_list(array.type):
|
||||
return _fixed_size_list_to_tensor(array, torch, column_name)
|
||||
return _leaf_to_tensor(array, field, torch, column_name).reshape((len(array),))
|
||||
|
||||
|
||||
def _is_nullable_numeric_scalar(array: pa.Array) -> bool:
|
||||
data_type = array.type
|
||||
if isinstance(data_type, pa.ExtensionType) or array.null_count == 0:
|
||||
return False
|
||||
return pa.types.is_integer(data_type) or pa.types.is_floating(data_type)
|
||||
|
||||
|
||||
def _nullable_numeric_scalar_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
try:
|
||||
numpy_values = array.to_numpy(zero_copy_only=False)
|
||||
except pa.ArrowInvalid as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert nullable column `{column_name}` of type {array.type} "
|
||||
f"to a torch tensor: {err}"
|
||||
) from err
|
||||
try:
|
||||
return torch.from_numpy(numpy_values)
|
||||
except (TypeError, RuntimeError) as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert nullable column `{column_name}` of type {array.type} "
|
||||
f"to a torch tensor: {err}"
|
||||
) from err
|
||||
|
||||
|
||||
def _batch_column_tensors(batch: pa.RecordBatch, allow_scalar_nulls: bool = False):
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
columns = []
|
||||
for field, column in zip(batch.schema, batch.columns):
|
||||
if allow_scalar_nulls and _is_nullable_numeric_scalar(column):
|
||||
tensor = _nullable_numeric_scalar_to_tensor(column, torch, field.name)
|
||||
else:
|
||||
tensor = _arrow_column_to_tensor(column, field, torch, field.name)
|
||||
columns.append((field.name, tensor))
|
||||
return torch, columns
|
||||
|
||||
|
||||
def _uniform_column_tensors(
|
||||
batch: pa.RecordBatch, format_name: str, allow_scalar_nulls: bool = False
|
||||
):
|
||||
torch, columns = _batch_column_tensors(batch, allow_scalar_nulls=allow_scalar_nulls)
|
||||
if len(columns) <= 1:
|
||||
return torch, columns
|
||||
|
||||
first_name, first = columns[0]
|
||||
first_shape = tuple(first.shape[1:])
|
||||
for name, tensor in columns[1:]:
|
||||
shape = tuple(tensor.shape[1:])
|
||||
if shape != first_shape:
|
||||
raise ValueError(
|
||||
f"Cannot use the {format_name!r} format because column `{name}` "
|
||||
f"has sample shape {shape} while column `{first_name}` has sample "
|
||||
f'shape {first_shape}. Use with_format("torch_dict") for columns '
|
||||
'with different shapes, or with_format("torch") for a list of '
|
||||
"per-row dicts."
|
||||
)
|
||||
return torch, columns
|
||||
|
||||
|
||||
def batch_to_tensor(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a PyTorch Tensor.
|
||||
|
||||
Each column is converted to a tensor (using zero-copy via DLPack)
|
||||
and the columns are then stacked into a single tensor.
|
||||
Each column is converted to a tensor with shape ``(rows, *sample_shape)``
|
||||
and the columns are stacked along a new leading dimension. Scalar columns
|
||||
have sample shape ``()`` and fixed-size-list columns contribute each list
|
||||
dimension. All columns must have the same sample shape.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -618,43 +867,99 @@ def batch_to_tensor(batch: pa.RecordBatch):
|
||||
|
||||
Returns
|
||||
-------
|
||||
torch.Tensor: The tensor containing the columns of the record batch.
|
||||
torch.Tensor: A tensor with shape ``(columns, rows, *sample_shape)``. A
|
||||
one-column batch returns an ``unsqueeze(0)`` view of that column.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
return torch.stack([torch.from_dlpack(col) for col in batch.columns])
|
||||
torch, columns = _uniform_column_tensors(batch, "torch_col")
|
||||
if not columns:
|
||||
return torch.empty((0, batch.num_rows))
|
||||
if len(columns) == 1:
|
||||
return columns[0][1].unsqueeze(0)
|
||||
return torch.stack([tensor for _, tensor in columns], dim=0)
|
||||
|
||||
|
||||
def batch_to_tensor_rows(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a list of PyTorch Tensor, one per row
|
||||
Convert a PyArrow RecordBatch to a list of PyTorch Tensors, one per row.
|
||||
|
||||
Each column is converted to a tensor (using zero-copy via DLPack)
|
||||
and the columns are then stacked into a single tensor. The 2D tensor
|
||||
is then converted to a list of tensors, one per row
|
||||
Each row tensor has shape ``(columns, *sample_shape)``. All columns must
|
||||
have the same sample shape, so a table mixing scalar and vector columns
|
||||
should use ``torch_dict`` or ``torch`` instead. Dtypes are combined with
|
||||
``torch.promote_types``, matching PyTorch's numeric promotion rules.
|
||||
|
||||
Fails if torch or numpy is not installed.
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Nulls in ordinary integer or floating scalar columns become ``NaN``.
|
||||
Nulls in nested fixed-size-list or tensor columns are rejected.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch : pa.RecordBatch
|
||||
The record batch to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[torch.Tensor]
|
||||
One tensor per row, each with shape ``(columns, *sample_shape)``. A
|
||||
one-column scalar batch produces ``(1,)`` tensors.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
numpy = attempt_import_or_raise("numpy", "numpy")
|
||||
columns = [col.to_numpy(zero_copy_only=False) for col in batch.columns]
|
||||
stacked = torch.tensor(numpy.column_stack(columns))
|
||||
rows = list(stacked.unbind(dim=0))
|
||||
return rows
|
||||
torch, columns = _uniform_column_tensors(
|
||||
batch, "torch_row", allow_scalar_nulls=True
|
||||
)
|
||||
if not columns:
|
||||
return [torch.empty((0,)) for _ in range(batch.num_rows)]
|
||||
|
||||
dtype = columns[0][1].dtype
|
||||
for _, tensor in columns[1:]:
|
||||
dtype = torch.promote_types(dtype, tensor.dtype)
|
||||
tensors = [
|
||||
tensor if tensor.dtype == dtype else tensor.to(dtype) for _, tensor in columns
|
||||
]
|
||||
stacked = torch.stack(tensors, dim=1)
|
||||
return list(stacked.unbind(dim=0))
|
||||
|
||||
|
||||
def batch_to_tensor_columns(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a dict of per-column PyTorch Tensors.
|
||||
|
||||
Each tensor has shape ``(rows, *sample_shape)`` and shares Arrow storage
|
||||
where the layout allows it. Unlike ``torch_col`` and ``torch_row``, columns
|
||||
may have different sample shapes. This is the transform behind
|
||||
``Permutation.with_format("torch_dict")`` and can be consumed directly by
|
||||
a ``DataLoader`` with an identity ``collate_fn``.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch : pa.RecordBatch
|
||||
The record batch to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, torch.Tensor]
|
||||
A tensor per column, each with shape ``(rows, *sample_shape)``.
|
||||
"""
|
||||
_, columns = _batch_column_tensors(batch)
|
||||
return dict(columns)
|
||||
|
||||
|
||||
def batch_to_tensor_dict(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a list of per-row dicts of PyTorch Tensors.
|
||||
|
||||
Each column is first converted to a 1-D tensor (zero-copy via DLPack), then
|
||||
sliced per row. The result is a list whose length is ``batch.num_rows`` and
|
||||
whose items are dicts keyed by column name. This shape composes directly
|
||||
with PyTorch's default ``DataLoader`` collate, which stacks the per-row
|
||||
dicts back into a dict of batched tensors.
|
||||
Each column is converted to a tensor with shape ``(rows, *sample_shape)``,
|
||||
then sliced per row. The result is a list whose length is
|
||||
``batch.num_rows`` and whose items are dicts keyed by column name. This
|
||||
shape composes directly with PyTorch's default ``DataLoader`` collate,
|
||||
which stacks the per-row dicts back into a dict of batched tensors.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -665,14 +970,9 @@ def batch_to_tensor_dict(batch: pa.RecordBatch):
|
||||
-------
|
||||
list[dict[str, torch.Tensor]]
|
||||
One per-row dict per row in the batch. Each dict maps column name to a
|
||||
0-D tensor view into the column.
|
||||
tensor view into the column.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
tensors = {
|
||||
name: torch.from_dlpack(col)
|
||||
for name, col in zip(batch.schema.names, batch.columns)
|
||||
}
|
||||
_, columns = _batch_column_tensors(batch)
|
||||
return [
|
||||
{name: tensor[i] for name, tensor in tensors.items()}
|
||||
for i in range(batch.num_rows)
|
||||
{name: tensor[i] for name, tensor in columns} for i in range(batch.num_rows)
|
||||
]
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop"
|
||||
|
||||
|
||||
def _run_in_subprocess(code: str, timeout: int = 30) -> subprocess.CompletedProcess:
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
|
||||
return subprocess.run(
|
||||
[sys.executable, "-c", textwrap.dedent(code)],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None:
|
||||
assert result.returncode == 0, result.stderr or result.stdout
|
||||
|
||||
|
||||
def test_import_and_inspection_do_not_start_background_loop():
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import threading
|
||||
|
||||
import lancedb
|
||||
from lancedb.background_loop import BackgroundEventLoop, LOOP
|
||||
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == {BACKGROUND_THREAD_NAME!r}
|
||||
]
|
||||
|
||||
assert LOOP.thread is None
|
||||
assert LOOP.loop is None
|
||||
assert background_threads() == []
|
||||
|
||||
# Inspecting a fresh instance is also side-effect free.
|
||||
loop = BackgroundEventLoop()
|
||||
assert loop.thread is None
|
||||
assert loop.loop is None
|
||||
assert background_threads() == []
|
||||
"""
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
def test_first_sync_call_starts_one_daemon_thread():
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import threading
|
||||
|
||||
import lancedb
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == {BACKGROUND_THREAD_NAME!r}
|
||||
]
|
||||
|
||||
assert LOOP.thread is None
|
||||
assert LOOP.loop is None
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
assert db.table_names() == []
|
||||
|
||||
worker = LOOP.thread
|
||||
assert worker is not None
|
||||
assert worker is background_threads()[0]
|
||||
assert len(background_threads()) == 1
|
||||
assert worker.daemon
|
||||
assert worker.is_alive()
|
||||
assert LOOP.loop is not None
|
||||
"""
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
def test_concurrent_first_use_initializes_one_background_thread():
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
worker_count = 8
|
||||
barrier = threading.Barrier(worker_count)
|
||||
results = []
|
||||
errors = []
|
||||
results_lock = threading.Lock()
|
||||
|
||||
def submit(index):
|
||||
try:
|
||||
barrier.wait(timeout=10)
|
||||
value = LOOP.run(asyncio.sleep(0.05, result=index))
|
||||
with results_lock:
|
||||
results.append(value)
|
||||
except BaseException as exc:
|
||||
with results_lock:
|
||||
errors.append(repr(exc))
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=submit, args=(index,))
|
||||
for index in range(worker_count)
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=20)
|
||||
|
||||
assert all(not thread.is_alive() for thread in threads)
|
||||
assert errors == []
|
||||
assert sorted(results) == list(range(worker_count))
|
||||
|
||||
background_threads = [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == {BACKGROUND_THREAD_NAME!r}
|
||||
]
|
||||
assert len(background_threads) == 1
|
||||
assert background_threads[0].daemon
|
||||
"""
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
sys.platform != "linux",
|
||||
reason=(
|
||||
"fork() is unavailable on Windows and unsafe on macOS "
|
||||
"(Apple frameworks/TLS are not fork-safe)"
|
||||
),
|
||||
)
|
||||
def test_forked_child_starts_background_loop_lazily():
|
||||
# Fork from a fresh interpreter: earlier tests in a shared pytest process
|
||||
# may have left native runtime state that is not part of this scenario.
|
||||
result = _run_in_subprocess(
|
||||
f"""
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
BACKGROUND_THREAD_NAME = {BACKGROUND_THREAD_NAME!r}
|
||||
|
||||
def background_threads():
|
||||
return [
|
||||
thread
|
||||
for thread in threading.enumerate()
|
||||
if thread.name == BACKGROUND_THREAD_NAME
|
||||
]
|
||||
|
||||
def fork_child(queue):
|
||||
try:
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
inherited_thread_is_none = LOOP.thread is None
|
||||
inherited_loop_is_none = LOOP.loop is None
|
||||
background_threads_before = [
|
||||
thread.name for thread in background_threads()
|
||||
]
|
||||
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
tables = db.table_names()
|
||||
|
||||
worker = LOOP.thread
|
||||
queue.put(
|
||||
dict(
|
||||
error=None,
|
||||
inherited_thread_is_none=inherited_thread_is_none,
|
||||
inherited_loop_is_none=inherited_loop_is_none,
|
||||
background_threads_before=background_threads_before,
|
||||
tables=tables,
|
||||
thread_alive=False if worker is None else worker.is_alive(),
|
||||
thread_daemon=False if worker is None else worker.daemon,
|
||||
background_thread_count=len(background_threads()),
|
||||
)
|
||||
)
|
||||
except BaseException:
|
||||
queue.put(dict(error=traceback.format_exc()))
|
||||
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
|
||||
parent_thread = LOOP.thread
|
||||
assert parent_thread is not None
|
||||
|
||||
ctx = mp.get_context("fork")
|
||||
queue = ctx.Queue()
|
||||
|
||||
# Simulate forking while another thread held the initialization lock. The
|
||||
# child must replace the inherited lock instead of trying to acquire it.
|
||||
LOOP._start_lock.acquire()
|
||||
try:
|
||||
proc = ctx.Process(target=fork_child, args=(queue,))
|
||||
proc.start()
|
||||
finally:
|
||||
LOOP._start_lock.release()
|
||||
|
||||
proc.join(timeout=20)
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
proc.join(timeout=5)
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
proc.join()
|
||||
raise AssertionError("Forked child hung starting the background loop")
|
||||
|
||||
assert proc.exitcode == 0, "child exited with code %s" % proc.exitcode
|
||||
payload = queue.get(timeout=5)
|
||||
queue.close()
|
||||
assert payload["error"] is None, payload["error"]
|
||||
assert payload["inherited_thread_is_none"] is True
|
||||
assert payload["inherited_loop_is_none"] is True
|
||||
assert payload["background_threads_before"] == []
|
||||
assert payload["tables"] == []
|
||||
assert payload["thread_alive"] is True
|
||||
assert payload["thread_daemon"] is True
|
||||
assert payload["background_thread_count"] == 1
|
||||
|
||||
# The child's reset must not disturb the parent's loop.
|
||||
assert LOOP.thread is parent_thread
|
||||
assert parent_thread.is_alive()
|
||||
assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
|
||||
""",
|
||||
# join(20) + terminate join(5) + queue get(5), plus startup and traceback.
|
||||
timeout=40,
|
||||
)
|
||||
_assert_subprocess_ok(result)
|
||||
@@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode():
|
||||
1: b"one",
|
||||
2: b"two",
|
||||
}
|
||||
ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["id"].to_pylist() == [2, 1]
|
||||
assert ordered["image"].to_pylist() == [b"two", b"one"]
|
||||
assert [
|
||||
row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes")
|
||||
] == [b"one"]
|
||||
@@ -1070,8 +1075,10 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path):
|
||||
)
|
||||
table.add([{"id": 1, "image": b"one"}])
|
||||
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot") as exc:
|
||||
table.to_arrow(blob_mode="bytes")
|
||||
assert "fetch_blobs(column, row_ids)" in str(exc.value)
|
||||
assert "with_row_id(True)" in str(exc.value)
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
table.search().to_list(blob_mode="bytes")
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
@@ -1103,6 +1110,54 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path)
|
||||
await table.query().to_batches(blob_mode="bytes")
|
||||
|
||||
|
||||
def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
rows = [
|
||||
{"id": 1, "image": b"one"},
|
||||
{"id": 2, "image": b""},
|
||||
{"id": 3, "image": None},
|
||||
{"id": 4, "image": b"excluded"},
|
||||
]
|
||||
source = db.create_table("source", data=rows, schema=schema)
|
||||
hits = (
|
||||
source.search()
|
||||
.where("id < 4")
|
||||
.select(["id"])
|
||||
.with_row_id(True)
|
||||
.limit(100)
|
||||
.to_arrow()
|
||||
)
|
||||
payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist()
|
||||
subset = db.create_table("subset", schema=schema)
|
||||
subset.add(
|
||||
[
|
||||
{"id": image_id, "image": payload}
|
||||
for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True)
|
||||
]
|
||||
)
|
||||
copied = subset.search().to_list(blob_mode="bytes")
|
||||
assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
|
||||
|
||||
|
||||
def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema)
|
||||
hits = source.search().where("id = 1").to_arrow()
|
||||
|
||||
with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc:
|
||||
db.create_table("copy", data=hits, schema=schema)
|
||||
|
||||
message = str(exc.value)
|
||||
assert "blob_mode='bytes'" in message
|
||||
assert "blob_mode='descriptions'" in message
|
||||
assert "with_row_id(True)" in message
|
||||
assert "fetch_blobs(column, row_ids)" in message
|
||||
assert "fetch_blob_files(column, row_ids)" in message
|
||||
assert not db.table_exists(["copy"])
|
||||
|
||||
|
||||
def test_fetch_blobs_round_trip():
|
||||
table = _blob_table(
|
||||
"round_trip",
|
||||
@@ -1619,16 +1674,41 @@ def test_bytes_mode_rejects_blobs_inside_lists():
|
||||
|
||||
|
||||
def test_row_addressable_paths_exclude_list_children():
|
||||
from lancedb.schema import row_addressable_blob_v2_paths
|
||||
from lancedb.schema import (
|
||||
row_addressable_blob_paths,
|
||||
row_addressable_blob_v2_paths,
|
||||
)
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("info", pa.struct([lancedb.blob("blob")])),
|
||||
pa.field(
|
||||
"info",
|
||||
pa.struct(
|
||||
[
|
||||
lancedb.blob("blob"),
|
||||
pa.field(
|
||||
"legacy",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
]
|
||||
),
|
||||
),
|
||||
pa.field(
|
||||
"legacy",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
pa.field("images", pa.list_(lancedb.blob("image"))),
|
||||
]
|
||||
)
|
||||
assert blob_v2_column_paths(schema) == ["info.blob", "images.image"]
|
||||
assert row_addressable_blob_paths(schema) == [
|
||||
"info.blob",
|
||||
"info.legacy",
|
||||
"legacy",
|
||||
]
|
||||
assert row_addressable_blob_v2_paths(schema) == ["info.blob"]
|
||||
|
||||
|
||||
@@ -1883,6 +1963,18 @@ def test_fetch_blob_apis_reject_missing_fragment_row_addr():
|
||||
_assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live])
|
||||
|
||||
|
||||
def test_fetch_blobs_missing_row_ids_suggest_take_offsets():
|
||||
table = _blob_table(
|
||||
"position_hint",
|
||||
[{"id": i, "image": b"x"} for i in range(3)],
|
||||
)
|
||||
with pytest.raises(ValueError, match="take_offsets") as exc:
|
||||
table.fetch_blobs("image", [10])
|
||||
message = str(exc.value)
|
||||
assert "first missing row ids: [10]" in message
|
||||
assert "with_row_id=True" in message
|
||||
|
||||
|
||||
def test_fetch_blob_apis_reject_deleted_row_ids():
|
||||
table = _blob_table(
|
||||
"deleted_rows",
|
||||
@@ -2141,8 +2233,11 @@ def test_fetch_blobs_from_query_result_without_row_id_raises():
|
||||
table = _blob_table("no_rowid", [{"id": 1, "image": b"x"}])
|
||||
hits = table.search().select(["id"]).to_arrow()
|
||||
assert "_rowid" not in hits.column_names
|
||||
with pytest.raises(ValueError, match="_rowid"):
|
||||
with pytest.raises(ValueError, match="take_offsets") as exc:
|
||||
table.fetch_blobs("image", hits)
|
||||
message = str(exc.value)
|
||||
assert "with_row_id=True" in message
|
||||
assert "list of row ids" in message
|
||||
|
||||
|
||||
_HYBRID_BLOB_SCHEMA = pa.schema(
|
||||
@@ -2293,6 +2388,8 @@ async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch):
|
||||
if blob_mode != "lazy":
|
||||
assert "_rowid" not in reader.schema.names
|
||||
assert "_lance_row_id" not in str(reader.schema)
|
||||
else:
|
||||
assert "_rowid" in reader.schema.names
|
||||
|
||||
|
||||
class _KeepAllScoresReranker(Reranker):
|
||||
@@ -2307,6 +2404,77 @@ class _KeepAllScoresReranker(Reranker):
|
||||
return combined.append_column("_relevance_score", scores)
|
||||
|
||||
|
||||
class _RecordingVectorReranker(Reranker):
|
||||
def __init__(self):
|
||||
super().__init__(return_score="all")
|
||||
self.calls = []
|
||||
|
||||
def rerank_hybrid(self, query, vector_results, fts_results):
|
||||
raise AssertionError("vector queries must not call rerank_hybrid")
|
||||
|
||||
def rerank_vector(self, query, vector_results):
|
||||
self.calls.append((query, vector_results))
|
||||
return vector_results.append_column(
|
||||
"_relevance_score",
|
||||
pa.array([1.0] * len(vector_results), type=pa.float32()),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
|
||||
def test_vector_to_arrow_reranks_before_blob_conversion(blob_mode, monkeypatch):
|
||||
db = lancedb.connect("memory:///")
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
||||
lancedb.blob("image"),
|
||||
]
|
||||
)
|
||||
table = db.create_table(f"vector_rerank_{blob_mode}", schema=schema)
|
||||
rows = 1100
|
||||
table.add(
|
||||
[
|
||||
{
|
||||
"id": row_id,
|
||||
"vector": [1.0, float(row_id % 2)],
|
||||
"image": f"image-{row_id}".encode(),
|
||||
}
|
||||
for row_id in range(rows)
|
||||
]
|
||||
)
|
||||
fetched = []
|
||||
fetch_blobs = table.fetch_blobs
|
||||
|
||||
def fetch(column, row_ids):
|
||||
fetched.append((column, len(row_ids)))
|
||||
return fetch_blobs(column, row_ids)
|
||||
|
||||
monkeypatch.setattr(table, "fetch_blobs", fetch)
|
||||
reranker = _RecordingVectorReranker()
|
||||
hits = (
|
||||
table.search([1.0, 0.0])
|
||||
.limit(rows)
|
||||
.select(["id", "image"])
|
||||
.rerank(reranker, "hello")
|
||||
.to_arrow(blob_mode=blob_mode)
|
||||
)
|
||||
|
||||
assert len(reranker.calls) == 1
|
||||
query, source = reranker.calls[0]
|
||||
assert query == "hello"
|
||||
# The reranker sees descriptors, not already-converted payload bytes.
|
||||
assert not pa.types.is_large_binary(source.schema.field("image").type)
|
||||
assert "_relevance_score" in hits.column_names
|
||||
assert len(hits) == rows
|
||||
if blob_mode == "bytes":
|
||||
# The whole lazy result is materialized before one aggregate conversion.
|
||||
assert fetched == [("image", rows)]
|
||||
assert pa.types.is_large_binary(hits.schema.field("image").type)
|
||||
else:
|
||||
assert fetched == []
|
||||
assert not pa.types.is_large_binary(hits.schema.field("image").type)
|
||||
|
||||
|
||||
def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
@@ -2336,7 +2504,7 @@ def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
|
||||
.rerank(_KeepAllScoresReranker())
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*legacy blob columns"):
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
||||
query.to_arrow(blob_mode="bytes")
|
||||
|
||||
|
||||
@@ -3099,3 +3267,393 @@ async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
|
||||
with file:
|
||||
actual.append(await file.aread())
|
||||
assert actual == [None, b"alpha", b"alpha"]
|
||||
|
||||
|
||||
def _initial_base_payloads(tmp_path):
|
||||
base_dir = tmp_path / "videos"
|
||||
base_dir.mkdir(exist_ok=True)
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
return base_dir, clip, payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_spec", ["lightweight", "dict", "dataset_base_path"])
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_store_relative_blob_ranges(
|
||||
tmp_path, base_spec, use_async
|
||||
):
|
||||
lance = None
|
||||
if base_spec == "dataset_base_path":
|
||||
lance = pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
field = lancedb.blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
base_kwargs = {"path": base_dir.as_uri(), "name": "source", "id": 1}
|
||||
if base_spec == "lightweight":
|
||||
bases = [lancedb.BasePath(**base_kwargs)]
|
||||
elif base_spec == "dict":
|
||||
bases = [base_kwargs]
|
||||
else:
|
||||
bases = [lance.DatasetBasePath(**base_kwargs)]
|
||||
|
||||
if use_async:
|
||||
db = await lancedb.connect_async(tmp_path / "db")
|
||||
table = await db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert await table.version() == 1
|
||||
created_schema = await table.schema()
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload[:6]]
|
||||
assert (
|
||||
await reopened.fetch_blob_ranges("video", [(row_id, 1, 3)])
|
||||
).to_pylist() == [payload[1:4]]
|
||||
else:
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
created_schema = table.schema
|
||||
# Manifest introspection needs pylance; the lightweight and dict
|
||||
# variants must still prove registration through the reopen and bytes.
|
||||
if lance is not None:
|
||||
registered = table.to_lance().base_paths()[1]
|
||||
assert registered.path == base_dir.as_uri()
|
||||
assert registered.is_dataset_root is False
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
assert created_schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
|
||||
|
||||
def test_create_table_initial_bases_bootstrap_empty_table_with_auto_id(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source")],
|
||||
)
|
||||
assert table.version == 1
|
||||
registered = list(table.to_lance().base_paths().values())
|
||||
assert len(registered) == 1
|
||||
assert registered[0].id > 0
|
||||
assert registered[0].path == base_dir.as_uri()
|
||||
assert registered[0].is_dataset_root is False
|
||||
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
table.add(rows)
|
||||
reopened = db.open_table("videos")
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1]]).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_reject_bad_input(tmp_path):
|
||||
base_dir, _, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect("memory:///")
|
||||
path = base_dir.as_uri()
|
||||
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
lancedb.BasePath(path=path, id=0)
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
db.create_table("zero", schema=schema, initial_bases=[{"path": path, "id": 0}])
|
||||
with pytest.raises(ValueError, match="unique"):
|
||||
db.create_table(
|
||||
"duplicates",
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=path, id=1),
|
||||
lancedb.BasePath(path=f"{path}/other", id=1),
|
||||
],
|
||||
)
|
||||
with pytest.raises(ValueError, match="missing 'path'"):
|
||||
db.create_table("missing_path", schema=schema, initial_bases=[{"id": 1}])
|
||||
with pytest.raises(TypeError, match="must be a BasePath, dict, or DatasetBasePath"):
|
||||
db.create_table("not_a_base", schema=schema, initial_bases=[object()])
|
||||
|
||||
|
||||
def test_create_table_allow_external_blob_outside_bases_is_atomic(tmp_path):
|
||||
payload = b"0123456789abcdef"
|
||||
clip = tmp_path / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
with pytest.raises(ValueError, match="allow_external_blob_outside_bases"):
|
||||
db.create_table("rejected", data=rows, schema=schema)
|
||||
with pytest.raises(ValueError, match="requires initial data"):
|
||||
db.create_table(
|
||||
"empty_opt_in", schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos", data=rows, schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 0, 6)]).to_pylist() == [
|
||||
payload[:6]
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_keep_scoped_options_on_reopen(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload = b"scoped-payload"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload)
|
||||
clip_b.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
storage_options = {
|
||||
"timeout": "7s",
|
||||
"base_1.region": "base-one",
|
||||
"base_2.region": "base-two",
|
||||
}
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
storage_options=storage_options,
|
||||
)
|
||||
assert table.version == 1
|
||||
assert {base.id for base in table.to_lance().base_paths().values()} == {1, 2}
|
||||
|
||||
reopened = db.open_table("videos", storage_options=storage_options)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1], by_id[2]]).to_pylist() == [
|
||||
payload,
|
||||
payload,
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_through_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
|
||||
|
||||
def test_namespace_create_keeps_scoped_options_over_connection_defaults(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
# The invalid scoped option belongs to base 1. It must survive the merge
|
||||
# with connection defaults instead of being replaced by them.
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)
|
||||
],
|
||||
storage_options={"base_1.scheduler_error_mode": "invalid"},
|
||||
)
|
||||
|
||||
|
||||
def test_namespace_reopen_applies_scoped_options_per_base(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload_a = b"namespace-base-a"
|
||||
payload_b = b"namespace-base-b"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload_a)
|
||||
clip_b.write_bytes(payload_b)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
)
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.scheduler_error_mode": "invalid"}
|
||||
)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
reopened.fetch_blobs("video", [by_id[1]])
|
||||
assert reopened.fetch_blobs("video", [by_id[2]]).to_pylist() == [payload_b]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_through_async_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = await db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert await table.version() == 1
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_namespace_refresh_layers_caller_scoped_options(tmp_path):
|
||||
from lance_namespace import (
|
||||
DeclareTableResponse,
|
||||
DescribeTableResponse,
|
||||
LanceNamespace,
|
||||
)
|
||||
from lancedb.namespace import LanceNamespaceDBConnection
|
||||
|
||||
class RefreshingNamespace(LanceNamespace):
|
||||
def __init__(self, location):
|
||||
self.location = location
|
||||
self.refreshes = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return self.location
|
||||
|
||||
def declare_table(self, request):
|
||||
return DeclareTableResponse(
|
||||
location=self.location,
|
||||
storage_options={
|
||||
"timeout": "7s",
|
||||
# Expired immediately so the next read must refresh.
|
||||
"expires_at_millis": "1",
|
||||
},
|
||||
)
|
||||
|
||||
def describe_table(self, request):
|
||||
self.refreshes += 1
|
||||
return DescribeTableResponse(
|
||||
location=self.location,
|
||||
storage_options={"timeout": "8s", "namespace_vended": "fresh"},
|
||||
)
|
||||
|
||||
payload = b"0123456789abcdef"
|
||||
base_dir = tmp_path / "base"
|
||||
base_dir.mkdir()
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
namespace = RefreshingNamespace((tmp_path / "table.lance").as_uri())
|
||||
db = LanceNamespaceDBConnection(namespace)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(base_dir.as_uri(), name="base", id=1)],
|
||||
storage_options={"base_1.caller_scoped": "keep-me"},
|
||||
)
|
||||
initial = table.initial_storage_options()
|
||||
assert initial["base_1.caller_scoped"] == "keep-me"
|
||||
assert initial["timeout"] == "7s"
|
||||
|
||||
latest = table.latest_storage_options()
|
||||
assert namespace.refreshes > 0, "expired seed did not trigger a refresh"
|
||||
assert latest["base_1.caller_scoped"] == "keep-me"
|
||||
assert latest["timeout"] == "8s"
|
||||
assert latest["namespace_vended"] == "fresh"
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.caller_scoped": "keep-me"}
|
||||
)
|
||||
assert reopened.latest_storage_options()["base_1.caller_scoped"] == "keep-me"
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", [row_id]).to_pylist() == [payload]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 4, 6)]).to_pylist() == [
|
||||
payload[4:10]
|
||||
]
|
||||
|
||||
@@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_pylance", [False, True])
|
||||
def test_blob_uri_array(with_pylance):
|
||||
if with_pylance:
|
||||
pytest.importorskip("lance")
|
||||
# Use fresh processes so each extension class can own Arrow's registry.
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
import importlib.abc
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if sys.argv[1] == "False":
|
||||
class MissingLance(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if fullname == "lance" or fullname.startswith("lance."):
|
||||
raise ModuleNotFoundError(fullname, name="lance")
|
||||
sys.meta_path.insert(0, MissingLance())
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb import BasePath, blob_uri_array
|
||||
from lancedb.schema import blob
|
||||
|
||||
if sys.argv[1] == "True":
|
||||
from lance import DatasetBasePath
|
||||
from lance.blob import BlobType
|
||||
else:
|
||||
from lancedb.schema import _FallbackBlobType as BlobType
|
||||
DatasetBasePath = None
|
||||
|
||||
schema = pa.schema([blob("video")])
|
||||
array = blob_uri_array(
|
||||
["s3://bucket/a.mp4", None, "b.mp4"],
|
||||
positions=[0, None, None],
|
||||
sizes=[4, None, None],
|
||||
)
|
||||
assert isinstance(array, pa.ExtensionArray)
|
||||
assert type(array.type) is BlobType
|
||||
assert array.type == schema.field("video").type
|
||||
assert array.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
|
||||
None,
|
||||
{"data": None, "uri": "b.mp4", "position": None, "size": None},
|
||||
]
|
||||
whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
|
||||
assert whole.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
|
||||
]
|
||||
|
||||
checks = [
|
||||
(lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
|
||||
"both position and size",
|
||||
),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
|
||||
(lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
|
||||
(lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
|
||||
(lambda: blob_uri_array([b"u"]), "must be a string"),
|
||||
]
|
||||
for call, fragment in checks:
|
||||
try:
|
||||
call()
|
||||
except (TypeError, ValueError, OverflowError) as error:
|
||||
assert fragment in str(error), (fragment, error)
|
||||
else:
|
||||
raise AssertionError(f"accepted invalid input: {fragment}")
|
||||
|
||||
try:
|
||||
BasePath("s3://bucket", id=0)
|
||||
except ValueError as error:
|
||||
assert "id=None" in str(error)
|
||||
else:
|
||||
raise AssertionError("accepted explicit id=0")
|
||||
|
||||
# The public create route must accept the helper and register the base
|
||||
# in the same commit as the data, with or without pylance.
|
||||
root = pathlib.Path(tempfile.mkdtemp())
|
||||
base_dir = root / "videos"
|
||||
base_dir.mkdir()
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
db = lancedb.connect(root / "db")
|
||||
field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
table_schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=table_schema
|
||||
)
|
||||
if DatasetBasePath is not None:
|
||||
bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
|
||||
else:
|
||||
bases = [BasePath(path=base_dir.as_uri(), name="source")]
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
assert (
|
||||
table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
)
|
||||
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
|
||||
assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
|
||||
assert table.fetch_blob_ranges(
|
||||
"video", [(row_ids[0].as_py(), 1, 3)]
|
||||
).to_pylist() == [payload[1:4]]
|
||||
if DatasetBasePath is not None:
|
||||
base_paths = table.to_lance().base_paths()
|
||||
assert base_paths[1].path == base_dir.as_uri()
|
||||
assert base_paths[1].is_dataset_root is False
|
||||
if sys.argv[1] == "False":
|
||||
assert "lance" not in sys.modules
|
||||
"""
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script, str(with_pylance)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from test_remote_db import (
|
||||
BLOB_DESCRIBE_RESPONSE,
|
||||
blob_descriptor_take_table,
|
||||
mock_lancedb_connection,
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def remote_buffer_table(*, http_requests=None, truncate_first=False):
|
||||
payload = bytes(range(256)) * 4096
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
path = urlparse(request.path).path
|
||||
if http_requests is not None:
|
||||
http_requests.append(path)
|
||||
if path.endswith("/describe/"):
|
||||
body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode()
|
||||
content_type = "application/json"
|
||||
elif path.endswith("/query/"):
|
||||
data = json.loads(
|
||||
request.rfile.read(int(request.headers["Content-Length"]))
|
||||
)
|
||||
assert data["columns"] == ["image"]
|
||||
table = blob_descriptor_take_table().slice(0, 1)
|
||||
images = table["image"].combine_chunks()
|
||||
images = pa.StructArray.from_arrays(
|
||||
[
|
||||
images.field("kind"),
|
||||
images.field("position"),
|
||||
pa.array([len(payload)], pa.uint64()),
|
||||
images.field("blob_id"),
|
||||
images.field("blob_uri"),
|
||||
],
|
||||
fields=list(images.type),
|
||||
)
|
||||
table = table.set_column(0, table.schema.field(0), images)
|
||||
sink = pa.BufferOutputStream()
|
||||
with pa.ipc.new_stream(sink, table.schema) as writer:
|
||||
writer.write_table(table)
|
||||
body = sink.getvalue().to_pybytes()
|
||||
content_type = "application/vnd.apache.arrow.stream"
|
||||
else:
|
||||
assert path == "/v1/table/test/blob/image/10/bytes"
|
||||
assert "version=1" in request.path
|
||||
start, end = map(int, request.headers["Range"][6:].split("-"))
|
||||
requests.append((start, end + 1))
|
||||
body = payload[start : end + 1]
|
||||
if truncate_first and len(requests) == 1:
|
||||
body = body[:5]
|
||||
request.send_response(206)
|
||||
request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
|
||||
request.send_header("Content-Length", str(len(body)))
|
||||
request.end_headers()
|
||||
request.wfile.write(body)
|
||||
return
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", content_type)
|
||||
request.send_header("Content-Length", str(len(body)))
|
||||
request.send_header("phalanx-version", "0.5.0")
|
||||
request.send_header("x-lancedb-version", "1")
|
||||
request.end_headers()
|
||||
request.wfile.write(body)
|
||||
|
||||
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
|
||||
yield db.open_table("test"), payload, requests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024])
|
||||
async def test_remote_read_ahead_over_http(use_async, buffer_size):
|
||||
with remote_buffer_table() as (table, payload, requests):
|
||||
if use_async:
|
||||
files = await table._table.fetch_blob_files(
|
||||
"image", [10], buffer_size=buffer_size
|
||||
)
|
||||
else:
|
||||
files = table.fetch_blob_files("image", [10], buffer_size=buffer_size)
|
||||
file = files[0]
|
||||
assert requests == []
|
||||
assert file.read(2) == payload[:2]
|
||||
window = 512 * 1024 if buffer_size is None else max(buffer_size, 2)
|
||||
assert requests == [(0, window)]
|
||||
assert file.read(2) == payload[2:4]
|
||||
assert len(requests) == (2 if buffer_size == 0 else 1)
|
||||
file.seek(1)
|
||||
assert file.read(1) == payload[1:2]
|
||||
assert len(requests) == (3 if buffer_size == 0 else 1)
|
||||
before = len(requests)
|
||||
assert file.read_range(0, 1) == payload[:1]
|
||||
assert len(requests) == before + 1
|
||||
assert requests[-1] == (0, 1)
|
||||
assert file.tell() == 2
|
||||
file.set_buffer_size(0)
|
||||
assert file.read(1) == payload[2:3]
|
||||
assert requests[-1] == (2, 3)
|
||||
file.set_buffer_size(16)
|
||||
assert file.read(1) == payload[3:4]
|
||||
assert requests[-1] == (3, 19)
|
||||
file.seek(len(payload) - 1)
|
||||
assert file.read(4) == payload[-1:]
|
||||
assert requests[-1] == (len(payload) - 1, len(payload))
|
||||
before = len(requests)
|
||||
assert file.read(1) == b""
|
||||
assert len(requests) == before
|
||||
file.close()
|
||||
with pytest.raises(ValueError, match="closed"):
|
||||
file.set_buffer_size(0)
|
||||
|
||||
|
||||
def test_short_prefetch_over_http_preserves_cursor():
|
||||
with remote_buffer_table(truncate_first=True) as (table, payload, requests):
|
||||
file = table.fetch_blob_files("image", [10], buffer_size=8)[0]
|
||||
with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"):
|
||||
file.read(6)
|
||||
assert file.tell() == 0
|
||||
assert file.read(3) == payload[:3]
|
||||
assert file.tell() == 3
|
||||
assert requests == [(0, 8), (0, 8)]
|
||||
file.close()
|
||||
|
||||
|
||||
def test_idle_prefetch_releases_http_concurrency_slot():
|
||||
with remote_buffer_table() as (table, payload, requests):
|
||||
first, second = table.fetch_blob_files("image", [10, 10])
|
||||
assert first.read(1) == payload[:1]
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
def read_other():
|
||||
try:
|
||||
results.append(second.read(1))
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
|
||||
reader = threading.Thread(target=read_other, daemon=True)
|
||||
reader.start()
|
||||
reader.join(timeout=2)
|
||||
completed_while_first_idle = not reader.is_alive()
|
||||
first.close()
|
||||
reader.join(timeout=2)
|
||||
second.close()
|
||||
assert completed_while_first_idle, (
|
||||
"idle prefetch retained the HTTP request slot"
|
||||
)
|
||||
assert not errors
|
||||
assert results == [payload[:1]]
|
||||
assert requests == [(0, 512 * 1024), (0, 512 * 1024)]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_local_buffer_configuration_through_python(tmp_path, use_async):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")])
|
||||
)
|
||||
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
|
||||
if use_async:
|
||||
files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0)
|
||||
else:
|
||||
files = table.fetch_blob_files("image", row_ids, buffer_size=0)
|
||||
file = files[0]
|
||||
assert file.read(2) == b"01"
|
||||
file.set_buffer_size(4)
|
||||
assert file.read(2) == b"23"
|
||||
file.seek(1)
|
||||
assert file.read(3) == b"123"
|
||||
assert file.read_range(8, 2) == b"89"
|
||||
with pytest.raises(ValueError, match="non-negative"):
|
||||
file.set_buffer_size(-1)
|
||||
with pytest.raises(TypeError):
|
||||
file.set_buffer_size(1.5)
|
||||
file.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_open_descriptor_files_forward_buffer_size(use_async):
|
||||
with remote_buffer_table() as (table, payload, requests):
|
||||
descriptor = {
|
||||
"kind": 1,
|
||||
"position": 0,
|
||||
"size": len(payload),
|
||||
"blob_id": 0,
|
||||
"blob_uri": "",
|
||||
"source": {
|
||||
"uri": "s3://bucket/test.lance",
|
||||
"version": 1,
|
||||
"committed_at_micros": 1,
|
||||
"column": "image",
|
||||
"row_reference": 10,
|
||||
"row_is_address": False,
|
||||
},
|
||||
}
|
||||
if use_async:
|
||||
files = [
|
||||
file
|
||||
async for file in table._table.open_blob_files(
|
||||
[None, descriptor], buffer_size=8
|
||||
)
|
||||
]
|
||||
else:
|
||||
files = list(table.open_blob_files([None, descriptor], buffer_size=8))
|
||||
assert files[0] is None
|
||||
assert files[1].read(1) == payload[:1]
|
||||
assert requests == [(0, 8)]
|
||||
files[1].close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_invalid_buffer_size_rejects_before_http(use_async):
|
||||
http_requests = []
|
||||
with remote_buffer_table(http_requests=http_requests) as (table, _, requests):
|
||||
http_requests.clear()
|
||||
with pytest.raises(ValueError, match="non-negative"):
|
||||
if use_async:
|
||||
await table._table.fetch_blob_files("image", [10], buffer_size=-1)
|
||||
else:
|
||||
table.fetch_blob_files("image", [10], buffer_size=-1)
|
||||
assert requests == []
|
||||
assert http_requests == []
|
||||
@@ -8,12 +8,7 @@ import textwrap
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["sync", "async"])
|
||||
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
|
||||
def test_blob_query_without_pylance(tmp_path, api, result):
|
||||
if result == "pandas":
|
||||
pytest.importorskip("pandas")
|
||||
script = """\
|
||||
_WITHOUT_LANCE = """\
|
||||
import importlib.abc
|
||||
import sys
|
||||
|
||||
@@ -23,7 +18,15 @@ class MissingLance(importlib.abc.MetaPathFinder):
|
||||
raise ModuleNotFoundError(fullname, name="lance")
|
||||
|
||||
sys.meta_path.insert(0, MissingLance())
|
||||
""" + textwrap.dedent(
|
||||
"""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["sync", "async"])
|
||||
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
|
||||
def test_blob_query_without_pylance(tmp_path, api, result):
|
||||
if result == "pandas":
|
||||
pytest.importorskip("pandas")
|
||||
script = _WITHOUT_LANCE + textwrap.dedent(
|
||||
"""\
|
||||
import asyncio
|
||||
import lancedb
|
||||
@@ -94,3 +97,187 @@ sys.meta_path.insert(0, MissingLance())
|
||||
text=True,
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["sync", "async"])
|
||||
@pytest.mark.parametrize("result", ["pandas", "batches", "arrow"])
|
||||
def test_plain_legacy_blob_query_without_pylance(tmp_path, api, result):
|
||||
if result == "pandas":
|
||||
pytest.importorskip("pandas")
|
||||
script = _WITHOUT_LANCE + textwrap.dedent(
|
||||
"""\
|
||||
import asyncio
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb.query import ColumnOrdering
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("filename", pa.string()),
|
||||
pa.field(
|
||||
"video_blob",
|
||||
pa.large_binary(),
|
||||
metadata={"lance-encoding:blob": "true"},
|
||||
),
|
||||
]
|
||||
)
|
||||
rows = [
|
||||
{"id": 1, "filename": "file-1.mp4", "video_blob": b"outside"},
|
||||
{"id": 2, "filename": "file-2.mp4", "video_blob": b""},
|
||||
{"id": 3, "filename": "file-3.mp4", "video_blob": None},
|
||||
{"id": 4, "filename": "file-4.mp4", "video_blob": b"four"},
|
||||
]
|
||||
expected = [
|
||||
{"filename": "file-2.mp4", "payload": b""},
|
||||
{"filename": "file-3.mp4", "payload": None},
|
||||
{"filename": "file-4.mp4", "payload": b"four"},
|
||||
]
|
||||
|
||||
def configure(query):
|
||||
return (
|
||||
query.select({"filename": "filename", "payload": "video_blob"})
|
||||
.where("id >= 2")
|
||||
.order_by(
|
||||
[ColumnOrdering(column_name="id", ascending=True)]
|
||||
)
|
||||
.limit(3)
|
||||
)
|
||||
|
||||
async def main():
|
||||
storage_options = {"new_table_data_storage_version": "2.1"}
|
||||
if sys.argv[2] == "async":
|
||||
db = await lancedb.connect_async(
|
||||
sys.argv[1], storage_options=storage_options
|
||||
)
|
||||
table = await db.create_table("legacy", schema=schema)
|
||||
await table.add(rows)
|
||||
table = await db.open_table("legacy")
|
||||
def query():
|
||||
return configure(table.query())
|
||||
def original_query():
|
||||
return table.query().select(
|
||||
{"filename": "filename", "payload": "video_blob"}
|
||||
).limit(1)
|
||||
def empty_query():
|
||||
return query().where("id < 0")
|
||||
def batches():
|
||||
return query().to_batches(
|
||||
max_batch_length=1, blob_mode="bytes"
|
||||
)
|
||||
else:
|
||||
db = lancedb.connect(
|
||||
sys.argv[1], storage_options=storage_options
|
||||
)
|
||||
table = db.create_table("legacy", schema=schema)
|
||||
table.add(rows)
|
||||
table = db.open_table("legacy")
|
||||
def query():
|
||||
return configure(table.search())
|
||||
def original_query():
|
||||
return table.search().select(
|
||||
{"filename": "filename", "payload": "video_blob"}
|
||||
).limit(1)
|
||||
def empty_query():
|
||||
return query().where("id < 0")
|
||||
def batches():
|
||||
return query().to_batches(
|
||||
batch_size=1, blob_mode="bytes"
|
||||
)
|
||||
|
||||
if sys.argv[2] == "async":
|
||||
reused = table.query().select(
|
||||
{"filename": "filename", "payload": "video_blob"}
|
||||
).limit(3)
|
||||
byte_reader = await reused.to_batches(blob_mode="bytes")
|
||||
await byte_reader.read_all()
|
||||
lazy_reader = await reused.to_batches(blob_mode="lazy")
|
||||
assert "_rowid" not in lazy_reader.schema.names
|
||||
await lazy_reader.read_all()
|
||||
reused.select(["filename"])
|
||||
nonblob_reader = await reused.to_batches(blob_mode="lazy")
|
||||
assert nonblob_reader.schema.names == ["filename"]
|
||||
await nonblob_reader.read_all()
|
||||
|
||||
if sys.argv[3] == "pandas":
|
||||
frame = query().to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
frame = await frame
|
||||
assert frame.to_dict("records") == expected
|
||||
original = original_query().to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
original = await original
|
||||
assert original.to_dict("records") == [
|
||||
{"filename": "file-1.mp4", "payload": b"outside"}
|
||||
]
|
||||
direct = table.to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
direct = await direct
|
||||
assert direct.to_dict("records") == rows
|
||||
empty = empty_query().to_pandas(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
empty = await empty
|
||||
assert empty.to_dict("records") == []
|
||||
elif sys.argv[3] == "batches":
|
||||
reader = batches()
|
||||
if sys.argv[2] == "async":
|
||||
reader = await reader
|
||||
rows_out = [batch async for batch in reader]
|
||||
else:
|
||||
rows_out = list(reader)
|
||||
assert reader.schema.field("payload").type == pa.large_binary()
|
||||
assert "_rowid" not in reader.schema.names
|
||||
assert all(batch.num_rows == 1 for batch in rows_out)
|
||||
assert all(batch.schema == reader.schema for batch in rows_out)
|
||||
actual = [row for batch in rows_out for row in batch.to_pylist()]
|
||||
assert actual == expected
|
||||
original_reader = original_query().to_batches(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
original_reader = await original_reader
|
||||
original_rows = [batch async for batch in original_reader]
|
||||
else:
|
||||
original_rows = list(original_reader)
|
||||
assert [
|
||||
row for batch in original_rows for row in batch.to_pylist()
|
||||
] == [{"filename": "file-1.mp4", "payload": b"outside"}]
|
||||
empty_reader = empty_query().to_batches(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
empty_reader = await empty_reader
|
||||
empty_batches = [batch async for batch in empty_reader]
|
||||
else:
|
||||
empty_batches = list(empty_reader)
|
||||
assert empty_batches == []
|
||||
assert empty_reader.schema.field("payload").type == pa.large_binary()
|
||||
else:
|
||||
table_out = query().to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
table_out = await table_out
|
||||
assert table_out.schema.field("payload").type == pa.large_binary()
|
||||
assert "_rowid" not in table_out.column_names
|
||||
assert table_out.to_pylist() == expected
|
||||
original = original_query().to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
original = await original
|
||||
assert original.to_pylist() == [
|
||||
{"filename": "file-1.mp4", "payload": b"outside"}
|
||||
]
|
||||
direct = table.to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
direct = await direct
|
||||
assert direct.to_pylist() == rows
|
||||
empty_table = empty_query().to_arrow(blob_mode="bytes")
|
||||
if sys.argv[2] == "async":
|
||||
empty_table = await empty_table
|
||||
assert empty_table.num_rows == 0
|
||||
assert empty_table.schema.field("payload").type == pa.large_binary()
|
||||
assert "lance" not in sys.modules
|
||||
|
||||
asyncio.run(main())
|
||||
"""
|
||||
)
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-c", script, str(tmp_path), api, result],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Exercise the public sync/async range APIs over bounded loopback HTTP."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import threading
|
||||
|
||||
import lancedb._lancedb as native
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
from lancedb.remote.errors import HttpError, TableNotFoundError
|
||||
from test_remote_db import mock_lancedb_connection
|
||||
|
||||
MIB = 1024 * 1024
|
||||
IDENTITY = "v1:" + "a" * 64
|
||||
ROUTE = "/v1/table/test/fetch_blob_ranges/"
|
||||
|
||||
|
||||
def payload(row, offset, length, version):
|
||||
pattern = bytes((row * 17 + i + version) % 251 for i in range(251))
|
||||
start = offset % 251
|
||||
return (pattern * ((start + length + 250) // 251))[start : start + length]
|
||||
|
||||
|
||||
class RangeServer:
|
||||
def __init__(self, fault=None):
|
||||
self.fault = fault
|
||||
self.calls = []
|
||||
self.fetches = []
|
||||
self.identities = []
|
||||
self.stalled = threading.Event()
|
||||
self.release = threading.Event()
|
||||
|
||||
def __call__(self, request):
|
||||
request.connection.settimeout(15)
|
||||
size = int(request.headers.get("Content-Length", 0))
|
||||
assert size <= 256 * 1024
|
||||
body = json.loads(request.rfile.read(size) or b"{}")
|
||||
self.calls.append((request.command, request.path, body))
|
||||
if request.path in (
|
||||
"/v1/table/test/describe/",
|
||||
"/v1/table/test/branches/list/",
|
||||
):
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.send_header("phalanx-version", "1.13.0-beta.0")
|
||||
if request.path.endswith("/describe/"):
|
||||
request.send_header("x-lancedb-blob-ranges", "1")
|
||||
request.end_headers()
|
||||
response = (
|
||||
{
|
||||
"branches": {
|
||||
"experiment": {
|
||||
"parentBranch": None,
|
||||
"parentVersion": 1,
|
||||
"createAt": 1,
|
||||
"manifestSize": 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
if request.path.endswith("branches/list/")
|
||||
else {"version": 8, "schema": {"fields": []}}
|
||||
)
|
||||
request.wfile.write(json.dumps(response).encode())
|
||||
return
|
||||
assert (request.command, request.path) == ("POST", ROUTE)
|
||||
self.fetches.append(body)
|
||||
self.identities.append(request.headers.get("x-lancedb-query-snapshot"))
|
||||
assert body["column"] == "image"
|
||||
assert body["branch"] == "experiment"
|
||||
ranges = body["ranges"]
|
||||
assert len(ranges) <= 1024
|
||||
assert sum(r["length"] for r in ranges) <= 64 * MIB
|
||||
version = body["version"] or (7 if len(self.fetches) == 1 else 8)
|
||||
values = [
|
||||
None
|
||||
if r["row_id"] == 20
|
||||
else payload(r["row_id"], r["offset"], r["length"], version)
|
||||
for r in ranges
|
||||
]
|
||||
fault = (
|
||||
self.fault
|
||||
if len(self.fetches) > 1 or str(self.fault).startswith("first-")
|
||||
else None
|
||||
)
|
||||
if fault in ("recreated", "gone"):
|
||||
request.send_response(400 if fault == "recreated" else 404)
|
||||
request.end_headers()
|
||||
request.wfile.write(
|
||||
b"query snapshot identity mismatch: source gone or replaced"
|
||||
)
|
||||
return
|
||||
if fault == "stall" and len(self.fetches) == 2:
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
|
||||
request.send_header("x-lancedb-version", str(version))
|
||||
request.send_header("x-lancedb-query-snapshot", IDENTITY)
|
||||
request.end_headers()
|
||||
request.wfile.flush()
|
||||
self.stalled.set()
|
||||
assert self.release.wait(15), "test did not release stalled response"
|
||||
return
|
||||
if fault == "structured400":
|
||||
request.send_response(400)
|
||||
request.send_header("x-lancedb-error-code", "invalid_input")
|
||||
request.end_headers()
|
||||
request.wfile.write(b'{"error":"range exceeds blob size"}')
|
||||
return
|
||||
if isinstance(fault, int):
|
||||
request.send_response(fault)
|
||||
request.end_headers()
|
||||
request.wfile.write(b"ordinary server failure")
|
||||
return
|
||||
if fault == "disconnect":
|
||||
request.connection.shutdown(socket.SHUT_RDWR)
|
||||
return
|
||||
column = "wrong" if fault == "column" else "value"
|
||||
data_type = pa.binary() if fault == "type" else pa.large_binary()
|
||||
if fault == "count":
|
||||
values = []
|
||||
elif fault == "length":
|
||||
values = [b""]
|
||||
batch = pa.table({column: pa.array(values, type=data_type)})
|
||||
sink = pa.BufferOutputStream()
|
||||
with pa.ipc.new_stream(sink, batch.schema) as writer:
|
||||
writer.write_table(batch, max_chunksize=257)
|
||||
ipc = sink.getvalue().to_pybytes()
|
||||
if fault == "eos":
|
||||
ipc = ipc[:-8]
|
||||
elif fault == "body":
|
||||
ipc = ipc[: len(ipc) // 2]
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
|
||||
if fault != "version":
|
||||
request.send_header("x-lancedb-version", str(version))
|
||||
if fault not in ("missing-identity", "first-missing-identity"):
|
||||
identity = (
|
||||
"broken"
|
||||
if fault == "first-invalid-identity"
|
||||
else "v1:" + "b" * 64
|
||||
if fault == "wrong-identity"
|
||||
else IDENTITY
|
||||
)
|
||||
request.send_header("x-lancedb-query-snapshot", identity)
|
||||
request.send_header(
|
||||
"Content-Length", str(len(ipc) + (10 if fault == "transport" else 0))
|
||||
)
|
||||
request.end_headers()
|
||||
for i in range(0, len(ipc), 8192):
|
||||
request.wfile.write(ipc[i : i + 8192])
|
||||
|
||||
|
||||
async def fetch(table, requests, use_async):
|
||||
result = table.fetch_blob_ranges("image", requests)
|
||||
return await result if use_async else result
|
||||
|
||||
|
||||
def api(db, use_async, version=None):
|
||||
table = db.open_table("test", branch="experiment", version=version)
|
||||
return table._table if use_async else table
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("version", [None, 3])
|
||||
async def test_range_sdk_order_snapshot_and_overwrite(use_async, version):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async, version)
|
||||
requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)]
|
||||
requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)]
|
||||
result = await fetch(table, requests, use_async)
|
||||
assert isinstance(result, pa.LargeBinaryArray)
|
||||
assert result.to_pylist() == [
|
||||
None if row == 20 else payload(row, offset, length, version or 7)
|
||||
for row, offset, length in requests
|
||||
]
|
||||
assert [b["version"] for b in handler.fetches] == [version, version or 7]
|
||||
result = await fetch(table, [(10, 0, 1)], use_async)
|
||||
assert result.to_pylist() == [payload(10, 0, 1, version or 8)]
|
||||
assert handler.fetches[-1]["version"] == version
|
||||
assert len(handler.fetches) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_cached_reopen_negotiates_capability(use_async):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
for version in (7, 8):
|
||||
table = api(db, use_async)
|
||||
result = await fetch(table, [(10, 0, 1)], use_async)
|
||||
assert result.to_pylist() == [payload(10, 0, 1, version)]
|
||||
assert len(handler.fetches) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_large_single_and_aggregate_budget(use_async):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
requests = [
|
||||
(10, 3, 33 * MIB),
|
||||
(30, 7, 33 * MIB),
|
||||
(40, 11, 70 * MIB),
|
||||
(20, 0, 2**64 - 1),
|
||||
]
|
||||
# The loopback server advances latest after the first partition.
|
||||
result = await fetch(table, requests, use_async)
|
||||
assert len(result) == 4
|
||||
for i, (row, offset, length) in enumerate(requests[:3]):
|
||||
expected = payload(row, offset, length, 7)
|
||||
assert (
|
||||
hashlib.sha256(result[i].as_buffer()).digest()
|
||||
== hashlib.sha256(expected).digest()
|
||||
)
|
||||
assert len(result[i].as_buffer()) == length
|
||||
assert result[3].as_py() is None
|
||||
assert len(handler.fetches) == 3
|
||||
assert [b["version"] for b in handler.fetches] == [None, 7, 7]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"fault",
|
||||
[
|
||||
"type",
|
||||
"column",
|
||||
"count",
|
||||
"length",
|
||||
"eos",
|
||||
"body",
|
||||
"transport",
|
||||
"version",
|
||||
"disconnect",
|
||||
401,
|
||||
403,
|
||||
404,
|
||||
429,
|
||||
500,
|
||||
],
|
||||
)
|
||||
async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault):
|
||||
handler = RangeServer(fault=fault)
|
||||
with mock_lancedb_connection(
|
||||
handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2}
|
||||
) as db:
|
||||
table = api(db, use_async)
|
||||
with pytest.raises(Exception) as exc:
|
||||
await fetch(table, [(10, 0, 1)] * 1025, use_async)
|
||||
if fault == 404:
|
||||
assert isinstance(exc.value, TableNotFoundError)
|
||||
assert isinstance(exc.value.__cause__, HttpError)
|
||||
assert exc.value.__cause__.status_code == 404
|
||||
else:
|
||||
assert not isinstance(exc.value, ValueError)
|
||||
if isinstance(fault, int):
|
||||
assert exc.value.status_code == fault
|
||||
assert len(handler.fetches) == 2
|
||||
assert all(
|
||||
path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE)
|
||||
for _, path, _ in handler.calls
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_structured_400_preserves_value_error(use_async):
|
||||
handler = RangeServer(fault="structured400")
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
with pytest.raises(ValueError, match="range exceeds blob size"):
|
||||
await fetch(table, [(10, 0, 1)] * 1025, use_async)
|
||||
assert len(handler.fetches) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_range_sdk_async_cancel_releases_only_request_permit():
|
||||
handler = RangeServer(fault="stall")
|
||||
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
|
||||
table = api(db, True)
|
||||
pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True))
|
||||
try:
|
||||
assert await asyncio.to_thread(handler.stalled.wait, 10)
|
||||
pending.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await pending
|
||||
assert len(handler.fetches) == 2
|
||||
result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5)
|
||||
assert result.to_pylist() == [payload(10, 0, 1, 8)]
|
||||
assert len(handler.fetches) == 3
|
||||
finally:
|
||||
pending.cancel()
|
||||
handler.release.set()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_range_sdk_integer_validation_and_empty_zero_io(use_async):
|
||||
handler = RangeServer()
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
before = len(handler.calls)
|
||||
assert (await fetch(table, [], use_async)).to_pylist() == []
|
||||
for request in [
|
||||
(-1, 0, 1),
|
||||
(2**64, 0, 1),
|
||||
(10, -1, 1),
|
||||
(10, 0, -1),
|
||||
(10, 0, 2**64),
|
||||
(10, 0.5, 1),
|
||||
(20, 2**64 - 1, 1),
|
||||
(10, 0),
|
||||
]:
|
||||
with pytest.raises((ValueError, OverflowError, TypeError)):
|
||||
await fetch(table, [request], use_async)
|
||||
assert len(handler.calls) == before
|
||||
|
||||
|
||||
def test_range_sdk_loaded_artifact_identity():
|
||||
artifact = Path(native.__file__).resolve()
|
||||
digest = hashlib.sha256()
|
||||
with artifact.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}")
|
||||
assert artifact.is_file()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"fault", ["missing-identity", "wrong-identity", "recreated", "gone"]
|
||||
)
|
||||
@pytest.mark.parametrize("huge", [False, True])
|
||||
async def test_range_sdk_original_identity_survives_every_partition(
|
||||
use_async, fault, huge
|
||||
):
|
||||
handler = RangeServer(fault=fault)
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025
|
||||
error = (
|
||||
ValueError
|
||||
if fault == "recreated"
|
||||
else TableNotFoundError
|
||||
if fault == "gone"
|
||||
else NotImplementedError
|
||||
)
|
||||
with pytest.raises(
|
||||
error, match="snapshot identity" if fault != "gone" else None
|
||||
):
|
||||
await fetch(table, requests, use_async)
|
||||
assert handler.identities == [None, IDENTITY]
|
||||
assert len(handler.fetches) == 2
|
||||
assert [body["version"] for body in handler.fetches] == [None, 7]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"])
|
||||
async def test_range_sdk_bulk_requires_identity_before_payload_acceptance(
|
||||
use_async, fault
|
||||
):
|
||||
handler = RangeServer(fault=fault)
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = api(db, use_async)
|
||||
before = len(handler.calls)
|
||||
with pytest.raises(NotImplementedError, match="snapshot identity"):
|
||||
await fetch(table, [(10, 0, 1)] * 1025, use_async)
|
||||
assert len(handler.fetches) == 1
|
||||
assert len(handler.calls) == before + 1
|
||||
@@ -2,7 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import warnings
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
|
||||
endpoint,
|
||||
api_key="secret",
|
||||
sql_host_override="invalid://localhost",
|
||||
storage_options={"azure_storage_account_name": "catalog-account"},
|
||||
client_config={
|
||||
"extra_headers": {
|
||||
"X-LanceDB-Database": "wrong",
|
||||
@@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
|
||||
assert db.table_names() == []
|
||||
restored = lancedb.deserialize_conn(db.serialize())
|
||||
assert restored.sql_host_override == "invalid://localhost"
|
||||
assert restored.storage_options == {"azure_storage_account_name": "catalog-account"}
|
||||
for connection in (db, restored):
|
||||
with pytest.raises(ValueError, match="sql_host_override must use"):
|
||||
connection.execute_query_async("SELECT 1")
|
||||
@@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
|
||||
)
|
||||
assert "x-lancedb-database-prefix" not in headers
|
||||
assert headers["x-api-key"] == "secret"
|
||||
assert headers["x-azure-storage-account-name"] == "catalog-account"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server):
|
||||
]
|
||||
)
|
||||
catalog = await lancedb.connect_catalog_async(
|
||||
endpoint, sql_host_override="invalid://localhost"
|
||||
endpoint,
|
||||
sql_host_override="invalid://localhost",
|
||||
storage_options={"account_name": "async-account"},
|
||||
)
|
||||
assert isinstance(catalog, lancedb.AsyncCatalog)
|
||||
db = await catalog.connect_database("analytics")
|
||||
@@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server):
|
||||
await catalog.drop_database("full")
|
||||
await catalog.drop_database("missing", ignore_missing=True)
|
||||
assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"}
|
||||
for _, headers, _ in requests:
|
||||
headers = {key.lower(): value for key, value in headers.items()}
|
||||
assert headers["x-azure-storage-account-name"] == "async-account"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"])
|
||||
@@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint):
|
||||
lancedb.connect_catalog(endpoint)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"])
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_accepts_database_connection_settings(
|
||||
catalog_server, asynchronous, region
|
||||
):
|
||||
endpoint, requests, responses = catalog_server
|
||||
responses.extend([(200, {"namespaces": []}), (200, {"tables": []})])
|
||||
settings = {
|
||||
"uri": "db://analytics",
|
||||
"api_key": "shared-secret",
|
||||
"region": region,
|
||||
"host_override": endpoint,
|
||||
"sql_host_override": "invalid://localhost",
|
||||
"read_consistency_interval": timedelta(seconds=5),
|
||||
"client_config": {"extra_headers": {"x-shared-setting": "shared"}},
|
||||
"storage_options": {"azure_storage_account_name": "shared-account"},
|
||||
"session": None,
|
||||
"manifest_enabled": False,
|
||||
"namespace_client_properties": None,
|
||||
}
|
||||
if not asynchronous:
|
||||
settings.update(
|
||||
request_thread_pool=None,
|
||||
namespace_client_impl=None,
|
||||
namespace_client_pushdown_operations=None,
|
||||
)
|
||||
with pytest.warns(
|
||||
UserWarning, match="region is ignored by connect_catalog"
|
||||
) as caught:
|
||||
catalog = (
|
||||
await lancedb.connect_catalog_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect_catalog(**settings)
|
||||
)
|
||||
assert len(caught) == 1
|
||||
assert catalog.uri == endpoint
|
||||
assert (
|
||||
[name async for name in catalog.list_databases()]
|
||||
if asynchronous
|
||||
else list(catalog.list_databases())
|
||||
) == []
|
||||
db = (
|
||||
await lancedb.connect_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect(**settings)
|
||||
)
|
||||
assert (await db.table_names() if asynchronous else db.table_names()) == []
|
||||
root_headers = {key.lower(): value for key, value in requests[0][1].items()}
|
||||
db_headers = {key.lower(): value for key, value in requests[1][1].items()}
|
||||
for headers in (root_headers, db_headers):
|
||||
assert headers["x-api-key"] == "shared-secret"
|
||||
assert headers["x-shared-setting"] == "shared"
|
||||
assert headers["x-azure-storage-account-name"] == "shared-account"
|
||||
assert "x-lancedb-database" not in root_headers
|
||||
assert db_headers["x-lancedb-database"] == "analytics"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("host_only", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_default_region_is_silent_and_api_key_uses_environment(
|
||||
catalog_server, monkeypatch, asynchronous, host_only
|
||||
):
|
||||
endpoint, requests, responses = catalog_server
|
||||
monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret")
|
||||
responses.extend([(200, {}), (200, {"tables": []})])
|
||||
settings = {"host_override": endpoint} if host_only else {"uri": endpoint}
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
catalog = (
|
||||
await lancedb.connect_catalog_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect_catalog(**settings)
|
||||
)
|
||||
assert caught == []
|
||||
assert catalog.uri == endpoint
|
||||
db = (
|
||||
await catalog.connect_database("analytics")
|
||||
if asynchronous
|
||||
else catalog.connect_database("analytics")
|
||||
)
|
||||
if not asynchronous:
|
||||
db = lancedb.deserialize_conn(db.serialize())
|
||||
assert (await db.table_names() if asynchronous else db.table_names()) == []
|
||||
for _, headers, _ in requests:
|
||||
headers = {key.lower(): value for key, value in headers.items()}
|
||||
assert headers["x-api-key"] == "environment-secret"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous):
|
||||
endpoint, _, _ = catalog_server
|
||||
settings = {"uri": "https://unused.example", "host_override": endpoint}
|
||||
catalog = (
|
||||
await lancedb.connect_catalog_async(**settings)
|
||||
if asynchronous
|
||||
else lancedb.connect_catalog(**settings)
|
||||
)
|
||||
assert catalog.uri == endpoint
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"options, message",
|
||||
[
|
||||
({}, "uri or host_override is required"),
|
||||
({"session": object()}, "session"),
|
||||
({"manifest_enabled": True}, "manifest_enabled"),
|
||||
({"namespace_client_properties": {}}, "namespace_client_properties"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_rejects_unsupported_connection_settings(
|
||||
catalog_server, asynchronous, options, message
|
||||
):
|
||||
_, requests, _ = catalog_server
|
||||
error = NotImplementedError if options else ValueError
|
||||
with pytest.raises(error, match=message):
|
||||
if asynchronous:
|
||||
await lancedb.connect_catalog_async(**options)
|
||||
else:
|
||||
lancedb.connect_catalog(**options)
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"options, error, message",
|
||||
[
|
||||
(
|
||||
{"namespace_client_impl": "dir"},
|
||||
NotImplementedError,
|
||||
"namespace_client_impl",
|
||||
),
|
||||
(
|
||||
{"namespace_client_pushdown_operations": []},
|
||||
NotImplementedError,
|
||||
"namespace_client_pushdown_operations",
|
||||
),
|
||||
({"unknown_option": True}, ValueError, "Unknown keyword arguments"),
|
||||
],
|
||||
)
|
||||
def test_catalog_rejects_unsupported_sync_settings(options, error, message):
|
||||
with pytest.raises(error, match=message):
|
||||
lancedb.connect_catalog(**options)
|
||||
|
||||
|
||||
def test_catalog_accepts_deprecated_sync_settings(catalog_server):
|
||||
endpoint, _, responses = catalog_server
|
||||
responses.append((200, {}))
|
||||
with pytest.warns(DeprecationWarning) as caught:
|
||||
catalog = lancedb.connect_catalog(
|
||||
endpoint,
|
||||
request_thread_pool=2,
|
||||
connection_timeout=5,
|
||||
read_timeout=10,
|
||||
)
|
||||
assert len(caught) == 3
|
||||
db = catalog.connect_database("analytics")
|
||||
assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5)
|
||||
assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)])
|
||||
|
||||
@@ -0,0 +1,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]
|
||||
@@ -0,0 +1,36 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous):
|
||||
source_uri = str(tmp_path / "source.lance")
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
await db.create_table("source", [{"id": 1}])
|
||||
table = await db.clone_table("target", source_uri, exist_ok=True)
|
||||
assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
|
||||
await table.add([{"id": 2}])
|
||||
version = await table.version()
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
await db.clone_table("target", source_uri)
|
||||
kept = await db.clone_table("target", "missing.lance", exist_ok=True)
|
||||
assert await kept.version() == version
|
||||
assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}]
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
db.create_table("source", [{"id": 1}])
|
||||
table = db.clone_table("target", source_uri, exist_ok=True)
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1}]
|
||||
table.add([{"id": 2}])
|
||||
version = table.version
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
db.clone_table("target", source_uri)
|
||||
kept = db.clone_table("target", "missing.lance", exist_ok=True)
|
||||
assert kept.version == version
|
||||
assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}]
|
||||
@@ -0,0 +1,319 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import lancedb
|
||||
import pytest
|
||||
from lancedb.embeddings import CohereEmbeddingFunction, get_registry
|
||||
from lancedb.pydantic import LanceModel
|
||||
from utils import start_server_thread
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def foundry_cohere(monkeypatch):
|
||||
pytest.importorskip("cohere", minversion="5.15.0")
|
||||
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
monkeypatch.setenv("COHERE_API_KEY", "test-hosted-key")
|
||||
monkeypatch.setenv("TEST_FOUNDRY_COHERE_KEY", "test-foundry-key")
|
||||
registry = get_registry()
|
||||
monkeypatch.setattr(registry, "_allowed_endpoints", set())
|
||||
monkeypatch.setattr(registry, "_variables", {})
|
||||
registry.set_var("foundry-key", os.environ["TEST_FOUNDRY_COHERE_KEY"])
|
||||
requests = []
|
||||
statuses = {}
|
||||
|
||||
class EmbedHandler(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
requests.append((self.path, self.headers.get("Authorization"), body))
|
||||
status = statuses.pop(body["texts"][0], None)
|
||||
if status is not None:
|
||||
self.send_response(status)
|
||||
if status == 307:
|
||||
self.send_header("Location", "/redirect-target/v2/embed")
|
||||
self.end_headers()
|
||||
return
|
||||
vectors = []
|
||||
for text in body["texts"]:
|
||||
matches = (body["input_type"], text) in {
|
||||
("search_document", "matching document"),
|
||||
("search_query", "matching query"),
|
||||
}
|
||||
if text == "wrong dimension":
|
||||
vectors.append([0.0])
|
||||
else:
|
||||
vectors.append(
|
||||
([1.0, 0.0] if matches else [0.0, 1.0]) + [0.0] * 254
|
||||
)
|
||||
response = json.dumps(
|
||||
{
|
||||
"id": "fixture",
|
||||
"embeddings": {"float": vectors},
|
||||
"texts": body["texts"],
|
||||
}
|
||||
).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(response)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with HTTPServer(("127.0.0.1", 0), EmbedHandler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
options = {
|
||||
"name": "my-embed-v4-deployment",
|
||||
"base_url": f"http://127.0.0.1:{server.server_port}/providers/cohere",
|
||||
"output_dimension": 256,
|
||||
"api_key": "$var:foundry-key",
|
||||
}
|
||||
yield options, requests, statuses
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_foundry_cohere_retrieval_and_endpoint_trust(
|
||||
foundry_cohere, monkeypatch, tmp_path
|
||||
):
|
||||
import httpx
|
||||
|
||||
options, requests, _ = foundry_cohere
|
||||
func = get_registry().get("cohere").create(**options)
|
||||
request_timeouts = []
|
||||
handle_request = httpx.HTTPTransport.handle_request
|
||||
|
||||
def record_request_timeout(transport, request):
|
||||
request_timeouts.append(request.extensions.get("timeout"))
|
||||
return handle_request(transport, request)
|
||||
|
||||
monkeypatch.setattr(httpx.HTTPTransport, "handle_request", record_request_timeout)
|
||||
|
||||
class Document(LanceModel):
|
||||
text: str = func.SourceField()
|
||||
vector: list[float] = func.VectorField()
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", schema=Document)
|
||||
table.add([{"text": "distractor"}, {"text": "matching document"}])
|
||||
reopened = lancedb.connect(tmp_path).open_table("docs")
|
||||
assert reopened.schema.field("vector").type.list_size == 256
|
||||
metadata = reopened.schema.metadata[b"embedding_functions"]
|
||||
assert b"test-foundry-key" not in metadata
|
||||
assert json.loads(metadata) == [
|
||||
{
|
||||
"name": "cohere",
|
||||
"model": options,
|
||||
"source_column": "text",
|
||||
"vector_column": "vector",
|
||||
}
|
||||
]
|
||||
assert reopened.search("matching query").limit(1).to_list()[0]["text"] == (
|
||||
"matching document"
|
||||
)
|
||||
assert (
|
||||
request_timeouts
|
||||
== [{"connect": 300, "read": 300, "write": 300, "pool": 300}] * 2
|
||||
)
|
||||
|
||||
# A fresh interpreter has the key but must separately trust the stored URL.
|
||||
child = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
import lancedb
|
||||
from lancedb.embeddings import UntrustedEmbeddingConfigError, get_registry
|
||||
|
||||
registry = get_registry()
|
||||
registry.set_var("foundry-key", os.environ["TEST_FOUNDRY_COHERE_KEY"])
|
||||
db = lancedb.connect(sys.argv[1])
|
||||
try:
|
||||
db.open_table("docs").search("matching query").limit(1).to_list()
|
||||
except UntrustedEmbeddingConfigError as error:
|
||||
assert sys.argv[2] in str(error)
|
||||
else:
|
||||
raise AssertionError("The stored endpoint needs explicit approval")
|
||||
registry.allow_endpoint(sys.argv[2])
|
||||
assert db.open_table("docs").search("matching query").limit(1).to_list()[0][
|
||||
"text"
|
||||
] == "matching document"
|
||||
""",
|
||||
str(tmp_path),
|
||||
options["base_url"],
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
assert child.returncode == 0, child.stderr
|
||||
assert requests == [
|
||||
(
|
||||
"/providers/cohere/v2/embed",
|
||||
"Bearer test-foundry-key",
|
||||
{
|
||||
"model": "my-embed-v4-deployment",
|
||||
"texts": texts,
|
||||
"input_type": input_type,
|
||||
"output_dimension": 256,
|
||||
"embedding_types": ["float"],
|
||||
},
|
||||
)
|
||||
for input_type, texts in [
|
||||
("search_document", ["distractor", "matching document"]),
|
||||
("search_query", ["matching query"]),
|
||||
("search_query", ["matching query"]),
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
def test_foundry_cohere_retries_only_failed_batch(foundry_cohere, monkeypatch):
|
||||
options, requests, statuses = foundry_cohere
|
||||
backoffs = []
|
||||
monkeypatch.setattr(
|
||||
"lancedb.embeddings.utils.time", SimpleNamespace(sleep=backoffs.append)
|
||||
)
|
||||
func = CohereEmbeddingFunction.create(**options, max_retries=1)
|
||||
texts = [f"document {index}" for index in range(96)] + ["matching document"]
|
||||
statuses["matching document"] = 429
|
||||
vectors = func.compute_source_embeddings_with_retry(texts)
|
||||
assert [body["texts"] for _, _, body in requests] == [
|
||||
texts[:96],
|
||||
texts[96:],
|
||||
texts[96:],
|
||||
]
|
||||
assert len(backoffs) == 1
|
||||
assert [vector[:2] for vector in vectors] == [[0.0, 1.0]] * 96 + [[1.0, 0.0]]
|
||||
|
||||
|
||||
def test_foundry_cohere_rejects_invalid_inputs_and_vectors(foundry_cohere, monkeypatch):
|
||||
options, requests, _ = foundry_cohere
|
||||
monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail)
|
||||
func = CohereEmbeddingFunction.create(**options)
|
||||
with pytest.raises(ValueError, match="unexpected dimension"):
|
||||
func.compute_query_embeddings_with_retry("wrong dimension")
|
||||
with pytest.raises(ValueError, match="requires string inputs"):
|
||||
func.compute_source_embeddings_with_retry([b"image"])
|
||||
assert len(requests) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_type", ["search_document", "search_query"], ids=["add", "search"]
|
||||
)
|
||||
def test_foundry_cohere_does_not_retry_or_follow_endpoint_redirect(
|
||||
foundry_cohere, monkeypatch, tmp_path, input_type
|
||||
):
|
||||
from cohere.core.api_error import ApiError
|
||||
|
||||
options, requests, statuses = foundry_cohere
|
||||
func = CohereEmbeddingFunction.create(**options, max_retries=2)
|
||||
|
||||
class Document(LanceModel):
|
||||
text: str = func.SourceField()
|
||||
vector: list[float] = func.VectorField()
|
||||
|
||||
table = lancedb.connect(tmp_path).create_table("docs", schema=Document)
|
||||
table.add([{"text": "seed", "vector": [0.0] * 256}])
|
||||
backoffs = []
|
||||
monkeypatch.setattr(
|
||||
"lancedb.embeddings.utils.time", SimpleNamespace(sleep=backoffs.append)
|
||||
)
|
||||
statuses["redirected text"] = 307
|
||||
|
||||
if input_type == "search_document":
|
||||
with pytest.raises(RuntimeError, match=r"ApiError:.*status_code: 307"):
|
||||
table.add([{"text": "redirected text"}])
|
||||
else:
|
||||
with pytest.raises(ApiError) as error:
|
||||
table.search("redirected text").limit(1).to_list()
|
||||
assert error.value.status_code == 307
|
||||
|
||||
assert backoffs == []
|
||||
assert [
|
||||
(path, body["input_type"], body["texts"]) for path, _, body in requests
|
||||
] == [("/providers/cohere/v2/embed", input_type, ["redirected text"])]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"overrides, message",
|
||||
[
|
||||
({"name": ""}, "deployed Cohere model"),
|
||||
({"output_dimension": None}, "requires output_dimension and api_key"),
|
||||
({"output_dimension": 0}, "greater than 0"),
|
||||
({"api_key": None}, "requires output_dimension and api_key"),
|
||||
({"api_key": "test-plaintext-key"}, "cannot be set to a hardcoded value"),
|
||||
({"api_key": "$var:foundry-key:test-plaintext-key"}, "without a default"),
|
||||
({"query_input_type": "classification"}, "search_query for queries"),
|
||||
({"base_url": None}, "require base_url"),
|
||||
({"base_url": "http://user:password@127.0.0.1"}, "without credentials"),
|
||||
],
|
||||
)
|
||||
def test_foundry_cohere_validates_config(monkeypatch, overrides, message):
|
||||
registry = get_registry()
|
||||
monkeypatch.setattr(registry, "_variables", {"foundry-key": "test-foundry-key"})
|
||||
options = {
|
||||
"name": "embed-v-4-0",
|
||||
"base_url": "http://127.0.0.1/providers/cohere",
|
||||
"output_dimension": 256,
|
||||
"api_key": "$var:foundry-key",
|
||||
}
|
||||
with pytest.raises(ValueError, match=message):
|
||||
registry.get("cohere").create(**(options | overrides))
|
||||
|
||||
|
||||
def test_cohere_legacy_metadata_and_v1_client(monkeypatch):
|
||||
requests = []
|
||||
|
||||
class LegacyClient:
|
||||
def __init__(self, key):
|
||||
assert key == "test-hosted-key"
|
||||
|
||||
def embed(self, **body):
|
||||
requests.append(body)
|
||||
return SimpleNamespace(embeddings=[[1.0, 2.0]])
|
||||
|
||||
monkeypatch.setitem(sys.modules, "cohere", SimpleNamespace(Client=LegacyClient))
|
||||
monkeypatch.setenv("COHERE_API_KEY", "test-hosted-key")
|
||||
monkeypatch.setattr(CohereEmbeddingFunction, "client", None)
|
||||
registry = get_registry()
|
||||
func = registry.get("cohere").create()
|
||||
assert func.ndims() == 1024
|
||||
assert func.safe_model_dump() == {}
|
||||
assert func.compute_source_embeddings(["default document"]) == [[1.0, 2.0]]
|
||||
|
||||
# This schema predates the custom endpoint parameters.
|
||||
stored = {
|
||||
"name": "cohere",
|
||||
"model": {"name": "embed-multilingual-v2.0", "query_input_type": "clustering"},
|
||||
"source_column": "text",
|
||||
"vector_column": "vector",
|
||||
}
|
||||
metadata = {b"embedding_functions": json.dumps([stored]).encode()}
|
||||
old_func = registry.parse_functions(metadata)["vector"].function
|
||||
assert old_func.ndims() == 768
|
||||
assert old_func.safe_model_dump() == stored["model"]
|
||||
assert old_func.compute_query_embeddings("legacy query") == [[1.0, 2.0]]
|
||||
assert requests == [
|
||||
{
|
||||
"texts": ["default document"],
|
||||
"model": "embed-multilingual-v3.0",
|
||||
"input_type": "search_document",
|
||||
},
|
||||
{
|
||||
"texts": ["legacy query"],
|
||||
"model": "embed-multilingual-v2.0",
|
||||
"input_type": "clustering",
|
||||
},
|
||||
]
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import contextlib
|
||||
import inspect
|
||||
import pickle
|
||||
import re
|
||||
import sys
|
||||
from datetime import timedelta
|
||||
@@ -69,6 +70,29 @@ def test_basic(tmp_path):
|
||||
assert db.open_table("test").name == db["test"].name
|
||||
|
||||
|
||||
def test_lance_db_connection_pickle_roundtrip(tmp_path):
|
||||
interval = timedelta(seconds=2)
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=interval)
|
||||
db.create_table("pickle_conn", pa.table({"id": [1, 2]}))
|
||||
|
||||
restored = pickle.loads(pickle.dumps(db))
|
||||
|
||||
assert restored.uri == str(tmp_path)
|
||||
assert restored.read_consistency_interval == interval
|
||||
assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2]
|
||||
|
||||
|
||||
def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
|
||||
table = db.create_table("pickle_zero", pa.table({"id": [1]}))
|
||||
|
||||
restored_db, restored_table = pickle.loads(pickle.dumps((db, table)))
|
||||
lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]}))
|
||||
|
||||
assert restored_db.read_consistency_interval == timedelta(0)
|
||||
assert restored_table.to_arrow()["id"].to_pylist() == [1, 2]
|
||||
|
||||
|
||||
def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch):
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
@@ -282,9 +306,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path):
|
||||
assert empty.page_token is None
|
||||
|
||||
|
||||
def test_db_contains_stops_after_matching_table_page(
|
||||
tmp_db: lancedb.DBConnection, monkeypatch
|
||||
):
|
||||
def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch):
|
||||
calls = []
|
||||
pages = {
|
||||
None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"),
|
||||
@@ -297,18 +319,44 @@ def test_db_contains_stops_after_matching_table_page(
|
||||
|
||||
monkeypatch.setattr(tmp_db, "list_tables", list_tables)
|
||||
|
||||
assert "table_1" in tmp_db
|
||||
assert calls == [None]
|
||||
|
||||
calls.clear()
|
||||
assert "table_2" in tmp_db
|
||||
assert calls == [None, "next"]
|
||||
|
||||
calls.clear()
|
||||
assert len(tmp_db) == 3
|
||||
assert calls == [None, "next"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]])
|
||||
async def test_local_table_exists_without_listing(
|
||||
tmp_path, monkeypatch, namespace_path
|
||||
):
|
||||
db = lancedb.connect(tmp_path)
|
||||
for depth in range(1, len(namespace_path) + 1):
|
||||
db.create_namespace(namespace_path[:depth])
|
||||
db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path)
|
||||
if not namespace_path:
|
||||
for idx in range(100):
|
||||
(tmp_path / f"a{idx:03}.lance").mkdir()
|
||||
assert "events" not in db.list_tables().tables
|
||||
adb = await lancedb.connect_async(tmp_path)
|
||||
|
||||
def fail_listing(*args, **kwargs):
|
||||
raise AssertionError("Existence checks must not list tables")
|
||||
|
||||
monkeypatch.setattr(db, "list_tables", fail_listing)
|
||||
monkeypatch.setattr(adb, "list_tables", fail_listing)
|
||||
table_id = namespace_path + ["events"]
|
||||
assert db.table_exists(table_id) is True
|
||||
assert await adb.table_exists(table_id) is True
|
||||
assert db.table_exists(namespace_path + ["missing"]) is False
|
||||
assert await adb.table_exists(namespace_path + ["missing"]) is False
|
||||
assert ("events" in db) is (not namespace_path)
|
||||
assert "missing" not in db
|
||||
assert table_id == namespace_path + ["events"]
|
||||
|
||||
db.drop_table("events", namespace_path=namespace_path)
|
||||
assert db.table_exists(table_id) is False
|
||||
assert await adb.table_exists(table_id) is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_table_names_async(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
@@ -821,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection):
|
||||
tmp_db.open_table("does_not_exist")
|
||||
|
||||
|
||||
def test_open_table_sync_with_location(tmp_path):
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
db.create_table("test", data=[{"id": 0}])
|
||||
dataset_path = tmp_path / "db" / "test.lance"
|
||||
|
||||
other_db = lancedb.connect(tmp_path / "other")
|
||||
opened = other_db.open_table("test", location=str(dataset_path))
|
||||
assert opened.name == "test"
|
||||
assert opened.count_rows() == 1
|
||||
|
||||
|
||||
def test_open_table_sync_lance_dataset_path_hint(tmp_path):
|
||||
data_dir = tmp_path / "data"
|
||||
lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}])
|
||||
dataset_db = lancedb.connect(data_dir / "embeddings.lance")
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
dataset_db.open_table("embeddings")
|
||||
message = str(exc_info.value)
|
||||
assert "Table 'embeddings' was not found" in message
|
||||
assert "points to a Lance dataset rather than a database directory" in message
|
||||
assert f"parent directory '{data_dir}'" in message
|
||||
assert "open table 'embeddings' instead" in message
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
dataset_db.open_table("missing", location=str(tmp_path / "missing.lance"))
|
||||
assert "points to a Lance dataset" not in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_table(tmp_path):
|
||||
from conftest import pandas_string_type
|
||||
@@ -908,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() == []
|
||||
@@ -924,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() == []
|
||||
|
||||
@@ -10,12 +10,140 @@ import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb import LanceDBConnection, udf
|
||||
from lancedb import LanceDBConnection, function
|
||||
from lancedb.compaction import CompactionResult
|
||||
from lancedb.index import FTS
|
||||
from lancedb.prewarm import PrewarmDataResult
|
||||
|
||||
# TODO: setup integ test mark and script
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def maintenance_connection_options():
|
||||
uri = os.environ.get("LANCEDB_URI")
|
||||
if not uri:
|
||||
pytest.skip(
|
||||
"Set LANCEDB_URI to a server supporting SQL maintenance job results"
|
||||
)
|
||||
assert uri.startswith("db://")
|
||||
return {
|
||||
"uri": uri,
|
||||
"api_key": os.environ.get("LANCEDB_API_KEY"),
|
||||
"region": os.environ.get("LANCEDB_REGION", "us-east-1"),
|
||||
"host_override": os.environ.get("LANCEDB_HOST_OVERRIDE"),
|
||||
"sql_host_override": os.environ.get("LANCEDB_SQL_HOST_OVERRIDE"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
@pytest.mark.parametrize("operation", ["compact", "prewarm", "prewarm_legacy"])
|
||||
async def test_maintenance_job_result_and_reopen_against_server(
|
||||
maintenance_connection_options, asynchronous, operation
|
||||
):
|
||||
"""Exercise real SQL receipts, workers and HTTP job results with matching versions.
|
||||
|
||||
Configure LANCEDB_URI, LANCEDB_API_KEY and the REST/Flight SQL endpoint
|
||||
overrides for a writable database. Workers must publish maintenance results;
|
||||
an unsupported server fails the contract rather than silently skipping it.
|
||||
"""
|
||||
if asynchronous:
|
||||
connection = await lancedb.connect_async(**maintenance_connection_options)
|
||||
else:
|
||||
connection = lancedb.connect(**maintenance_connection_options)
|
||||
|
||||
async def call(method, *args, **kwargs):
|
||||
result = method(*args, **kwargs)
|
||||
return await result if asynchronous else result
|
||||
|
||||
name = f"maintenance_{uuid4().hex}"
|
||||
created = False
|
||||
expected = [{"id": i, "payload": i * 10} for i in range(16)]
|
||||
timeout = timedelta(minutes=5)
|
||||
try:
|
||||
table = await call(
|
||||
connection.create_table, name, pa.Table.from_pylist(expected[:4])
|
||||
)
|
||||
created = True
|
||||
for start in (4, 8, 12):
|
||||
await call(table.add, pa.Table.from_pylist(expected[start : start + 4]))
|
||||
version = await table.version() if asynchronous else table.version
|
||||
if operation == "compact":
|
||||
job = await call(
|
||||
table.compact_async,
|
||||
compaction_options={
|
||||
"target_rows_per_fragment": 100,
|
||||
"batch_size": 128,
|
||||
"io_buffer_size": 0,
|
||||
},
|
||||
)
|
||||
elif operation == "prewarm_legacy":
|
||||
assert (
|
||||
await call(
|
||||
table.prewarm_data,
|
||||
["payload"],
|
||||
filter="id >= 8",
|
||||
concurrency=2,
|
||||
)
|
||||
is None
|
||||
)
|
||||
reader = await call(
|
||||
connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"'
|
||||
)
|
||||
batches = await call(reader.read_all)
|
||||
jobs = pa.Table.from_batches(batches) if asynchronous else batches
|
||||
ids = [
|
||||
row["job_id"]
|
||||
for row in jobs.to_pylist()
|
||||
if row["job_type"] == "prewarm_page_cache"
|
||||
]
|
||||
assert len(ids) == 1, jobs.to_pylist()
|
||||
job = await call(connection.open_job, ids[0])
|
||||
else:
|
||||
job = await call(
|
||||
table.prewarm_data_async,
|
||||
["payload"],
|
||||
filter="id >= 8",
|
||||
concurrency=2,
|
||||
)
|
||||
assert job.id()
|
||||
progress = []
|
||||
result = await call(job.wait, timeout=timeout, progress=progress.append)
|
||||
assert any(snapshot["state"] == "finished" for snapshot in progress)
|
||||
await call(job.refresh)
|
||||
assert await call(job.status) == "finished"
|
||||
if operation == "compact":
|
||||
assert isinstance(result, CompactionResult)
|
||||
assert job.job_type() == "compact"
|
||||
assert not result.partial_commit and result.rows_failed == 0
|
||||
assert result.completion_percentage == 100
|
||||
assert 0 <= result.rows_succeeded <= len(expected)
|
||||
assert result.files_added is not None and result.files_removed is not None
|
||||
else:
|
||||
assert isinstance(result, PrewarmDataResult)
|
||||
assert job.job_type() == "prewarm_page_cache"
|
||||
assert result.table_version == version == job.spec()["table_version"]
|
||||
assert job.spec()["columns"] == ["payload"]
|
||||
assert job.spec()["concurrency"] == 2
|
||||
assert result.fragments_selected > 0
|
||||
assert result.executors_completed == result.executors_targeted
|
||||
assert result.executors_partial == 0
|
||||
assert result.bytes_read is None and result.ranges_completed is None
|
||||
reopened = await call(connection.open_job, job.id())
|
||||
assert await call(reopened.wait, timeout=timeout) == result
|
||||
query = table.query() if asynchronous else table.search()
|
||||
actual = await call(
|
||||
query.select(["id", "payload"]).limit(len(expected) + 1).to_arrow
|
||||
)
|
||||
assert sorted(actual.to_pylist(), key=lambda row: row["id"]) == expected
|
||||
finally:
|
||||
try:
|
||||
if created:
|
||||
await call(connection.drop_table, name)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("LANCEDB_URI"), reason="Set LANCEDB_URI to a JSON FTS server"
|
||||
)
|
||||
@@ -98,7 +226,7 @@ def test_function_execution_controls_through_sql_and_materialized_view():
|
||||
view_name = f"batch_probe_view_{suffix}"
|
||||
registered_version = None
|
||||
|
||||
@udf(
|
||||
@function(
|
||||
name=function_name,
|
||||
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
output_schema=pa.int64(),
|
||||
@@ -180,3 +308,65 @@ def test_against_local_server():
|
||||
table = conn.open_table("sift1m_ivf1024_pq16")
|
||||
df = table.search(np.random.rand(128)).to_pandas()
|
||||
assert len(df) == 10
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_prewarm_preview_against_server(
|
||||
maintenance_connection_options, asynchronous
|
||||
):
|
||||
"""Preview is typed, source-versioned, and creates no maintenance jobs."""
|
||||
from lancedb.prewarm import PrewarmDataPlan
|
||||
|
||||
connection = (
|
||||
await lancedb.connect_async(**maintenance_connection_options)
|
||||
if asynchronous
|
||||
else lancedb.connect(**maintenance_connection_options)
|
||||
)
|
||||
|
||||
async def call(method, *args, **kwargs):
|
||||
result = method(*args, **kwargs)
|
||||
return await result if asynchronous else result
|
||||
|
||||
async def jobs():
|
||||
reader = await call(connection.execute_query, f'SHOW JOBS FOR TABLE "{name}"')
|
||||
result = await call(reader.read_all)
|
||||
if asynchronous:
|
||||
return [row for batch in result for row in batch.to_pylist()]
|
||||
return result.to_pylist()
|
||||
|
||||
name = f"preview_{uuid4().hex}"
|
||||
created = False
|
||||
try:
|
||||
table = await call(connection.create_table, name, [{"id": 1, "payload": "one"}])
|
||||
created = True
|
||||
version = await table.version() if asynchronous else table.version
|
||||
before = await jobs()
|
||||
for predicate, mode, selected in [
|
||||
(None, "unfiltered", 1),
|
||||
("TRUE", "full_warm_fallback", 1),
|
||||
("FALSE", "constant", 0),
|
||||
("id > 10", "full_warm_fallback", 1),
|
||||
]:
|
||||
preview = await call(
|
||||
table.explain_prewarm_data, ["payload"], filter=predicate, concurrency=2
|
||||
)
|
||||
assert isinstance(preview, PrewarmDataPlan)
|
||||
assert preview.table_version == version
|
||||
assert preview.pruning.mode == mode
|
||||
assert preview.pruning.input_fragments == 1
|
||||
assert preview.pruning.selected_fragments == selected
|
||||
if mode == "full_warm_fallback":
|
||||
assert preview.pruning.fallback_reason
|
||||
assert await jobs() == before
|
||||
assert (await table.version() if asynchronous else table.version) == version
|
||||
# A preview does not reserve the source snapshot for a later request.
|
||||
await call(table.add, [{"id": 2, "payload": "two"}])
|
||||
newer = await call(table.explain_prewarm_data)
|
||||
assert newer.table_version > version
|
||||
assert newer.pruning.input_fragments == 2
|
||||
assert await jobs() == before
|
||||
finally:
|
||||
if created:
|
||||
await call(connection.drop_table, name)
|
||||
connection.close()
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_to_reader_collects_without_default_slicing(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
rows = 5000
|
||||
data = pa.table(
|
||||
{
|
||||
"id": pa.array(range(rows), type=pa.int64()),
|
||||
"text": pa.array([f"row-{i}" for i in range(rows)]),
|
||||
}
|
||||
)
|
||||
table = await db.create_table("test", data)
|
||||
|
||||
reader = await table._inner.query().execute_to_reader(None, None)
|
||||
batches = list(reader)
|
||||
|
||||
assert sum(batch.num_rows for batch in batches) == rows
|
||||
assert max(batch.num_rows for batch in batches) > 1024
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_to_reader_preserves_empty_schema(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
data = pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2], type=pa.int64()),
|
||||
"text": pa.array(["a", "b"]),
|
||||
}
|
||||
)
|
||||
table = await db.create_table("test", data)
|
||||
|
||||
query = table._inner.query()
|
||||
query.where("id < 0")
|
||||
reader = await query.execute_to_reader(None, None)
|
||||
result = pa.Table.from_batches(reader, schema=reader.schema)
|
||||
|
||||
assert result.num_rows == 0
|
||||
assert result.schema == await table.query().where("id < 0").output_schema()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_to_reader_propagates_timeout(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", data=[{"id": 1}, {"id": 2}])
|
||||
|
||||
with pytest.raises(Exception, match="Query timeout"):
|
||||
await table._inner.query().execute_to_reader(None, timedelta(0))
|
||||
@@ -31,11 +31,15 @@ Parameters used throughout:
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import functools
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
import threading
|
||||
from unittest.mock import patch
|
||||
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from utils import (
|
||||
@@ -1028,6 +1032,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 ─────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -1079,6 +1182,74 @@ def test_streaming_dataloader_commits_only_consumed_worker_batches(tmp_path):
|
||||
assert remaining == uninterrupted == [[3, 4], [30, 40]]
|
||||
|
||||
|
||||
def test_block_size_dataloader_workers_reconnect(tmp_path):
|
||||
"""Block-mode datasets pickle with no permutation table and reopen per worker."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("block_workers", pa.table({"id": list(range(8))}))
|
||||
dataset = StreamingDataset(
|
||||
table,
|
||||
num_splits=2,
|
||||
shuffle=False,
|
||||
block_size=2,
|
||||
)
|
||||
loader = StreamingDataLoader(
|
||||
dataset,
|
||||
batch_size=2,
|
||||
num_workers=2,
|
||||
multiprocessing_context="spawn",
|
||||
)
|
||||
iterator = iter(loader)
|
||||
try:
|
||||
batches = [batch["id"].tolist() for batch in iterator]
|
||||
finally:
|
||||
iterator._shutdown_workers()
|
||||
|
||||
assert sorted(row for batch in batches for row in batch) == list(range(8))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filter", [None, "id % 2 = 0"])
|
||||
@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False])
|
||||
def test_block_size_pickle_does_not_grow_with_block_count(
|
||||
tmp_path, reshuffle_blocks_per_epoch, filter
|
||||
):
|
||||
"""Spawned workers start serially once the pickle outgrows a pipe buffer."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("block_pickle", pa.table({"id": list(range(1 << 16))}))
|
||||
|
||||
def make(block_size):
|
||||
return StreamingDataset(
|
||||
table,
|
||||
num_splits=2,
|
||||
shuffle_seed=7,
|
||||
epoch=3,
|
||||
block_size=block_size,
|
||||
reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch,
|
||||
filter=filter,
|
||||
)
|
||||
|
||||
def pickled_state(dataset):
|
||||
# The fixed-size shared-memory counters only pickle while spawning a
|
||||
# child, and their size does not depend on the block count.
|
||||
state = dataset.__getstate__()
|
||||
for key in ("_worker_stats", "_untracked_worker_iteration", "_filled_count"):
|
||||
del state[key]
|
||||
return pickle.dumps(state)
|
||||
|
||||
few_blocks, many_blocks = make(1 << 12), make(4)
|
||||
few_size = len(pickled_state(few_blocks))
|
||||
many_size = len(pickled_state(many_blocks))
|
||||
assert many_size - few_size < 1024, (few_size, many_size)
|
||||
# A filter's per-live-row offsets must not ride along either.
|
||||
assert many_size < 64 * 1024, many_size
|
||||
|
||||
restored = StreamingDataset.__new__(StreamingDataset)
|
||||
restored.__setstate__(pickle.loads(pickled_state(many_blocks)))
|
||||
assert restored._block_perm == many_blocks._block_perm
|
||||
assert restored._block_perm != sorted(restored._block_perm)
|
||||
if filter is not None:
|
||||
np.testing.assert_array_equal(restored._live_offsets, many_blocks._live_offsets)
|
||||
|
||||
|
||||
def test_distributed_checkpoint_uses_rank_local_worker_boundary(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("rank_boundary", pa.table({"id": list(range(8))}))
|
||||
@@ -2993,6 +3164,36 @@ def _packed_dataset(table, pack_sequences, *, blocks_per_epoch, pad_id=0, **kwar
|
||||
)
|
||||
|
||||
|
||||
def test_pack_sequences_checkpoint_with_block_size(tmp_path):
|
||||
table = _create_token_table(
|
||||
tmp_path,
|
||||
[[1], [2], [10, 11, 12, 13, 14, 15, 16, 17], [20]],
|
||||
)
|
||||
kwargs = dict(
|
||||
pack_sequences=5,
|
||||
blocks_per_epoch=4,
|
||||
num_splits=2,
|
||||
block_size=2,
|
||||
)
|
||||
reference = [
|
||||
block["input_ids"].tolist() for block in _packed_dataset(table, **kwargs)
|
||||
]
|
||||
|
||||
dataset = _packed_dataset(table, **kwargs)
|
||||
iterator = iter(dataset)
|
||||
first_cycle = [next(iterator), next(iterator)]
|
||||
checkpoint = dataset.state_dict()
|
||||
iterator.close()
|
||||
|
||||
resumed = _packed_dataset(table, **kwargs)
|
||||
resumed.load_state_dict(checkpoint)
|
||||
remaining = [block["input_ids"].tolist() for block in resumed]
|
||||
|
||||
assert [block["input_ids"].tolist() for block in first_cycle] == reference[:2]
|
||||
assert checkpoint["blocks_emitted_per_split"] == [1, 1]
|
||||
assert remaining == reference[2:]
|
||||
|
||||
|
||||
def test_pack_sequences_emits_blocks_and_pads_final_tail(tmp_path):
|
||||
table = _create_token_table(tmp_path, [[1, 2], [3, 4], [5]])
|
||||
dataset = _packed_dataset(table, 6, blocks_per_epoch=2)
|
||||
@@ -3472,6 +3673,732 @@ def test_streaming_dataset_over_remote_table():
|
||||
assert_server_safe_row_id_requests(server)
|
||||
|
||||
|
||||
class _ReorderingOffsetScanServer(MockPermutationServer):
|
||||
"""Answers offset/limit pages as if the table's two fragments complete in a
|
||||
different order on each request, which remote scans are allowed to do."""
|
||||
|
||||
def _query(self, request, body):
|
||||
if "offset" in body and not body.get("filter"):
|
||||
rows = list(range(self.num_rows))
|
||||
half = self.num_rows // 2
|
||||
if body["offset"] >= half:
|
||||
rows = rows[half:] + rows[:half]
|
||||
start = body["offset"]
|
||||
return self._arrow(
|
||||
request, pa.table({"id": rows[start : start + body["k"]]})
|
||||
)
|
||||
return super()._query(request, body)
|
||||
|
||||
|
||||
def test_two_phase_over_remote_table():
|
||||
"""Unfiltered 2-phase reads of a remote table name each block's rows by
|
||||
_rowoffset: offset/limit pages have no cross-request order guarantee."""
|
||||
server = _ReorderingOffsetScanServer(num_rows=16)
|
||||
|
||||
with mock_remote_table(server) as table:
|
||||
ds = StreamingDataset(table, num_splits=2, block_size=4, shuffle=False)
|
||||
ids = [row["id"] for row in ds]
|
||||
|
||||
assert sorted(ids) == list(range(server.num_rows)), (
|
||||
"Every row of the remote table must be yielded exactly once"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_over_remote_table_filtered_and_shuffled():
|
||||
"""2-phase's filtered live-offset precompute and take_offsets-based
|
||||
block reads both work against a remote table, including restoring
|
||||
take_offsets' unspecified order via the _rowoffset it also selects."""
|
||||
server = MockPermutationServer(num_rows=20)
|
||||
live_ids = list(range(16)) # 16 live rows -> 4 blocks, divides num_splits=2
|
||||
|
||||
with mock_remote_table(server) as table:
|
||||
ds = StreamingDataset(
|
||||
table,
|
||||
num_splits=2,
|
||||
block_size=4,
|
||||
shuffle=True,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
filter="id IN (" + ",".join(str(i) for i in live_ids) + ")",
|
||||
columns=["id"],
|
||||
)
|
||||
ids = [row["id"] for row in ds]
|
||||
|
||||
assert sorted(ids) == live_ids, "only live rows, each exactly once"
|
||||
|
||||
|
||||
def test_two_phase_over_remote_table_does_not_pin_callers_handle():
|
||||
"""_open_pinned_table() must not mutate the caller's own RemoteTable.
|
||||
|
||||
Without a connection_factory, the reopen helpers used for local/memory
|
||||
tables return the *same* RemoteTable object for the remote case (correct
|
||||
for their original cross-process pickling purpose, wrong for same-process
|
||||
reuse here). Checking that object out to the block-mode pin would
|
||||
therefore pin -- and, since checkout_version != None marks a handle
|
||||
version-pinned -- effectively make read-only the caller's own live table,
|
||||
not an unrelated copy.
|
||||
"""
|
||||
server = MockPermutationServer(num_rows=8)
|
||||
|
||||
with mock_remote_table(server) as table:
|
||||
assert table._checkout_version is None, "caller's table starts unpinned"
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
list(ds) # drive at least one _open_pinned_table() call
|
||||
assert table._checkout_version is None, (
|
||||
"iterating a 2-phase dataset must not pin the caller's own "
|
||||
"table handle to a fixed version"
|
||||
)
|
||||
|
||||
|
||||
@functools.lru_cache
|
||||
def _cached_open_table(uri, name):
|
||||
return lancedb.connect(uri).open_table(name)
|
||||
|
||||
|
||||
@functools.lru_cache
|
||||
def _cached_open_table_with_session(uri, name):
|
||||
return lancedb.connect(uri, session=lancedb.Session()).open_table(name)
|
||||
|
||||
|
||||
class _ReturnsTable:
|
||||
def __init__(self, table):
|
||||
self.table = table
|
||||
|
||||
def __call__(self, name):
|
||||
return self.table
|
||||
|
||||
|
||||
@pytest.mark.parametrize("connection", ["local", "session", "memory"])
|
||||
def test_two_phase_does_not_pin_cached_factory_handle(tmp_path, connection):
|
||||
"""A connection_factory may return a cached, caller-owned handle: pinning
|
||||
the dataset's snapshot must leave that handle writable, must not need a
|
||||
picklable connection, and must keep reading the construction snapshot
|
||||
after the handle's table changes."""
|
||||
if connection == "memory":
|
||||
table = lancedb.connect("memory://").create_table(
|
||||
"t", pa.table({"id": list(range(8))})
|
||||
)
|
||||
table.add(pa.table({"id": [100]}))
|
||||
table.delete("id = 100") # the snapshot is at a version above 1
|
||||
factory = _ReturnsTable(table)
|
||||
else:
|
||||
lancedb.connect(tmp_path).create_table("t", pa.table({"id": list(range(8))}))
|
||||
open_table = (
|
||||
_cached_open_table_with_session
|
||||
if connection == "session"
|
||||
else _cached_open_table
|
||||
)
|
||||
factory = functools.partial(open_table, str(tmp_path))
|
||||
table = factory("t")
|
||||
|
||||
ds = StreamingDataset(
|
||||
table, block_size=4, shuffle=False, connection_factory=factory
|
||||
)
|
||||
table.delete("id = 0")
|
||||
table.add(pa.table({"id": [8]}))
|
||||
|
||||
assert table.count_rows() == 8
|
||||
assert [row["id"] for row in ds] == list(range(8))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2-phase shuffled reads (block_size)
|
||||
# ---------------------------------------------------------------------------
|
||||
# block_size switches StreamingDataset from 1-phase (per-row permutation) to
|
||||
# 2-phase (block-granularity shuffle + a row-level shuffle bounded by
|
||||
# max_shuffle_distance). NUM_ROWS=120 with block_size=10 gives 12 blocks,
|
||||
# which divides NUM_SPLITS=12 evenly, so most tests below reuse lance_table
|
||||
# and those constants without the runt blocks and mid-block split boundaries
|
||||
# covered explicitly by their own tests.
|
||||
|
||||
|
||||
def test_two_phase_full_coverage_no_duplicates(lance_table):
|
||||
"""Every sample ID appears exactly once across a full 2-phase epoch."""
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=10,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert len(ids) == NUM_ROWS
|
||||
assert sorted(ids) == list(range(NUM_ROWS)), "every row must appear exactly once"
|
||||
|
||||
|
||||
def test_two_phase_reads_runt_block(lance_table):
|
||||
"""A trailing partial block (block_size doesn't evenly divide the row
|
||||
count) is read like any other block."""
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=13, # NUM_ROWS=120 -> 9 full blocks and a 3-row runt
|
||||
shuffle=False,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(NUM_ROWS))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"block_size,num_splits,filter",
|
||||
[
|
||||
# 12 blocks over 5 splits: split boundaries fall mid-block.
|
||||
pytest.param(10, 5, None, id="whole_blocks_uneven_splits"),
|
||||
# 9 full blocks plus a 3-row runt over 7 splits: 120 // 7 = 17 rows
|
||||
# per split, so exactly 1 row is dropped.
|
||||
pytest.param(13, 7, None, id="runt_and_uneven_splits"),
|
||||
# 60 live rows in 9 blocks of 7 (the last a 4-row runt) over 4 splits.
|
||||
pytest.param(7, 4, "id % 2 = 0", id="filtered"),
|
||||
],
|
||||
)
|
||||
def test_two_phase_drops_fewer_rows_than_splits(
|
||||
lance_table, block_size, num_splits, filter, reshuffle_blocks_per_epoch
|
||||
):
|
||||
"""Splits are cut by rows, not whole blocks, so each epoch drops fewer than
|
||||
num_splits rows (as 1-phase does) and every split serves the same count."""
|
||||
live_ids = set(range(NUM_ROWS)) if filter is None else set(range(0, NUM_ROWS, 2))
|
||||
rows_per_split = len(live_ids) // num_splits
|
||||
for epoch in range(2):
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=num_splits,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
epoch=epoch,
|
||||
block_size=block_size,
|
||||
filter=filter,
|
||||
reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch,
|
||||
)
|
||||
for split in range(num_splits):
|
||||
assert sum(b.stop - b.start for b in ds._split_blocks(split)) == (
|
||||
rows_per_split
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert len(ids) == len(set(ids)) == rows_per_split * num_splits
|
||||
assert set(ids) <= live_ids
|
||||
assert len(live_ids) - len(ids) < num_splits
|
||||
|
||||
|
||||
def test_two_phase_no_shuffle_preserves_order(lance_table):
|
||||
"""shuffle=False yields rows in exact original storage order."""
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=10,
|
||||
shuffle=False,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(NUM_ROWS)), (
|
||||
"shuffle=False must preserve original row order block-by-block"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_respects_max_shuffle_distance(lance_table):
|
||||
"""No row moves farther than max_shuffle_distance from its natural
|
||||
(block, then row) position within its split's own block assignment.
|
||||
|
||||
White-box: reconstructs the expected natural-rank order directly from
|
||||
ds._block_perm (the shuffled block order), since that's the reference
|
||||
frame the displacement bound is defined against, not raw table order.
|
||||
"""
|
||||
block_size = 10 # NUM_ROWS=120 -> 12 blocks
|
||||
max_shuffle_distance = 25
|
||||
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
max_shuffle_distance=max_shuffle_distance,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
|
||||
natural_order = [
|
||||
row_id
|
||||
for bp in ds._block_perm
|
||||
for row_id in range(bp * block_size, (bp + 1) * block_size)
|
||||
]
|
||||
assert sorted(ids) == list(range(NUM_ROWS))
|
||||
assert sorted(natural_order) == list(range(NUM_ROWS))
|
||||
|
||||
natural_rank = {row_id: rank for rank, row_id in enumerate(natural_order)}
|
||||
for output_pos, row_id in enumerate(ids):
|
||||
displacement = abs(output_pos - natural_rank[row_id])
|
||||
assert displacement < max_shuffle_distance, (
|
||||
f"row {row_id} displaced {displacement} positions from its natural "
|
||||
f"rank, exceeding max_shuffle_distance={max_shuffle_distance}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs,expected_window,expected_distance",
|
||||
[
|
||||
pytest.param({}, 8, 80, id="defaults"),
|
||||
pytest.param({"window_blocks": 2}, 2, 20, id="window_override"),
|
||||
pytest.param({"max_shuffle_distance": 15}, 8, 15, id="distance_override"),
|
||||
],
|
||||
)
|
||||
def test_two_phase_window_defaults(
|
||||
lance_table, kwargs, expected_window, expected_distance
|
||||
):
|
||||
ds = StreamingDataset(
|
||||
lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10, **kwargs
|
||||
)
|
||||
assert ds._window_blocks == expected_window
|
||||
assert ds._max_shuffle_distance == expected_distance
|
||||
|
||||
|
||||
def test_two_phase_filter_counts_live_rows(tmp_path):
|
||||
"""block_size counts only rows passing filter; dead rows never appear."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"t",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(NUM_ROWS)),
|
||||
"category": ["train"] * 60 + ["val"] * 60,
|
||||
}
|
||||
),
|
||||
)
|
||||
ds = StreamingDataset(
|
||||
table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=10, # 60 live (train) rows -> 6 blocks exactly, no runt
|
||||
filter="category = 'train'",
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert all(i < 60 for i in ids), "only live (train) rows should appear"
|
||||
assert sorted(ids) == list(range(60))
|
||||
|
||||
|
||||
def test_two_phase_resume_checkpoint_round_trip(lance_table):
|
||||
"""state_dict/load_state_dict resumes a 2-phase dataset without gaps or
|
||||
repeats, the same guarantee test_doc_example_checkpoint verifies for
|
||||
1-phase."""
|
||||
steps_before_checkpoint = 5
|
||||
block_size = 10 # NUM_ROWS=120 -> 12 blocks, divides NUM_SPLITS=12 evenly
|
||||
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
)
|
||||
it = iter(ds)
|
||||
consumed = [next(it)["id"] for _ in range(steps_before_checkpoint * NUM_SPLITS)]
|
||||
checkpoint = ds.state_dict()
|
||||
remaining_original = [s["id"] for s in it]
|
||||
|
||||
ds_resumed = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
)
|
||||
ds_resumed.load_state_dict(checkpoint)
|
||||
remaining_resumed = [s["id"] for s in ds_resumed]
|
||||
|
||||
assert remaining_original == remaining_resumed, (
|
||||
"Resumed 2-phase dataset must continue from exactly the same position"
|
||||
)
|
||||
assert sorted(consumed + remaining_original) == list(range(NUM_ROWS)), (
|
||||
"Consumed + remaining must cover every row exactly once"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"saved,resumed,mismatched_key",
|
||||
[
|
||||
pytest.param(
|
||||
{"block_size": 10}, {"block_size": 5}, "block_size", id="block_size"
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10}, {}, "block_size", id="two_phase_into_one_phase"
|
||||
),
|
||||
pytest.param(
|
||||
{}, {"block_size": 10}, "block_size", id="one_phase_into_two_phase"
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10},
|
||||
{"block_size": 10, "max_shuffle_distance": 15},
|
||||
"max_shuffle_distance",
|
||||
id="max_shuffle_distance",
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10},
|
||||
{"block_size": 10, "reshuffle_blocks_per_epoch": False},
|
||||
"reshuffle_blocks_per_epoch",
|
||||
id="reshuffle_blocks_per_epoch",
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10},
|
||||
{"block_size": 10, "shuffle": False},
|
||||
"shuffle",
|
||||
id="shuffle",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_two_phase_checkpoint_rejects_different_read_order(
|
||||
lance_table, saved, resumed, mismatched_key
|
||||
):
|
||||
"""Saved positions index one 2-phase read order; resuming them under
|
||||
another would replay consumed rows and skip unread ones. The error names
|
||||
the setting to change."""
|
||||
|
||||
def make(options):
|
||||
return StreamingDataset(
|
||||
lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED, **options
|
||||
)
|
||||
|
||||
source = make(saved)
|
||||
it = iter(source)
|
||||
for _ in range(2 * NUM_SPLITS):
|
||||
next(it)
|
||||
checkpoint = source.state_dict()
|
||||
|
||||
with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch: checkpoint"):
|
||||
make(resumed).load_state_dict(checkpoint)
|
||||
with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch across"):
|
||||
StreamingDataset.merge_state_dicts([checkpoint, make(resumed).state_dict()])
|
||||
|
||||
|
||||
def test_two_phase_failed_reader_build_closes_built_readers(lance_table, monkeypatch):
|
||||
"""A resume position past a split's end fails while building readers; the
|
||||
readers built before it must still release their prefetch executors."""
|
||||
ds = StreamingDataset(
|
||||
lance_table, num_splits=2, shuffle_seed=SHUFFLE_SEED, block_size=10
|
||||
)
|
||||
checkpoint = ds.state_dict()
|
||||
checkpoint["positions_consumed_per_split"] = [0, NUM_ROWS]
|
||||
ds.load_state_dict(checkpoint)
|
||||
|
||||
closed = []
|
||||
close = streaming._TwoPhaseSplitReader.close
|
||||
|
||||
def counting_close(reader):
|
||||
closed.append(reader)
|
||||
close(reader)
|
||||
|
||||
monkeypatch.setattr(streaming._TwoPhaseSplitReader, "close", counting_close)
|
||||
with pytest.raises(ValueError, match="out of range"):
|
||||
list(ds)
|
||||
assert len(closed) == 1
|
||||
|
||||
|
||||
def test_two_phase_pinned_version_survives_concurrent_write(tmp_path):
|
||||
"""The block plan is pinned to the table version at construction; a
|
||||
write between construction and iteration must not change what an
|
||||
in-progress epoch reads."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", pa.table({"id": list(range(8))}))
|
||||
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
table.delete("id = 0") # mutate after construction, before iteration
|
||||
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(8)), (
|
||||
"must read the version pinned at construction, not the live, since-mutated one"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_pinned_memory_table_survives_concurrent_write():
|
||||
"""Same guarantee as the on-disk test above, but for a memory:// table.
|
||||
|
||||
A memory table's "pickle state" is its row data (to_arrow()), not just
|
||||
reopen coordinates, so it must be captured once at construction -- not
|
||||
recomputed from the live table on every _open_pinned_table() call --
|
||||
or a write made after construction would leak into every later read.
|
||||
"""
|
||||
db = lancedb.connect("memory://")
|
||||
table = db.create_table("t", pa.table({"id": list(range(8))}))
|
||||
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
table.delete("id = 0")
|
||||
table.add(pa.table({"id": [8]}))
|
||||
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(8)), (
|
||||
"must read the snapshot captured at construction, not the live, "
|
||||
"since-mutated one"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_memory_table_already_at_a_later_version():
|
||||
"""Constructing over a memory table already past version 1 must not
|
||||
fail: the pin is the snapshot's data, not a version number to replay
|
||||
against a freshly rebuilt (always version-1) in-memory table."""
|
||||
db = lancedb.connect("memory://")
|
||||
table = db.create_table("t", pa.table({"id": list(range(4))}))
|
||||
table.add(pa.table({"id": [4, 5, 6, 7]})) # now at version 2, 8 live rows
|
||||
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert sorted(ids) == list(range(8))
|
||||
|
||||
|
||||
def test_two_phase_reader_plan_arrays_are_int32(lance_table):
|
||||
"""_plan_block_pos/_plan_local_offset are retained for the reader's
|
||||
whole lifetime, one entry per row in the entire split (the open
|
||||
whole-split-memory review thread) -- so their dtype is a real, constant
|
||||
memory-footprint decision, not an implementation detail. Pinned here at
|
||||
int32 (half of int64) so a future change can't silently regress it."""
|
||||
ds = StreamingDataset(
|
||||
lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10
|
||||
)
|
||||
reader = ds._make_two_phase_reader(0, ds._open_pinned_table(), None)
|
||||
assert reader._plan_block_pos.dtype == np.int32
|
||||
assert reader._plan_local_offset.dtype == np.int32
|
||||
# Values must still be correct, not just narrower -- e.g. a block index
|
||||
# silently wrapping around int32 would be a far worse regression than
|
||||
# the memory this dtype choice saves.
|
||||
assert reader._plan_block_pos.max() < len(ds._split_blocks(0))
|
||||
assert reader._plan_local_offset.max() < 10 # block_size
|
||||
|
||||
|
||||
class _LookupCountingDict(dict):
|
||||
def __init__(self, *args):
|
||||
super().__init__(*args)
|
||||
self.lookups = 0
|
||||
|
||||
def __getitem__(self, key):
|
||||
self.lookups += 1
|
||||
return super().__getitem__(key)
|
||||
|
||||
def get(self, key, default=None):
|
||||
self.lookups += 1
|
||||
return super().get(key, default)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"skip,swap_calls",
|
||||
[
|
||||
pytest.param(0, False, id="fresh"),
|
||||
pytest.param(1500, False, id="resumed"),
|
||||
# io_queue_depth lets calls take the reader's lock out of order.
|
||||
pytest.param(0, True, id="out_of_order"),
|
||||
],
|
||||
)
|
||||
def test_two_phase_reader_sequential_read_is_linear_in_blocks(skip, swap_calls):
|
||||
"""A sequential read must fetch each block once and keep per-call
|
||||
bookkeeping bounded by the resident window, not by how many blocks the
|
||||
split has already passed -- otherwise prefetch cost grows quadratically
|
||||
with split size."""
|
||||
num_blocks, block_size, batch = 400, 8, 8
|
||||
block_ids = list(range(1000, 1000 + num_blocks))
|
||||
reads = []
|
||||
|
||||
def read_block(block_id):
|
||||
reads.append(block_id)
|
||||
# Two record batches per block, as a multi-batch scan returns.
|
||||
half = block_size // 2
|
||||
return pa.concat_tables(
|
||||
pa.table({"block": [block_id] * half, "row": range(lo, lo + half)})
|
||||
for lo in (0, half)
|
||||
)
|
||||
|
||||
reader = streaming._TwoPhaseSplitReader(
|
||||
block_ids=block_ids,
|
||||
block_live_counts=[block_size] * num_blocks,
|
||||
shuffle=True,
|
||||
max_shuffle_distance=4 * block_size,
|
||||
seed=SHUFFLE_SEED,
|
||||
read_block_fn=read_block,
|
||||
columns=None,
|
||||
skip=skip,
|
||||
prefetch_depth=2,
|
||||
)
|
||||
try:
|
||||
# Later positions overwrite earlier ones, leaving each block's last.
|
||||
expected_last_pos = {
|
||||
bp: pos for pos, bp in enumerate(reader._plan_block_pos.tolist())
|
||||
}
|
||||
assert reader._block_last_pos == expected_last_pos
|
||||
|
||||
reader._block_last_pos = _LookupCountingDict(reader._block_last_pos)
|
||||
starts = list(range(0, reader.num_rows, batch))
|
||||
if swap_calls:
|
||||
starts[0::2], starts[1::2] = starts[1::2], starts[0::2]
|
||||
outputs = {}
|
||||
for start in starts:
|
||||
out = reader.__getitems__(range(start, min(start + batch, reader.num_rows)))
|
||||
outputs[start] = list(
|
||||
zip(out.column("block").to_pylist(), out.column("row").to_pylist())
|
||||
)
|
||||
assert all(
|
||||
t.column("block").num_chunks == 1 for t in reader._loaded.values()
|
||||
)
|
||||
rows = [row for start in sorted(outputs) for row in outputs[start]]
|
||||
num_calls = len(starts)
|
||||
finally:
|
||||
reader.close()
|
||||
|
||||
expected_rows = [
|
||||
(block_ids[bp], off)
|
||||
for bp, off in zip(
|
||||
reader._plan_block_pos.tolist(), reader._plan_local_offset.tolist()
|
||||
)
|
||||
]
|
||||
assert rows == expected_rows
|
||||
if skip == 0:
|
||||
assert sorted(rows) == [
|
||||
(bid, off) for bid in block_ids for off in range(block_size)
|
||||
]
|
||||
needed_blocks = {block_ids[bp] for bp in expected_last_pos}
|
||||
assert sorted(reads) == sorted(needed_blocks)
|
||||
# Rescanning every already-passed block on each prefetch top-up grows
|
||||
# quadratically (~29k lookups fresh here); a bounded walk stays linear
|
||||
# (~2k).
|
||||
assert reader._block_last_pos.lookups < 10 * (num_calls + num_blocks)
|
||||
|
||||
|
||||
def test_two_phase_auto_blocks_per_epoch_reads_only_sampled_blocks(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
"""blocks_per_epoch='auto' must sample whole blocks: a scattered row
|
||||
sample touches nearly every block and so reads the whole token column."""
|
||||
table = _create_token_table(tmp_path, [[1, 2, 3]] * 1000)
|
||||
reads = []
|
||||
read_block = StreamingDataset._read_block
|
||||
|
||||
def counting_read_block(self, pinned_table, block, columns):
|
||||
reads.append(block)
|
||||
return read_block(self, pinned_table, block, columns)
|
||||
|
||||
monkeypatch.setattr(StreamingDataset, "_read_block", counting_read_block)
|
||||
with pytest.warns(UserWarning, match="approximate token-count sample"):
|
||||
dataset = _packed_dataset(
|
||||
table, 4, blocks_per_epoch="auto", num_splits=2, block_size=10
|
||||
)
|
||||
|
||||
# 1% of each 500-row split rounds up to a single 10-row block per split.
|
||||
assert len(reads) == 2
|
||||
assert reads[0] in dataset._split_blocks(0)
|
||||
assert reads[1] in dataset._split_blocks(1)
|
||||
# Every document is 3 tokens plus EOS, so the sample is exact: 4000 / 4.
|
||||
assert dataset.state_dict()["blocks_per_epoch"] == 1000
|
||||
|
||||
|
||||
def test_two_phase_rejects_rte_write_spec_table(tmp_path):
|
||||
"""An RTE write spec means some acknowledged writes live only in the
|
||||
MemWAL, invisible to a version-pinned read; block_size must refuse the
|
||||
table at construction rather than silently reading stale base-table
|
||||
values (mirroring the row-id rejection 1-phase already applies)."""
|
||||
from lancedb import RTEWriteSpec
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64(), nullable=False),
|
||||
pa.field("value", pa.int64(), nullable=False),
|
||||
]
|
||||
)
|
||||
table = db.create_table(
|
||||
"t",
|
||||
pa.Table.from_pydict({"id": list(range(8)), "value": [0] * 8}, schema=schema),
|
||||
)
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 1))
|
||||
table.merge_insert(
|
||||
"id"
|
||||
).when_matched_update_all().when_not_matched_insert_all().execute(
|
||||
pa.Table.from_pydict({"id": list(range(8)), "value": [99] * 8}, schema=schema)
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="RTE write spec"):
|
||||
StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
|
||||
|
||||
def test_two_phase_rejects_fingerprinted_checkpoint(lance_table):
|
||||
"""A checkpoint tied to a split_strategy permutation cannot resume block mode."""
|
||||
source = StreamingDataset(
|
||||
lance_table,
|
||||
split_strategy=lambda b: b.bootstrap_sample(
|
||||
2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED
|
||||
),
|
||||
num_splits=NUM_SPLITS,
|
||||
)
|
||||
checkpoint = source.state_dict()
|
||||
assert "perm_fingerprint" in checkpoint
|
||||
|
||||
target = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=checkpoint["shuffle_seed"],
|
||||
block_size=10,
|
||||
)
|
||||
with pytest.raises(ValueError, match="no permutation table"):
|
||||
target.load_state_dict(checkpoint)
|
||||
|
||||
|
||||
def test_two_phase_reshuffle_blocks_per_epoch_toggle(lance_table):
|
||||
"""reshuffle_blocks_per_epoch=False keeps each split's blocks fixed
|
||||
across epochs; the default (True) reassigns them every epoch."""
|
||||
block_size = 10 # NUM_ROWS=120 -> 12 blocks
|
||||
|
||||
def block_perm_for(epoch, reshuffle):
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
epoch=epoch,
|
||||
reshuffle_blocks_per_epoch=reshuffle,
|
||||
)
|
||||
return list(ds._block_perm)
|
||||
|
||||
assert block_perm_for(0, False) == block_perm_for(1, False), (
|
||||
"blocks must stay pinned to the same split across epochs when disabled"
|
||||
)
|
||||
assert block_perm_for(0, True) != block_perm_for(1, True), (
|
||||
"blocks should be reassigned across epochs by default"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_too_few_blocks_for_num_splits_raises(tmp_path):
|
||||
"""Fewer blocks than num_splits would leave some splits with no data."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", pa.table({"id": list(range(20))})) # 2 blocks
|
||||
with pytest.raises(ValueError):
|
||||
StreamingDataset(table, num_splits=4, shuffle_seed=SHUFFLE_SEED, block_size=10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"extra_kwargs",
|
||||
[
|
||||
pytest.param(
|
||||
{"block_size": 10, "shuffle_clump_size": 5},
|
||||
id="shuffle_clump_size_with_block_size",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"block_size": 10,
|
||||
"split_strategy": lambda b: b.split_sequential(fixed=NUM_SPLITS),
|
||||
},
|
||||
id="split_strategy_with_block_size",
|
||||
),
|
||||
pytest.param({"block_size": 1}, id="block_size_too_small"),
|
||||
pytest.param({"window_blocks": 2}, id="window_blocks_without_block_size"),
|
||||
pytest.param(
|
||||
{"max_shuffle_distance": 5}, id="max_shuffle_distance_without_block_size"
|
||||
),
|
||||
pytest.param(
|
||||
{"reshuffle_blocks_per_epoch": True},
|
||||
id="reshuffle_blocks_per_epoch_without_block_size",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_two_phase_constructor_validation_raises(lance_table, extra_kwargs):
|
||||
"""Invalid 2-phase parameter combinations raise ValueError at construction."""
|
||||
with pytest.raises(ValueError):
|
||||
StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
**extra_kwargs,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# split_strategy escape hatch
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1107,6 +1107,47 @@ def test_openai_bad_request_partial_batch_recovery():
|
||||
assert embeddings[1] is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_openai_client(monkeypatch):
|
||||
client = MagicMock()
|
||||
client.embeddings.create.return_value.data = []
|
||||
monkeypatch.setattr(
|
||||
"lancedb.embeddings.openai.attempt_import_or_raise", MagicMock()
|
||||
)
|
||||
monkeypatch.setattr(get_registry().get("openai"), "_openai_client", client)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("texts", "expected"),
|
||||
[([], []), ([None, ""], [None, None])],
|
||||
ids=["empty-batch", "all-inputs-filtered"],
|
||||
)
|
||||
def test_openai_skips_batches_without_valid_text(mock_openai_client, texts, expected):
|
||||
model = get_registry().get("openai").create()
|
||||
|
||||
assert model.compute_source_embeddings(texts) == expected
|
||||
mock_openai_client.embeddings.create.assert_not_called()
|
||||
|
||||
|
||||
def test_openai_add_all_invalid_texts_as_null_vectors(mock_openai_client, tmp_path):
|
||||
model = get_registry().get("openai").create(name="text-embedding-3-small", dim=2)
|
||||
|
||||
class TextModel(LanceModel):
|
||||
text: Optional[str] = model.SourceField()
|
||||
vector: Optional[Vector(model.ndims())] = model.VectorField()
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("words", schema=TextModel)
|
||||
table.add([{"text": None}, {"text": ""}], on_bad_vectors="null")
|
||||
|
||||
assert table.to_arrow().to_pylist() == [
|
||||
{"text": None, "vector": None},
|
||||
{"text": "", "vector": None},
|
||||
]
|
||||
mock_openai_client.embeddings.create.assert_not_called()
|
||||
|
||||
|
||||
def test_ollama_embeddings_pickle():
|
||||
"""OllamaEmbeddings must pickle even after the cached client is created."""
|
||||
registry = get_registry()
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import boto3
|
||||
from botocore.response import StreamingBody
|
||||
from botocore.stub import ANY, Stubber
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from pydantic import ValidationError
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb.embeddings import get_registry
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
|
||||
|
||||
TITAN_IMAGE = "amazon.titan-embed-image-v1"
|
||||
COHERE_IMAGE = "cohere.embed-v4:0"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bedrock_runtime(monkeypatch):
|
||||
runtime = boto3.Session(
|
||||
aws_access_key_id="stub-access-key",
|
||||
aws_secret_access_key="stub-secret-key",
|
||||
region_name="us-east-1",
|
||||
).client("bedrock-runtime")
|
||||
monkeypatch.setattr(boto3.Session, "client", lambda *args, **kwargs: runtime)
|
||||
return runtime
|
||||
|
||||
|
||||
def stub_embedding(stub, model_id, response):
|
||||
data = json.dumps(response).encode("utf-8")
|
||||
stub.add_response(
|
||||
"invoke_model",
|
||||
{
|
||||
"body": StreamingBody(io.BytesIO(data), len(data)),
|
||||
"contentType": "application/json",
|
||||
},
|
||||
{
|
||||
"modelId": model_id,
|
||||
"body": ANY,
|
||||
"contentType": "application/json",
|
||||
"accept": "application/json",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def encode_image(image, image_format):
|
||||
with io.BytesIO() as buffer:
|
||||
image.save(buffer, format=image_format)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"model_id, dimensions", [(TITAN_IMAGE, 1024), (COHERE_IMAGE, 1536)]
|
||||
)
|
||||
@pytest.mark.parametrize("source_type", [bytes, str], ids=["bytes", "paths"])
|
||||
async def test_bedrock_image_search(
|
||||
tmp_path, bedrock_runtime, mocker, model_id, dimensions, source_type
|
||||
):
|
||||
db_path = tmp_path / "database"
|
||||
db = lancedb.connect(db_path)
|
||||
kwargs = {"name": model_id} if model_id != TITAN_IMAGE else {}
|
||||
model = (
|
||||
get_registry()
|
||||
.get("bedrock-image")
|
||||
.create(region="eu-west-1", max_retries=0, **kwargs)
|
||||
)
|
||||
assert model.ndims() == dimensions
|
||||
|
||||
class Photo(LanceModel):
|
||||
label: str
|
||||
image: source_type = model.SourceField()
|
||||
vector: Vector(dimensions) = model.VectorField()
|
||||
|
||||
red_image = Image.new("RGB", (64, 64), "red")
|
||||
red_png = encode_image(red_image, "PNG")
|
||||
blue_image = Image.new("RGB", (64, 64), "blue")
|
||||
blue_jpeg = encode_image(blue_image, "JPEG")
|
||||
images = {"red": red_png, "blue": blue_jpeg}
|
||||
cohere_only_images = {}
|
||||
if model_id == COHERE_IMAGE:
|
||||
cohere_only_images = {
|
||||
"webp": encode_image(blue_image, "WEBP"),
|
||||
"gif": encode_image(blue_image, "GIF"),
|
||||
}
|
||||
images.update(cohere_only_images)
|
||||
sources = images.copy()
|
||||
if source_type is str:
|
||||
# The contents, not the file suffix, determine the request MIME type.
|
||||
for label, encoded_image in images.items():
|
||||
path = tmp_path / f"{label}.image"
|
||||
path.write_bytes(encoded_image)
|
||||
sources[label] = str(path)
|
||||
|
||||
red = [1.0, 0.0] + [0.0] * (dimensions - 2)
|
||||
blue = [0.0, 1.0] + [0.0] * (dimensions - 2)
|
||||
other = [0.0, 0.0, 1.0] + [0.0] * (dimensions - 3)
|
||||
invoke = mocker.spy(bedrock_runtime, "invoke_model")
|
||||
session = mocker.spy(boto3, "Session")
|
||||
with Stubber(bedrock_runtime) as stub:
|
||||
for vector in (red, blue, *([other] * len(cohere_only_images)), blue, red, red):
|
||||
if model_id == TITAN_IMAGE:
|
||||
stub_embedding(stub, model_id, {"embedding": vector})
|
||||
else:
|
||||
stub_embedding(stub, model_id, {"embeddings": {"float": [vector]}})
|
||||
|
||||
table = db.create_table("photos", schema=Photo)
|
||||
table.add(
|
||||
[{"label": label, "image": image} for label, image in sources.items()]
|
||||
)
|
||||
table = db.open_table("photos")
|
||||
restored = table.embedding_functions["vector"].function
|
||||
assert (restored.name, restored.region, restored.max_retries) == (
|
||||
model_id,
|
||||
"eu-west-1",
|
||||
0,
|
||||
)
|
||||
assert table.schema.field("vector").type.list_size == dimensions
|
||||
assert table.search("blue").limit(1).to_list()[0]["label"] == "blue"
|
||||
assert table.search(red_image).limit(1).to_list()[0]["label"] == "red"
|
||||
|
||||
async_db = await lancedb.connect_async(db_path)
|
||||
async_table = await async_db.open_table("photos")
|
||||
query = await async_table.search(red_image, query_type="vector")
|
||||
assert (await query.limit(1).to_list())[0]["label"] == "red"
|
||||
stub.assert_no_pending_responses()
|
||||
|
||||
assert session.call_args_list
|
||||
assert all(not call.args and not call.kwargs for call in session.call_args_list)
|
||||
red_base64 = base64.b64encode(red_png).decode("ascii")
|
||||
blue_base64 = base64.b64encode(blue_jpeg).decode("ascii")
|
||||
if model_id == TITAN_IMAGE:
|
||||
red_query = {"inputImage": red_base64}
|
||||
expected = [
|
||||
{"inputImage": red_base64},
|
||||
{"inputImage": blue_base64},
|
||||
{"inputText": "blue"},
|
||||
red_query,
|
||||
red_query,
|
||||
]
|
||||
else:
|
||||
red_uri = f"data:image/png;base64,{red_base64}"
|
||||
blue_uri = f"data:image/jpeg;base64,{blue_base64}"
|
||||
red_query = {"images": [red_uri], "input_type": "search_query"}
|
||||
additional_documents = [
|
||||
{
|
||||
"images": [
|
||||
f"data:image/{image_format};base64,"
|
||||
f"{base64.b64encode(image).decode('ascii')}"
|
||||
],
|
||||
"input_type": "search_document",
|
||||
}
|
||||
for image_format, image in cohere_only_images.items()
|
||||
]
|
||||
expected = [
|
||||
{"images": [red_uri], "input_type": "search_document"},
|
||||
{"images": [blue_uri], "input_type": "search_document"},
|
||||
*additional_documents,
|
||||
{"texts": ["blue"], "input_type": "search_query"},
|
||||
red_query,
|
||||
red_query,
|
||||
]
|
||||
expected = [{**payload, "embedding_types": ["float"]} for payload in expected]
|
||||
assert [
|
||||
json.loads(call.kwargs["body"]) for call in invoke.call_args_list
|
||||
] == expected
|
||||
|
||||
|
||||
def test_bedrock_image_retry_does_not_replay_successful_rows(
|
||||
tmp_path, bedrock_runtime, mocker
|
||||
):
|
||||
sleep = mocker.patch("lancedb.embeddings.utils.time.sleep")
|
||||
model = get_registry().get("bedrock-image").create(max_retries=1)
|
||||
|
||||
class Photo(LanceModel):
|
||||
image: bytes | None = model.SourceField()
|
||||
vector: Vector(model.ndims()) | None = model.VectorField()
|
||||
|
||||
table = lancedb.connect(tmp_path).create_table("photos", schema=Photo)
|
||||
red_png = encode_image(Image.new("RGB", (64, 64), "red"), "PNG")
|
||||
blue_png = encode_image(Image.new("RGB", (64, 64), "blue"), "PNG")
|
||||
red = [1.0] + [0.0] * 1023
|
||||
blue = [0.0, 1.0] + [0.0] * 1022
|
||||
invoke = mocker.spy(bedrock_runtime, "invoke_model")
|
||||
with Stubber(bedrock_runtime) as stub:
|
||||
stub_embedding(stub, TITAN_IMAGE, {"embedding": red})
|
||||
stub.add_client_error(
|
||||
"invoke_model",
|
||||
service_error_code="ThrottlingException",
|
||||
http_status_code=429,
|
||||
)
|
||||
stub_embedding(stub, TITAN_IMAGE, {"embedding": blue})
|
||||
table.add(
|
||||
[{"image": red_png}, {"image": None}, {"image": blue_png}],
|
||||
on_bad_vectors="null",
|
||||
)
|
||||
stub.assert_no_pending_responses()
|
||||
|
||||
sleep.assert_called_once()
|
||||
assert [
|
||||
base64.b64decode(json.loads(call.kwargs["body"])["inputImage"])
|
||||
for call in invoke.call_args_list
|
||||
] == [red_png, blue_png, blue_png]
|
||||
assert table.to_arrow()["vector"].to_pylist() == [red, None, blue]
|
||||
|
||||
|
||||
def test_bedrock_image_local_error_does_not_retry(tmp_path, mocker):
|
||||
sleep = mocker.patch("lancedb.embeddings.utils.time.sleep")
|
||||
session = mocker.patch.object(boto3, "Session")
|
||||
model = get_registry().get("bedrock-image").create(max_retries=1)
|
||||
|
||||
class Photo(LanceModel):
|
||||
image: bytes = model.SourceField()
|
||||
vector: Vector(model.ndims()) = model.VectorField()
|
||||
|
||||
table = lancedb.connect(tmp_path).create_table("photos", schema=Photo)
|
||||
with pytest.raises(RuntimeError, match="UnidentifiedImageError"):
|
||||
table.add([{"image": b"invalid image bytes"}])
|
||||
assert table.count_rows() == 0
|
||||
|
||||
with pytest.raises(UnidentifiedImageError):
|
||||
model.compute_source_embeddings_with_retry(b"invalid image bytes")
|
||||
gif = encode_image(Image.new("RGB", (64, 64)), "GIF")
|
||||
with pytest.raises(ValueError, match="accepts PNG and JPEG images"):
|
||||
model.compute_source_embeddings_with_retry(gif)
|
||||
with pytest.raises(TypeError, match="text or a Pillow image"):
|
||||
model.compute_query_embeddings_with_retry(b"invalid query")
|
||||
sleep.assert_not_called()
|
||||
session.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field, value",
|
||||
[
|
||||
("profile_name", "other-profile"),
|
||||
("assumed_role", "arn:aws:iam::123456789012:role/OtherRole"),
|
||||
("role_session_name", "other-session"),
|
||||
],
|
||||
)
|
||||
def test_bedrock_image_rejects_credential_settings(tmp_path, mocker, field, value):
|
||||
registry = get_registry()
|
||||
image_provider = registry.get("bedrock-image")
|
||||
session = mocker.patch.object(boto3, "Session")
|
||||
with pytest.raises(ValidationError, match=field):
|
||||
image_provider.create(**{field: value})
|
||||
|
||||
model = image_provider.create()
|
||||
|
||||
class Photo(LanceModel):
|
||||
image: bytes = model.SourceField()
|
||||
vector: Vector(model.ndims()) = model.VectorField()
|
||||
|
||||
schema = Photo.to_arrow_schema()
|
||||
metadata = schema.metadata
|
||||
key = b"embedding_functions"
|
||||
entries = json.loads(metadata[key])
|
||||
entries[0]["model"][field] = value
|
||||
metadata[key] = json.dumps(entries).encode()
|
||||
schema = schema.with_metadata(metadata)
|
||||
lancedb.connect(tmp_path).create_table("photos", schema=schema)
|
||||
reopened = lancedb.connect(tmp_path).open_table("photos")
|
||||
with pytest.raises(ValidationError, match=field):
|
||||
reopened.search("sunset", query_type="vector").limit(1).to_list()
|
||||
session.assert_not_called()
|
||||
|
||||
|
||||
def test_bedrock_text_restores_credential_settings(tmp_path, mocker):
|
||||
registry = get_registry()
|
||||
model = registry.get("bedrock-text").create(
|
||||
profile_name="text-profile",
|
||||
assumed_role="arn:aws:iam::123456789012:role/TextRole",
|
||||
role_session_name="text-session",
|
||||
)
|
||||
|
||||
class TextRow(LanceModel):
|
||||
text: str = model.SourceField()
|
||||
vector: Vector(model.ndims()) = model.VectorField()
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
db.create_table("texts", schema=TextRow)
|
||||
restored = registry.parse_functions(db.open_table("texts").schema.metadata)[
|
||||
"vector"
|
||||
].function
|
||||
session = mocker.patch.object(boto3, "Session")
|
||||
client = session.return_value.client
|
||||
sts = mocker.Mock()
|
||||
runtime = mocker.Mock()
|
||||
client.side_effect = [sts, runtime]
|
||||
sts.assume_role.return_value = {
|
||||
"Credentials": {
|
||||
"AccessKeyId": "stub-key",
|
||||
"SecretAccessKey": "stub-secret",
|
||||
"SessionToken": "stub-token",
|
||||
}
|
||||
}
|
||||
|
||||
assert restored.client is runtime
|
||||
session.assert_called_once_with(
|
||||
region_name=model.region, profile_name="text-profile"
|
||||
)
|
||||
sts.assume_role.assert_called_once_with(
|
||||
RoleArn="arn:aws:iam::123456789012:role/TextRole",
|
||||
RoleSessionName="text-session",
|
||||
)
|
||||
assert client.call_args.kwargs["aws_session_token"] == "stub-token"
|
||||
|
||||
|
||||
def test_bedrock_text_cohere_v3(bedrock_runtime, mocker):
|
||||
model_id = "cohere.embed-multilingual-v3"
|
||||
model = get_registry().get("bedrock-text").create(name=model_id, max_retries=0)
|
||||
vector = [1.0] * 1024
|
||||
invoke = mocker.spy(bedrock_runtime, "invoke_model")
|
||||
with Stubber(bedrock_runtime) as stub:
|
||||
stub_embedding(stub, model_id, {"embeddings": [vector]})
|
||||
stub_embedding(stub, model_id, {"embeddings": [vector]})
|
||||
assert model.ndims() == 1024
|
||||
assert model.compute_source_embeddings(["document"]) == [vector]
|
||||
assert model.compute_query_embeddings("query") == [vector]
|
||||
stub.assert_no_pending_responses()
|
||||
|
||||
assert [json.loads(call.kwargs["body"]) for call in invoke.call_args_list] == [
|
||||
{"texts": ["document"], "input_type": "search_document"},
|
||||
{"texts": ["query"], "input_type": "search_query"},
|
||||
]
|
||||
@@ -233,15 +233,27 @@ OCI_REGION_ENDPOINT = (
|
||||
("ollama", {"host": ATTACKER_URL}),
|
||||
("ollama", {"ollama_client_kwargs": {"proxy": ATTACKER_URL}}),
|
||||
("watsonx", {"url": ATTACKER_URL}),
|
||||
(
|
||||
"cohere",
|
||||
{
|
||||
"name": "embed-v-4-0",
|
||||
"base_url": ATTACKER_URL,
|
||||
"output_dimension": 256,
|
||||
"api_key": "$var:cohere-test-key",
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_restored_custom_endpoint_requires_allowlist(name, model):
|
||||
def test_restored_custom_endpoint_requires_allowlist(name, model, monkeypatch):
|
||||
registry = get_registry()
|
||||
monkeypatch.setitem(registry._variables, "cohere-test-key", "test-cohere-key")
|
||||
|
||||
func = restore(name, model)
|
||||
with pytest.raises(UntrustedEmbeddingConfigError, match="attacker.example"):
|
||||
func.compute_query_embeddings("hello")
|
||||
|
||||
get_registry().allow_endpoint(ATTACKER_URL)
|
||||
assert isinstance(restore(name, model), get_registry().get(name))
|
||||
registry.allow_endpoint(ATTACKER_URL)
|
||||
assert isinstance(restore(name, model), registry.get(name))
|
||||
|
||||
|
||||
def test_default_endpoints_need_no_allowlist():
|
||||
|
||||
@@ -10,10 +10,12 @@ from lance_namespace.errors import TableNotFoundError as NamespaceTableNotFoundE
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.remote.errors import (
|
||||
AlreadyExistsError,
|
||||
ConflictError,
|
||||
FunctionNotFoundError,
|
||||
HttpError,
|
||||
LanceDBClientError,
|
||||
NamespaceNotFoundError,
|
||||
ResponseInterruptedError,
|
||||
RetryError,
|
||||
SecretNotFoundError,
|
||||
TableNotFoundError,
|
||||
@@ -72,6 +74,31 @@ def test_pickle_http_transport_error():
|
||||
assert restored.request_id == "req-789"
|
||||
|
||||
|
||||
def test_pickle_response_interrupted_error():
|
||||
err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True)
|
||||
restored = pickle.loads(pickle.dumps(err))
|
||||
assert type(restored) is ResponseInterruptedError
|
||||
assert str(restored) == "interrupted"
|
||||
assert restored.request_id == "req-1"
|
||||
assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7)
|
||||
assert restored.is_transport_error is True
|
||||
assert restored.status_code is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"])
|
||||
def test_http_conflict_error_preserves_reason_and_metadata(error_code):
|
||||
reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"
|
||||
original = HttpError(reason, "req-conflict", 409, error_code)
|
||||
for error in [original, pickle.loads(pickle.dumps(original))]:
|
||||
assert type(error) is ConflictError
|
||||
assert isinstance(error, HttpError)
|
||||
assert str(error) == reason
|
||||
assert error.request_id == "req-conflict"
|
||||
assert error.status_code == 409
|
||||
assert error.error_code == error_code
|
||||
assert error.is_transport_error is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error_code,resource_kind,status_code,expected_type",
|
||||
[
|
||||
@@ -251,6 +278,9 @@ def test_sql_errors_use_only_server_codes(code, category, type_name):
|
||||
(400, "schema_mismatch", "SchemaMismatchError"),
|
||||
(404, "table_not_found", "TableNotFoundError"),
|
||||
(404, "reference_not_found", "ReferenceNotFoundError"),
|
||||
(409, None, "ConflictError"),
|
||||
(409, "conflict", "ConflictError"),
|
||||
(500, "conflict", "HttpError"),
|
||||
(500, "column_not_found", "HttpError"),
|
||||
(503, "table_not_found", "HttpError"),
|
||||
],
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from collections import UserDict
|
||||
from pathlib import Path
|
||||
from types import MappingProxyType
|
||||
|
||||
import pytest
|
||||
|
||||
from lancedb import col
|
||||
from lancedb import col, lit
|
||||
import lancedb.functions as functions
|
||||
from lancedb.functions import (
|
||||
FunctionApplication,
|
||||
FunctionBinding,
|
||||
FunctionImage,
|
||||
FunctionVersion,
|
||||
PythonRuntimeSpec,
|
||||
SecretBinding,
|
||||
@@ -20,6 +22,7 @@ from lancedb.functions import (
|
||||
SecretReference,
|
||||
)
|
||||
from lancedb.table import AsyncTable
|
||||
from lancedb.resources import _resource_options
|
||||
|
||||
|
||||
FIXTURES = (
|
||||
@@ -34,7 +37,7 @@ FIXTURES = (
|
||||
|
||||
|
||||
def fixture(name: str) -> str:
|
||||
return (FIXTURES / name).read_text()
|
||||
return (FIXTURES / name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def job_result(name: str) -> dict:
|
||||
@@ -58,6 +61,7 @@ def assert_no_secret_values(value):
|
||||
|
||||
|
||||
def test_public_function_values_are_in_api_reference():
|
||||
assert "LiteralInputBinding" in functions.__all__
|
||||
docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md"
|
||||
rendered = docs.read_text()
|
||||
for name in functions.__all__:
|
||||
@@ -148,6 +152,91 @@ def test_function_version_identity_is_immutable_and_exact():
|
||||
FunctionVersion(**{**value, "version": invalid})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gpu", [False, True])
|
||||
def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
|
||||
value = job_result("remote_function_job.json")["image"]
|
||||
value["descriptor"]["future_metadata"] = "x" * 100_000
|
||||
if gpu:
|
||||
value["descriptor"]["requires"]["capabilities"] = [
|
||||
{
|
||||
"type": "lance.cuda",
|
||||
"version": 1,
|
||||
"device_count": 1,
|
||||
"cuda_toolkit": "12.4",
|
||||
}
|
||||
]
|
||||
image = FunctionImage(**value)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", DeprecationWarning)
|
||||
details = image.describe()
|
||||
rendered = repr(image)
|
||||
assert "manifest_digest=" in str(image)
|
||||
encoded = json.loads(image.to_canonical_json())
|
||||
assert details == {
|
||||
"manifest_digest": value["manifest_digest"],
|
||||
"python_version": "3.12.14",
|
||||
"requires_gpu": gpu,
|
||||
"cuda_toolkit": "12.4" if gpu else None,
|
||||
"platforms": None,
|
||||
"base_image": None,
|
||||
"size_bytes": None,
|
||||
}
|
||||
assert len(rendered) < 350
|
||||
assert f"requires_gpu={gpu}" in rendered
|
||||
assert "future_metadata" not in rendered
|
||||
assert encoded == value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"descriptor",
|
||||
[
|
||||
{},
|
||||
{"format_version": 2, "requires": {"capabilities": []}},
|
||||
{"format_version": 1, "requires": {"capabilities": [None]}},
|
||||
{"python": {"version": {"future": "x" * 100_000}}},
|
||||
],
|
||||
)
|
||||
def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
|
||||
image = FunctionImage(
|
||||
manifest_digest="sha256:example", descriptor=descriptor, source=True
|
||||
)
|
||||
assert image.describe()["requires_gpu"] is None
|
||||
assert image.describe()["python_version"] is None
|
||||
assert len(repr(image)) < 350
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
|
||||
)
|
||||
def test_runtime_digests_match_server_golden_values(case):
|
||||
runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"]))
|
||||
assert runtime.digest == case["digest"]
|
||||
assert (
|
||||
PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest
|
||||
== runtime.digest
|
||||
)
|
||||
|
||||
|
||||
def test_unknown_runtime_digest_fails_closed():
|
||||
runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}')
|
||||
with pytest.raises(ValueError, match="cannot digest unknown runtime kind"):
|
||||
runtime.digest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"])
|
||||
def test_function_version_preserves_runtime_digest(runtime_digest):
|
||||
value = job_result("remote_function_job.json")
|
||||
legacy = FunctionVersion.from_json(json.dumps(value))
|
||||
assert legacy.runtime_digest is None
|
||||
assert "runtime_digest" not in json.loads(legacy.to_canonical_json())
|
||||
value["runtime_digest"] = runtime_digest
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
assert version.runtime_digest == runtime_digest
|
||||
assert FunctionVersion.from_json(version.to_canonical_json()) == version
|
||||
with pytest.raises((TypeError, ValueError)):
|
||||
version.runtime_digest = "sha256:changed"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"])
|
||||
def test_function_version_preserves_source_digest(source_digest):
|
||||
value = job_result("remote_function_job.json")
|
||||
@@ -180,6 +269,28 @@ def test_function_version_exposes_registered_gpu_class():
|
||||
assert json.loads(version.to_canonical_json())["gpu_class"] == "a10g"
|
||||
|
||||
|
||||
def test_function_version_preserves_execution_controls():
|
||||
value = job_result("remote_function_job.json")
|
||||
value.update(
|
||||
batch_size=12,
|
||||
max_concurrency=4,
|
||||
row_timeout_seconds=8.0,
|
||||
result_stability="input_and_context",
|
||||
)
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
encoded = json.loads(version.to_canonical_json())
|
||||
|
||||
assert encoded == value
|
||||
assert type(encoded["batch_size"]) is int
|
||||
assert type(encoded["max_concurrency"]) is int
|
||||
assert type(encoded["row_timeout_seconds"]) is float
|
||||
assert type(encoded["result_stability"]) is str
|
||||
|
||||
for invalid in [True, 1.5, 0, -1, 2**32]:
|
||||
with pytest.raises(ValueError, match="max_concurrency"):
|
||||
FunctionVersion(**{**value, "max_concurrency": invalid})
|
||||
|
||||
|
||||
def test_function_version_binds_named_columns_as_one_immutable_application():
|
||||
version = FunctionVersion.from_json(
|
||||
json.dumps(job_result("remote_function_job.json"))
|
||||
@@ -232,6 +343,67 @@ def test_function_version_binding_validates_names_and_direct_columns():
|
||||
version(text=col("text").lower())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1])
|
||||
def test_function_version_binds_direct_literals_without_changing_identity(constant):
|
||||
value = job_result("remote_function_job.json")
|
||||
value["signature"]["inputs"].append(
|
||||
{
|
||||
"name": "option",
|
||||
"arrow_type": "bool"
|
||||
if type(constant) is bool
|
||||
else "utf8"
|
||||
if isinstance(constant, str)
|
||||
else "uint64"
|
||||
if constant == 2**64 - 1
|
||||
else "int64",
|
||||
"nullable": True,
|
||||
}
|
||||
)
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
expression = lit(constant)
|
||||
application = version(text=col("body"), option=expression)
|
||||
encoded = json.loads(application.to_canonical_json())
|
||||
assert encoded["inputs"] == [
|
||||
{"parameter": "text", "kind": "column", "value": {"path": "body"}},
|
||||
{"parameter": "option", "kind": "literal", "value": constant},
|
||||
]
|
||||
assert application.function.version == version.version
|
||||
assert application.function.object_id == version.object_id
|
||||
assert application.function.manifest_digest == version.image.manifest_digest
|
||||
assert FunctionApplication.from_json(application.to_canonical_json()) == application
|
||||
if constant is None:
|
||||
assert expression.to_sql() == "NULL"
|
||||
if type(constant) is int:
|
||||
assert expression.to_sql() == str(constant)
|
||||
|
||||
|
||||
def test_function_literals_reject_expressions_and_unsupported_values():
|
||||
version = FunctionVersion.from_json(
|
||||
json.dumps(job_result("remote_function_job.json"))
|
||||
)
|
||||
with pytest.raises(TypeError, match="direct col"):
|
||||
version(text=lit(16) + lit(8))
|
||||
with pytest.raises(ValueError, match="floating-point Function literals"):
|
||||
version(text=lit(1.5))
|
||||
with pytest.raises(TypeError, match="unsupported Function literal type"):
|
||||
version(text=lit(b"data"))
|
||||
|
||||
|
||||
def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters():
|
||||
value = json.loads((FIXTURES / "remote_function_binding.json").read_text())
|
||||
value["inputs"] = value["inputs"][:1]
|
||||
value["literal_inputs"] = [{"parameter": "body", "value": None}]
|
||||
binding = FunctionBinding.from_json(json.dumps(value))
|
||||
assert binding.literal_inputs[0].value is None
|
||||
assert json.loads(binding.to_canonical_json())["literal_inputs"] == [
|
||||
{"parameter": "body", "value": None}
|
||||
]
|
||||
assert FunctionBinding.from_json(binding.to_canonical_json()) == binding
|
||||
value["literal_inputs"][0]["parameter"] = "title"
|
||||
with pytest.raises(ValueError, match="input parameters must be unique"):
|
||||
FunctionBinding.from_json(json.dumps(value))
|
||||
|
||||
|
||||
def test_function_version_keeps_named_struct_outputs_in_one_application():
|
||||
value = job_result("remote_function_job.json")
|
||||
value["name"] = "text_features"
|
||||
@@ -285,10 +457,15 @@ def test_unknown_fields_and_discriminators_are_forward_decodable():
|
||||
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
assert version.image.descriptor["future_interface"] == {"kind": "wasm"}
|
||||
assert json.loads(version.to_canonical_json())["image"]["descriptor"][
|
||||
"future_interface"
|
||||
] == {"kind": "wasm"}
|
||||
assert version.signature.output.kind == "future_output_shape"
|
||||
assert not hasattr(version, "future_version_metadata")
|
||||
|
||||
canonical = json.loads(version.to_canonical_json())
|
||||
expected = json.loads(fixture("remote_function_version.canonical.json"))
|
||||
expected["image"]["descriptor"]["future_interface"] = {"kind": "wasm"}
|
||||
expected["signature"]["output"]["kind"] = "future_output_shape"
|
||||
assert canonical == expected
|
||||
assert "future_version_metadata" not in canonical
|
||||
|
||||
|
||||
def test_function_application_uses_rename_columns_only():
|
||||
@@ -434,17 +611,23 @@ class _FunctionDeclarationInner:
|
||||
|
||||
async def add_function_columns(
|
||||
self,
|
||||
application_json,
|
||||
output_name,
|
||||
bindings,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
gpu_class=None,
|
||||
gpu_count=None,
|
||||
):
|
||||
self.calls.append(
|
||||
(
|
||||
json.loads(application_json),
|
||||
output_name,
|
||||
[(json.loads(app), name) for app, name in bindings],
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
total_memory_bytes,
|
||||
total_gpu_count,
|
||||
)
|
||||
)
|
||||
return "declared"
|
||||
@@ -469,29 +652,45 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
mapping_type({"features": application._copy(update={"columns": {}})})
|
||||
)
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] == "features"
|
||||
assert inner.calls[-1][2:] == (None, None)
|
||||
[(_, name)], *options = inner.calls[-1]
|
||||
assert name == "features"
|
||||
assert options == [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)
|
||||
[(payload, name)], *options = inner.calls[-1]
|
||||
assert name is None
|
||||
assert payload["columns"] == {"normalized_text": "search_text"}
|
||||
assert options == [False, 300, 8000, None, 0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_rejects_multiple_bindings_and_unknown_newer_application():
|
||||
async def test_add_columns_routes_multiple_bindings_in_one_call():
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()._copy(update={"columns": {}})
|
||||
assert await table.add_columns({"a": application, "b": application}) == "declared"
|
||||
assert len(inner.calls) == 1
|
||||
assert [name for _, name in inner.calls[0][0]] == ["a", "b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_rejects_mixed_bindings_and_unknown_newer_application():
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()
|
||||
|
||||
with pytest.raises(ValueError, match="exactly one Function binding"):
|
||||
await table.add_columns({"a": application, "b": application})
|
||||
with pytest.raises(ValueError, match="cannot mix Function applications"):
|
||||
await table.add_columns({"a": application, "b": "1+1"})
|
||||
|
||||
future = json.loads(fixture("remote_function_application.json"))
|
||||
application = FunctionApplication(**future)
|
||||
@@ -537,3 +736,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)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+176
-14
@@ -29,6 +29,7 @@ from lancedb.query import (
|
||||
CombinedFieldsQuery,
|
||||
DocumentGranularity,
|
||||
FullTextOperator,
|
||||
FullTextSearchQuery,
|
||||
MatchQuery,
|
||||
MultiMatchQuery,
|
||||
PhraseQuery,
|
||||
@@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
|
||||
|
||||
def test_search_fts_phrase_query(table):
|
||||
table.create_fts_index("text", with_position=False)
|
||||
try:
|
||||
phrase_results = table.search('"puppy runs"').limit(100).to_list()
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
table.search('"puppy runs"').limit(100).to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
table.create_fts_index("text", with_position=True, replace=True)
|
||||
results = table.search("puppy").limit(100).to_list()
|
||||
|
||||
@@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_fts_phrase_query_async(async_table):
|
||||
await async_table.create_index("text", config=FTS(with_position=False))
|
||||
try:
|
||||
phrase_results = (
|
||||
await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
|
||||
)
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
await async_table.query().nearest_to_text('"puppy runs"').to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
await async_table.create_index("text", config=FTS(with_position=True))
|
||||
results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
|
||||
phrase_results = (
|
||||
@@ -1660,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object():
|
||||
def test_fts_phrase_query_execution_preserves_user_text():
|
||||
table = mock.Mock()
|
||||
table.schema = pa.schema([])
|
||||
table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader()
|
||||
# to_arrow() collects through the eager path; keep a real Table so the
|
||||
# reranker still receives and returns the real result contract.
|
||||
table._execute_arrow.return_value = pa.table({"text": ["result"]})
|
||||
|
||||
class CapturingReranker:
|
||||
score = "relevance"
|
||||
@@ -1682,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text():
|
||||
|
||||
query.to_arrow()
|
||||
|
||||
backend_query = table._execute_query.call_args.args[0]
|
||||
backend_query = table._execute_arrow.call_args.args[0]
|
||||
assert (
|
||||
backend_query.full_text_query.query,
|
||||
reranker.queries,
|
||||
@@ -1948,3 +1945,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
|
||||
|
||||
rows = await table.query().nearest_to_text("http").to_list()
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
|
||||
db = ldb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
table.create_index("text", config=FTS())
|
||||
kwargs = {"fts_columns": "text"}
|
||||
if operator is not None:
|
||||
kwargs["operator"] = operator
|
||||
query = table.search("gripper closed", query_type="fts", **kwargs)
|
||||
assert query.count_rows() == expected
|
||||
assert len(query.limit(100).to_list()) == expected
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", fts_columns="text")
|
||||
.operator("AND")
|
||||
.count_rows()
|
||||
== 15
|
||||
)
|
||||
if operator is not None:
|
||||
assert query.to_query_object().full_text_query.operator == operator
|
||||
query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
assert len(query.to_list()) <= 2
|
||||
assert (
|
||||
table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
|
||||
)
|
||||
assert (
|
||||
table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
|
||||
== 15
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
async def test_simple_fts_operator_and_count_async(
|
||||
tmp_path, indexed, operator, expected
|
||||
):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
await table.create_index("text", config=FTS())
|
||||
query = await table.search(
|
||||
"gripper closed", query_type="fts", fts_columns="text", operator=operator
|
||||
)
|
||||
assert await query.count_rows() == expected
|
||||
assert len(await query.limit(100).to_list()) == expected
|
||||
query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert await query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
direct = table.query().nearest_to_text(
|
||||
"gripper closed", columns="text", operator="AND"
|
||||
)
|
||||
assert await direct.count_rows() == 15
|
||||
assert direct.to_query_object().full_text_query.query.operator == "AND"
|
||||
assert (
|
||||
await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
def test_fts_phrase_count_positions(tmp_path, with_position, query):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.search(query, query_type="fts")
|
||||
if with_position:
|
||||
assert search.count_rows() == 1
|
||||
assert len(search.to_list()) == 1
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", operator="AND")
|
||||
.phrase_query()
|
||||
.count_rows()
|
||||
== 1
|
||||
)
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
await table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.query().nearest_to_text(query)
|
||||
if with_position:
|
||||
assert await search.count_rows() == 1
|
||||
assert len(await search.to_list()) == 1
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
await search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
def test_fts_operator_rejects_invalid_queries(table):
|
||||
with pytest.raises(ValueError):
|
||||
table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError, match="operator requires a string full-text query"):
|
||||
FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_operator_rejects_invalid_queries_async(async_table):
|
||||
with pytest.raises(ValueError):
|
||||
await async_table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
await async_table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError):
|
||||
async_table.query().nearest_to_text(query, operator="AND")
|
||||
|
||||
|
||||
def test_fts_count_fast_search(tmp_path):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"matches", pa.table({"text": ["gripper closed"] * 15})
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper closed"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").count_rows() == 20
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb.functions import (
|
||||
BlobWriter,
|
||||
FunctionDefinition,
|
||||
FunctionRegistrationRequest,
|
||||
FunctionVersion,
|
||||
function,
|
||||
)
|
||||
|
||||
|
||||
def _stored_function_version():
|
||||
fixture = (
|
||||
Path(__file__).parents[3]
|
||||
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
|
||||
/ "remote_function_version.canonical.json"
|
||||
)
|
||||
return json.loads(fixture.read_text())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"])
|
||||
@pytest.mark.parametrize("exist_ok", [None, False, True])
|
||||
async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
stored = _stored_function_version()
|
||||
result = pa.table({"definition": [json.dumps(stored)]})
|
||||
|
||||
@function(name=stored["name"])
|
||||
def replacement(value: float) -> float:
|
||||
return value * 2
|
||||
|
||||
class FunctionServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with FunctionServer() as server:
|
||||
options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
|
||||
kwargs["namespace_path"] = ["team"]
|
||||
if entry == "async_job":
|
||||
db = await lancedb.connect_async("db://analytics", **options)
|
||||
job = await db.create_function_async(replacement, **kwargs)
|
||||
version = await job.wait()
|
||||
else:
|
||||
db = lancedb.connect("db://analytics", **options)
|
||||
if entry == "sync_job":
|
||||
version = db.create_function_async(replacement, **kwargs).wait()
|
||||
else:
|
||||
version = db.create_function(replacement, **kwargs)
|
||||
(request,) = server.requests
|
||||
|
||||
prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION"
|
||||
assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
|
||||
assert b'"exist_ok"' not in request
|
||||
assert json.loads(version.to_canonical_json()) == stored
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blob_writer_paths_round_trip_through_function_registration():
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
stored = _stored_function_version()
|
||||
expected_paths = [[{"field": "item"}], [{"field": "variants"}, "item"]]
|
||||
output_schema = pa.schema(
|
||||
[
|
||||
BlobWriter.field("item"),
|
||||
pa.field("variants", pa.list_(BlobWriter.field("asset"))),
|
||||
pa.field("checksum", pa.binary(), nullable=False),
|
||||
]
|
||||
)
|
||||
|
||||
@function(name=stored["name"], output_schema=output_schema)
|
||||
def render(text: str):
|
||||
with BlobWriter.open() as output:
|
||||
output.write(text.encode())
|
||||
return {"item": output, "variants": [b"", None], "checksum": b""}
|
||||
|
||||
expected_output = json.loads(
|
||||
render.registration_request.signature.output.to_canonical_json()
|
||||
)
|
||||
assert expected_output["kind"] == "named_struct_blob_writer"
|
||||
assert expected_output["blob_writer_paths"] == expected_paths
|
||||
stored["signature"] = {
|
||||
"inputs": [{"name": "text", "arrow_type": "utf8", "nullable": False}],
|
||||
"output": expected_output,
|
||||
}
|
||||
|
||||
class FunctionServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"definition": [json.dumps(stored)]})
|
||||
)
|
||||
|
||||
with FunctionServer() as server:
|
||||
db = await lancedb.connect_async(
|
||||
"db://analytics",
|
||||
api_key="test-key",
|
||||
host_override="http://localhost:10024",
|
||||
sql_host_override=f"grpc://127.0.0.1:{server.port}",
|
||||
)
|
||||
job = await db.create_function_async(render)
|
||||
version = await job.wait()
|
||||
(request,) = server.requests
|
||||
|
||||
assert b"CREATE FUNCTION" in request
|
||||
_, marker, body = request.partition(b" FROM '{")
|
||||
assert marker
|
||||
submitted, _ = json.JSONDecoder().raw_decode("{" + body.decode(errors="replace"))
|
||||
assert submitted["signature"]["output"] == expected_output
|
||||
assert (
|
||||
json.loads(version.to_canonical_json())["signature"]["output"]
|
||||
== expected_output
|
||||
)
|
||||
application = version(text=lancedb.col("text")).rename(columns={"item": "payload"})
|
||||
assert json.loads(application.to_canonical_json())["output"] == expected_output
|
||||
assert application.columns == {"item": "payload"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_primary", [False, True])
|
||||
async def test_function_index_inspection_is_separate_from_registration(with_primary):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
primary = "https://primary.example/simple/"
|
||||
extra = "https://extra.example/simple/"
|
||||
stored = _stored_function_version()
|
||||
name = stored["name"]
|
||||
|
||||
def scale(value: float) -> float:
|
||||
return 2 * value
|
||||
|
||||
authored = function(name=name, pip=["example==1.0"], python_version="3.12")(scale)
|
||||
request = authored.registration_request
|
||||
expected_runtime = {
|
||||
"kind": "python",
|
||||
"python_version": "3.12",
|
||||
"environment": {"kind": "pip", "packages": ["example==1.0"]},
|
||||
}
|
||||
stored["runtime"] = json.loads(request.runtime.to_canonical_json())
|
||||
build = {"extra_index_urls": [extra]}
|
||||
if with_primary:
|
||||
build["index_url"] = primary
|
||||
stored["runtime"]["environment"]["build"] = build
|
||||
stored["runtime_digest"] = "sha256:" + "1" * 64
|
||||
stored["resolved_environment"] = {
|
||||
"packages": [],
|
||||
"provenance": {"configured_index_urls": [extra]},
|
||||
}
|
||||
|
||||
class FunctionServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
if b"DESCRIBE FUNCTION" in ticket.ticket:
|
||||
assert b"FORMAT JSON" in ticket.ticket
|
||||
return flight.RecordBatchStream(
|
||||
pa.table(
|
||||
{"description": [json.dumps(stored)]}
|
||||
).replace_schema_metadata({b"lancedb.describe.format": b"json"})
|
||||
)
|
||||
return flight.RecordBatchStream(
|
||||
pa.table({"definition": [json.dumps(stored)]})
|
||||
)
|
||||
|
||||
class IndexedDefinition(FunctionDefinition):
|
||||
def bind_secrets(self, secrets):
|
||||
payload = json.loads(super().bind_secrets(secrets).to_canonical_json())
|
||||
payload["runtime"]["environment"]["build"] = build
|
||||
return FunctionRegistrationRequest.from_json(json.dumps(payload))
|
||||
|
||||
definition = IndexedDefinition(
|
||||
scale,
|
||||
name=name,
|
||||
input_schema=None,
|
||||
output_schema=None,
|
||||
pip=("example==1.0",),
|
||||
env={},
|
||||
python_version="3.12",
|
||||
)
|
||||
|
||||
with FunctionServer() as server:
|
||||
options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://127.0.0.1:1",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
db = lancedb.connect("db://analytics", **options)
|
||||
async_db = await lancedb.connect_async("db://analytics", **options)
|
||||
|
||||
message = r"runtime\.environment\.build is unsupported"
|
||||
with pytest.raises(TypeError, match=message):
|
||||
db.create_function(definition)
|
||||
with pytest.raises(TypeError, match=message):
|
||||
await async_db.create_function_async(definition)
|
||||
assert server.requests == []
|
||||
|
||||
version = db.get_function(name, version=1)
|
||||
assert await async_db.get_function(name, version="1") == version
|
||||
assert all(
|
||||
f"DESCRIBE FUNCTION \"{name}\" WITH (version = '1') FORMAT JSON".encode()
|
||||
in ticket
|
||||
for ticket in server.requests
|
||||
)
|
||||
assert len(server.requests) == 2
|
||||
assert version.runtime_digest == stored["runtime_digest"]
|
||||
assert version.resolved_environment.provenance.configured_index_urls == (extra,)
|
||||
canonical = version.to_canonical_json()
|
||||
encoded = json.loads(canonical)
|
||||
assert FunctionVersion.from_json(canonical) == version
|
||||
if with_primary:
|
||||
assert version.runtime.environment.build.index_url == primary
|
||||
assert encoded["runtime"]["environment"]["build"] == {"index_url": primary}
|
||||
else:
|
||||
assert version.runtime.environment.build is None
|
||||
assert "build" not in encoded["runtime"]["environment"]
|
||||
with pytest.raises(TypeError, match="runtime metadata is for inspection only"):
|
||||
FunctionRegistrationRequest.model_validate(
|
||||
{**request.model_dump(), "runtime": version.runtime}
|
||||
)
|
||||
with pytest.raises(TypeError, match="runtime metadata is for inspection only"):
|
||||
request.model_copy(update={"runtime": version.runtime}).to_canonical_json()
|
||||
|
||||
job = await async_db.create_function_async(authored, refresh_lock=True)
|
||||
assert await job.wait() == version
|
||||
_, marker, body = server.requests[-1].partition(b" FROM '{")
|
||||
assert marker
|
||||
sent, _ = json.JSONDecoder().raw_decode("{" + body.decode(errors="replace"))
|
||||
assert sent["refresh_lock"] is True
|
||||
assert sent["runtime"] == expected_runtime
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import pytest
|
||||
|
||||
from lancedb import function, udf
|
||||
from lancedb.functions import FunctionDefinition
|
||||
|
||||
|
||||
def identity(value: int) -> int:
|
||||
return value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"torch>=2.0,,<3",
|
||||
"torch>=",
|
||||
"torch=>2.0",
|
||||
"torch[",
|
||||
"torch; python_version >=",
|
||||
"",
|
||||
" torch",
|
||||
"torch ",
|
||||
],
|
||||
)
|
||||
def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch):
|
||||
def unexpected_packaging(*args, **kwargs):
|
||||
pytest.fail("invalid requirements must fail before packaging the function")
|
||||
|
||||
monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging)
|
||||
with pytest.raises(ValueError) as error:
|
||||
function(pip=["numpy", package])(identity)
|
||||
assert "pip[1]" in str(error.value)
|
||||
assert repr(package) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"numpy>=1,,<3",
|
||||
"numpy>=",
|
||||
"numpy[version=]",
|
||||
"numpy[unknown_field=value]",
|
||||
"",
|
||||
" numpy",
|
||||
"numpy ",
|
||||
],
|
||||
)
|
||||
def test_invalid_conda_requirement_names_entry(package):
|
||||
with pytest.raises(ValueError) as error:
|
||||
function(conda=["scipy", package])(identity)
|
||||
assert "conda[1]" in str(error.value)
|
||||
assert repr(package) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["pip", "conda"])
|
||||
@pytest.mark.parametrize("package", [None, 42, ["numpy"]])
|
||||
def test_requirement_must_be_a_string(kind, package):
|
||||
with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"):
|
||||
function(**{kind: ["numpy", package]})(identity)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"numpy",
|
||||
"torch>=2.0,<3",
|
||||
'requests[security,socks]>=2; python_version >= "3.10"',
|
||||
"numpy (>=1.26, <3)",
|
||||
"six @ https://example.com/six-1.16.0.tar.gz",
|
||||
"six @ git+https://github.com/benjaminp/six.git@main",
|
||||
"https://example.com/six-1.16.0.tar.gz",
|
||||
"git+https://github.com/benjaminp/six.git@main",
|
||||
"git+ssh://git@github.com/benjaminp/six.git@main",
|
||||
],
|
||||
)
|
||||
def test_supported_pip_requirements_are_preserved(package):
|
||||
definition = function(pip=[package])(identity)
|
||||
assert definition.registration_request.runtime.environment.packages == (package,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"package",
|
||||
[
|
||||
"numpy",
|
||||
"numpy=1.26",
|
||||
"numpy>=1.26,<3",
|
||||
"numpy=1.26=py310_0",
|
||||
"numpy 1.26 py310_0",
|
||||
"conda-forge::numpy>=1.26",
|
||||
"conda-forge/linux-64::numpy>=1.26",
|
||||
"numpy[version='>=1.26,<3',build='py310*']",
|
||||
],
|
||||
)
|
||||
def test_supported_conda_requirements_are_preserved(package):
|
||||
definition = function(conda=[package])(identity)
|
||||
assert definition.registration_request.runtime.environment.packages == (package,)
|
||||
|
||||
|
||||
def test_requirements_still_sort_and_deduplicate():
|
||||
definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity)
|
||||
assert definition.registration_request.runtime.environment.packages == (
|
||||
"numpy",
|
||||
"torch>=2",
|
||||
)
|
||||
|
||||
|
||||
def test_deprecated_udf_alias_validates_requirements():
|
||||
with pytest.warns(DeprecationWarning, match="use lancedb.function"):
|
||||
with pytest.raises(ValueError, match=r"pip\[0\]"):
|
||||
udf(pip=["torch>=2.0,,<3"])(identity)
|
||||
|
||||
|
||||
def test_direct_function_definition_validates_requirements():
|
||||
with pytest.raises(ValueError, match=r"pip\[0\]"):
|
||||
FunctionDefinition(
|
||||
identity,
|
||||
name=None,
|
||||
input_schema=None,
|
||||
output_schema=None,
|
||||
pip=("torch>=2.0,,<3",),
|
||||
env={},
|
||||
python_version=None,
|
||||
)
|
||||
@@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable):
|
||||
assert result["_rowid"].to_pylist() == [0, 3]
|
||||
|
||||
|
||||
def test_hybrid_fragment_constraints_fail_loud(sync_table: Table):
|
||||
query = (
|
||||
sync_table.search("dog", query_type="hybrid")
|
||||
.vector([0.5, -0.5])
|
||||
.fragment_ids([0])
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.to_arrow()
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.explain_plan()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable):
|
||||
query = (
|
||||
table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0])
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.to_arrow()
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.analyze_plan()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_hybrid_query_filters(table: AsyncTable):
|
||||
# test that query params are passed down from the regular builder to
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
from datetime import timedelta
|
||||
import random
|
||||
import struct
|
||||
from typing import get_args, get_type_hints
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
import lancedb
|
||||
from lancedb import AsyncConnection, AsyncTable, connect_async
|
||||
from lancedb.index import (
|
||||
BTree,
|
||||
@@ -22,6 +24,9 @@ from lancedb.index import (
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
ZoneMap,
|
||||
RTree,
|
||||
ScalarPlugin,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -88,7 +93,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()
|
||||
@@ -249,6 +254,388 @@ async def test_create_fm_index(some_table: AsyncTable):
|
||||
assert indices[0].columns == ["data"]
|
||||
|
||||
|
||||
POINT_TYPE = pa.struct([("x", pa.float64()), ("y", pa.float64())])
|
||||
POLYGON_TYPE = pa.list_(pa.field("rings", pa.list_(pa.field("vertices", POINT_TYPE))))
|
||||
|
||||
|
||||
def geoarrow_field(name: str, extension: str, data_type: pa.DataType) -> pa.Field:
|
||||
return pa.field(
|
||||
name,
|
||||
data_type,
|
||||
metadata={
|
||||
"ARROW:extension:name": extension,
|
||||
"ARROW:extension:metadata": "{}",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# The triangle's bounding box covers the 25 grid points with x <= 4 and y <= 4,
|
||||
# but only the 15 with x + y <= 4 intersect the triangle itself.
|
||||
TRIANGLE = "ST_GeomFromText('POLYGON ((0 0, 4 0, 0 4, 0 0))')"
|
||||
INTERSECTS_TRIANGLE = f"ST_Intersects(geom, {TRIANGLE})"
|
||||
TRIANGLE_IDS = [10 * y + x for y in range(10) for x in range(10) if x + y <= 4]
|
||||
|
||||
|
||||
def grid_points(nrows: int) -> pa.Table:
|
||||
"""A grid of GeoArrow points in which row ``10 * y + x`` sits at ``(x, y)``."""
|
||||
ids = list(range(nrows))
|
||||
geom = pa.StructArray.from_arrays(
|
||||
[
|
||||
pa.array([float(i % 10) for i in ids]),
|
||||
pa.array([float(i // 10) for i in ids]),
|
||||
],
|
||||
names=["x", "y"],
|
||||
)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
|
||||
pa.field("vector", pa.list_(pa.float32(), DIM)),
|
||||
]
|
||||
)
|
||||
return pa.Table.from_arrays(
|
||||
[pa.array(ids, pa.int64()), geom, sample_fixed_size_list_array(nrows, DIM)],
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def point_table(db_async):
|
||||
return await db_async.create_table("point_table", grid_points(100))
|
||||
|
||||
|
||||
async def query_ids(query) -> list:
|
||||
return (await query.to_arrow())["id"].to_pylist()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_rtree_index(point_table: AsyncTable):
|
||||
assert sorted(await query_ids(point_table.query().where(INTERSECTS_TRIANGLE))) == (
|
||||
TRIANGLE_IDS
|
||||
)
|
||||
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
indices = await point_table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].name == "geom_idx"
|
||||
assert indices[0].index_type == "RTree"
|
||||
assert indices[0].columns == ["geom"]
|
||||
stats = await point_table.index_stats("geom_idx")
|
||||
assert stats.index_type == "RTREE"
|
||||
assert stats.num_indexed_rows == 100
|
||||
assert stats.num_unindexed_rows == 0
|
||||
|
||||
# The index narrows the scan to the bounding box; the exact predicate then
|
||||
# drops the candidates that fall outside the triangle.
|
||||
query = point_table.query().where(INTERSECTS_TRIANGLE)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == TRIANGLE_IDS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"predicate, expected_ids",
|
||||
[
|
||||
(INTERSECTS_TRIANGLE, TRIANGLE_IDS),
|
||||
(f"ST_Within(geom, {TRIANGLE})", [11, 12, 21]),
|
||||
(f"ST_CoveredBy(geom, {TRIANGLE})", TRIANGLE_IDS),
|
||||
(
|
||||
f"ST_Touches(geom, {TRIANGLE})",
|
||||
[0, 1, 2, 3, 4, 10, 13, 20, 22, 30, 31, 40],
|
||||
),
|
||||
(f"ST_Intersects(geom, {TRIANGLE}) AND id > 20", [21, 22, 30, 31, 40]),
|
||||
("ST_Intersects(geom, ST_Point(3.0, 3.0))", [33]),
|
||||
("ST_Contains(geom, ST_Point(3.0, 3.0))", [33]),
|
||||
("ST_Covers(geom, ST_Point(3.0, 3.0))", [33]),
|
||||
],
|
||||
)
|
||||
async def test_rtree_index_accelerates_spatial_filters(
|
||||
point_table: AsyncTable, predicate: str, expected_ids: list
|
||||
):
|
||||
unindexed = sorted(await query_ids(point_table.query().where(predicate)))
|
||||
assert unindexed == expected_ids
|
||||
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
query = point_table.query().where(predicate)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rtree_index_prefilters_vector_search(point_table: AsyncTable):
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Row 99 sits outside the triangle, and its nearest vectors are rows 98, 97, ...
|
||||
far_corner = list(range(99 * DIM, 100 * DIM))
|
||||
|
||||
prefiltered = point_table.query().nearest_to(far_corner).where(INTERSECTS_TRIANGLE)
|
||||
assert "ScalarIndexQuery" in await prefiltered.explain_plan(True)
|
||||
assert await query_ids(prefiltered.limit(5)) == [40, 31, 30, 22, 21]
|
||||
|
||||
postfiltered = (
|
||||
point_table.query()
|
||||
.nearest_to(far_corner)
|
||||
.where(INTERSECTS_TRIANGLE)
|
||||
.postfilter()
|
||||
.limit(5)
|
||||
)
|
||||
assert await query_ids(postfiltered) == []
|
||||
|
||||
|
||||
def square(corner: float) -> list:
|
||||
"""A 2 x 2 square polygon with its lower left corner at ``(corner, corner)``."""
|
||||
ring = [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]
|
||||
return [[{"x": corner + x, "y": corner + y} for x, y in ring]]
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def polygon_table(db_async):
|
||||
"""Ten overlapping squares; row ``i`` covers ``(i, i)`` to ``(i + 2, i + 2)``."""
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("area", "geoarrow.polygon", POLYGON_TYPE),
|
||||
]
|
||||
)
|
||||
data = pa.Table.from_arrays(
|
||||
[
|
||||
pa.array(range(10), pa.int64()),
|
||||
pa.array([square(float(i)) for i in range(10)], POLYGON_TYPE),
|
||||
],
|
||||
schema=schema,
|
||||
)
|
||||
return await db_async.create_table("polygons", data)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"predicate, expected_ids",
|
||||
[
|
||||
("ST_Intersects(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
|
||||
("ST_Contains(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
|
||||
("ST_Covers(area, ST_GeomFromText('POINT (3.5 3.5)'))", [2, 3]),
|
||||
("ST_Crosses(area, ST_GeomFromText('LINESTRING (2.5 2.5, 2.5 10)'))", [1, 2]),
|
||||
(
|
||||
"ST_Overlaps(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
|
||||
[2, 4],
|
||||
),
|
||||
(
|
||||
"ST_Touches(area, ST_GeomFromText('POLYGON ((3 3, 5 3, 5 5, 3 5, 3 3))'))",
|
||||
[1, 5],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_create_rtree_index_on_polygons(
|
||||
polygon_table: AsyncTable, predicate: str, expected_ids: list
|
||||
):
|
||||
assert sorted(await query_ids(polygon_table.query().where(predicate))) == (
|
||||
expected_ids
|
||||
)
|
||||
|
||||
await polygon_table.create_index("area", config=RTree(page_size=2))
|
||||
assert (await polygon_table.list_indices())[0].index_type == "RTree"
|
||||
|
||||
query = polygon_table.query().where(predicate)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rtree_index_with_null_geometries(db_async):
|
||||
# Every third row has no geometry; the others sit on the diagonal at (i, i).
|
||||
geom = pa.array(
|
||||
[None if i % 3 == 0 else {"x": float(i), "y": float(i)} for i in range(10)],
|
||||
POINT_TYPE,
|
||||
)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("geom", "geoarrow.point", POINT_TYPE),
|
||||
]
|
||||
)
|
||||
table = await db_async.create_table(
|
||||
"nulls",
|
||||
pa.Table.from_arrays([pa.array(range(10), pa.int64()), geom], schema=schema),
|
||||
)
|
||||
box = "ST_GeomFromText('POLYGON ((-1 -1, 1.5 -1, 1.5 1.5, -1 1.5, -1 -1))')"
|
||||
expected = {
|
||||
"geom IS NULL": [0, 3, 6, 9],
|
||||
"geom IS NOT NULL": [1, 2, 4, 5, 7, 8],
|
||||
# Row 0 is inside the box but has no geometry, so it matches neither.
|
||||
f"ST_Intersects(geom, {box})": [1],
|
||||
f"NOT ST_Intersects(geom, {box})": [2, 4, 5, 7, 8],
|
||||
}
|
||||
for predicate, ids in expected.items():
|
||||
assert sorted(await query_ids(table.query().where(predicate))) == ids
|
||||
|
||||
await table.create_index("geom", config=RTree())
|
||||
for predicate, ids in expected.items():
|
||||
assert sorted(await query_ids(table.query().where(predicate))) == ids
|
||||
for predicate in ["geom IS NULL", f"ST_Intersects(geom, {box})"]:
|
||||
assert "ScalarIndexQuery" in await table.query().where(predicate).explain_plan(
|
||||
True
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_rtree_index_on_wkb(db_async):
|
||||
"""GeoParquet and GeoPandas data usually arrives as well-known binary."""
|
||||
|
||||
def wkb_point(x: float, y: float) -> bytes:
|
||||
# Byte order (1 = little endian), geometry type (1 = point), x, y.
|
||||
return struct.pack("<BIdd", 1, 1, x, y)
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
geoarrow_field("geom", "geoarrow.wkb", pa.binary()),
|
||||
]
|
||||
)
|
||||
data = pa.Table.from_arrays(
|
||||
[
|
||||
pa.array(range(100), pa.int64()),
|
||||
pa.array([wkb_point(i % 10, i // 10) for i in range(100)], pa.binary()),
|
||||
],
|
||||
schema=schema,
|
||||
)
|
||||
table = await db_async.create_table("wkb", data)
|
||||
assert sorted(await query_ids(table.query().where(INTERSECTS_TRIANGLE))) == (
|
||||
TRIANGLE_IDS
|
||||
)
|
||||
|
||||
await table.create_index("geom", config=RTree())
|
||||
query = table.query().where(INTERSECTS_TRIANGLE)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == TRIANGLE_IDS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rtree_index_after_append_and_optimize(point_table: AsyncTable):
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Rows 100..199 continue the grid above the first one, at y = 10..19.
|
||||
await point_table.add(grid_points(200).slice(100))
|
||||
across_both = (
|
||||
"ST_Intersects(geom, ST_GeomFromText('POLYGON ((0 9, 2 9, 2 11, 0 11, 0 9))'))"
|
||||
)
|
||||
expected = [90, 91, 92, 100, 101, 102, 110, 111, 112]
|
||||
|
||||
stats = await point_table.index_stats("geom_idx")
|
||||
assert stats is not None
|
||||
assert (stats.num_indexed_rows, stats.num_unindexed_rows) == (100, 100)
|
||||
assert sorted(await query_ids(point_table.query().where(across_both))) == expected
|
||||
|
||||
await point_table.optimize()
|
||||
stats = await point_table.index_stats("geom_idx")
|
||||
assert stats is not None
|
||||
assert (stats.num_indexed_rows, stats.num_unindexed_rows) == (200, 0)
|
||||
query = point_table.query().where(across_both)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
assert sorted(await query_ids(query)) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_geoarrow_column_round_trips(point_table: AsyncTable):
|
||||
"""Enabling geo support must not change how GeoArrow columns are stored or read."""
|
||||
expected = grid_points(100)
|
||||
schema = await point_table.schema()
|
||||
assert schema.field("geom").metadata == expected.schema.field("geom").metadata
|
||||
assert schema.field("geom").type == POINT_TYPE
|
||||
|
||||
data = (await point_table.query().to_arrow()).sort_by("id")
|
||||
assert data["geom"].to_pylist() == expected["geom"].to_pylist()
|
||||
assert sorted(await query_ids(point_table.query().where("id < 3"))) == [0, 1, 2]
|
||||
|
||||
|
||||
# Asymmetric predicates with the constant geometry first. GeoDataFusion once
|
||||
# evaluated these with the arguments swapped, so a write filter silently matched
|
||||
# the wrong rows. Only the three interior points are contained, the boundary
|
||||
# points are also covered, and no point contains or covers the triangle.
|
||||
CONSTANT_FIRST_CASES = [
|
||||
(f"ST_Contains({TRIANGLE}, geom)", [11, 12, 21]),
|
||||
(f"ST_Covers({TRIANGLE}, geom)", TRIANGLE_IDS),
|
||||
(f"ST_Within({TRIANGLE}, geom)", []),
|
||||
(f"ST_CoveredBy({TRIANGLE}, geom)", []),
|
||||
(f"ST_Intersects({TRIANGLE}, geom)", TRIANGLE_IDS),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
|
||||
async def test_spatial_filter_constant_first(
|
||||
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
|
||||
):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
query = point_table.query().where(predicate)
|
||||
assert sorted(await query_ids(query)) == expected_ids
|
||||
if indexed:
|
||||
assert "ScalarIndexQuery" in await query.explain_plan(True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
|
||||
async def test_delete_with_constant_first_spatial_filter(
|
||||
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
|
||||
):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Delete every row the predicate rejects; exactly the matching rows survive.
|
||||
await point_table.delete(f"NOT {predicate}")
|
||||
assert sorted(await query_ids(point_table.query())) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("predicate, expected_ids", CONSTANT_FIRST_CASES)
|
||||
async def test_update_with_constant_first_spatial_filter(
|
||||
point_table: AsyncTable, indexed: bool, predicate: str, expected_ids: list
|
||||
):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
# Map each matching id to a negative one (-id - 1 keeps row 0 distinct).
|
||||
await point_table.update(updates_sql={"id": "-id - 1"}, where=predicate)
|
||||
updated = await query_ids(point_table.query().where("id < 0"))
|
||||
assert sorted(-new_id - 1 for new_id in updated) == expected_ids
|
||||
assert await point_table.count_rows() == 100
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
async def test_spatial_filter_with_null_constant(point_table: AsyncTable, indexed):
|
||||
if indexed:
|
||||
await point_table.create_index("geom", config=RTree())
|
||||
null_geometry = "ST_GeomFromText(CAST(NULL AS VARCHAR))"
|
||||
for predicate in [
|
||||
f"ST_Intersects(geom, {null_geometry})",
|
||||
f"ST_Within(geom, {null_geometry})",
|
||||
]:
|
||||
assert await query_ids(point_table.query().where(predicate)) == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_rtree_index_rejects_invalid_input(point_table: AsyncTable):
|
||||
with pytest.raises(ValueError, match="page_size must be at least 2"):
|
||||
await point_table.create_index("geom", config=RTree(page_size=1))
|
||||
# Only the message is part of the contract, not the exception type.
|
||||
with pytest.raises(Exception, match="GeoArrow"):
|
||||
await point_table.create_index("id", config=RTree())
|
||||
assert await point_table.list_indices() == []
|
||||
|
||||
|
||||
def test_create_rtree_index_sync(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("points", grid_points(100))
|
||||
table.create_index("geom", config=RTree())
|
||||
assert [index.index_type for index in table.list_indices()] == ["RTree"]
|
||||
table.create_index("geom", config=RTree(page_size=16), name="geom_rtree")
|
||||
assert table.index_stats("geom_rtree").index_type == "RTREE"
|
||||
|
||||
query = table.search().where(INTERSECTS_TRIANGLE).limit(100)
|
||||
assert "ScalarIndexQuery" in query.explain_plan(True)
|
||||
assert sorted(query.to_arrow()["id"].to_pylist()) == TRIANGLE_IDS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_ngram_index(db_async):
|
||||
# NGram indexes accelerate substring filters on UTF-8 string columns.
|
||||
@@ -279,6 +666,154 @@ async def test_create_ngram_index(db_async):
|
||||
assert "ScalarIndexQuery" in plan
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_zonemap_index(db_async):
|
||||
# ZoneMap indexes accelerate range and equality filters on ordered columns.
|
||||
data = pa.table(
|
||||
{
|
||||
"id": list(range(100)),
|
||||
"value": list(range(100)),
|
||||
}
|
||||
)
|
||||
table = await db_async.create_table("zonemap_table", data)
|
||||
await table.create_index("value", config=ZoneMap())
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].index_type == "ZoneMap"
|
||||
assert indices[0].columns == ["value"]
|
||||
|
||||
# The index narrows a range scan without changing its results.
|
||||
result = await table.query().where("value >= 90").to_arrow()
|
||||
assert sorted(result["id"].to_pylist()) == list(range(90, 100))
|
||||
|
||||
|
||||
def plugin_table_data():
|
||||
return pa.table(
|
||||
{"id": [1, 2, 3, 4], "text": ["abc", "xyz", None, ""]},
|
||||
schema=pa.schema([("id", pa.int32()), ("text", pa.string())]),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"index_type, params, column, expected_type, predicate, expected_ids",
|
||||
[
|
||||
("ZoneMap", None, "id", "ZoneMap", "id >= 2 AND id < 4", [2, 3]),
|
||||
(" BTREE ", None, "id", "BTree", "id = 3", [3]),
|
||||
(
|
||||
"bloomfilter",
|
||||
{"number_of_items": 2, "probability": 0.01},
|
||||
"text",
|
||||
"BloomFilter",
|
||||
"text = 'abc'",
|
||||
[1],
|
||||
),
|
||||
(
|
||||
"BloomFilter",
|
||||
'{"number_of_items": 2}',
|
||||
"text",
|
||||
"BloomFilter",
|
||||
"text = 'abc'",
|
||||
[1],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_create_scalar_plugin_index(
|
||||
db_async, index_type, params, column, expected_type, predicate, expected_ids
|
||||
):
|
||||
# Lance's built-in plugins, created by name, are listed with the same type
|
||||
# as their dedicated configs and serve the filters those configs serve.
|
||||
table = await db_async.create_table("plugin_table", plugin_table_data())
|
||||
config = ScalarPlugin(index_type, params)
|
||||
await table.create_index(column, config=config, name="plugin_idx")
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert [(i.name, i.index_type, i.columns) for i in indices] == [
|
||||
("plugin_idx", expected_type, [column])
|
||||
]
|
||||
stats = await table.index_stats("plugin_idx")
|
||||
assert stats.num_indexed_rows == 4
|
||||
|
||||
query = table.query().where(predicate)
|
||||
assert "ScalarIndexQuery" in await query.explain_plan()
|
||||
result = await query.to_arrow()
|
||||
assert sorted(result["id"].to_pylist()) == expected_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scalar_plugin_without_lancedb_type_lists_plugin_name(db_async):
|
||||
data = pa.table({"text": ["alpha beta", "beta gamma", "gamma delta"]})
|
||||
table = await db_async.create_table("minhash_table", data)
|
||||
await table.create_index("text", config=ScalarPlugin("minhashlsh"))
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].index_type == "MinHashLsh"
|
||||
assert 'index_type="MinHashLsh"' in repr(indices[0])
|
||||
stats = await table.index_stats(indices[0].name)
|
||||
assert stats.index_type == "MinHashLsh"
|
||||
|
||||
|
||||
def test_scalar_plugin_sync_table_and_job(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("plugin_table", plugin_table_data())
|
||||
|
||||
table.create_index("id", config=ScalarPlugin("zonemap"))
|
||||
job = table.create_index_async(
|
||||
"text",
|
||||
config=ScalarPlugin("bloomfilter", {"probability": 0.01}),
|
||||
name="text_bloom",
|
||||
)
|
||||
job.wait()
|
||||
|
||||
types = {index.name: index.index_type for index in table.list_indices()}
|
||||
assert types == {"id_idx": "ZoneMap", "text_bloom": "BloomFilter"}
|
||||
assert "ScalarIndexQuery" in table.search().where("text = 'abc'").explain_plan()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs, error, match",
|
||||
[
|
||||
({"index_type": ""}, ValueError, "must not be empty"),
|
||||
({"index_type": " "}, ValueError, "must not be empty"),
|
||||
({"index_type": None}, TypeError, "index_type must be a str"),
|
||||
({"index_type": "zonemap", "params": "[1]"}, ValueError, "got list"),
|
||||
({"index_type": "zonemap", "params": "null"}, ValueError, "got NoneType"),
|
||||
({"index_type": "zonemap", "params": "{x"}, ValueError, "not valid JSON"),
|
||||
({"index_type": "zonemap", "params": [1]}, TypeError, "got list"),
|
||||
({"index_type": "zonemap", "params": 1}, TypeError, "got int"),
|
||||
],
|
||||
)
|
||||
def test_scalar_plugin_rejects_invalid_config(kwargs, error, match):
|
||||
with pytest.raises(error, match=match):
|
||||
ScalarPlugin(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scalar_plugin_errors_reach_the_caller(db_async):
|
||||
table = await db_async.create_table("plugin_table", plugin_table_data())
|
||||
|
||||
# The native layer checks the params again, after the dataclass is mutated.
|
||||
config = ScalarPlugin("zonemap")
|
||||
config.params = "[1]"
|
||||
with pytest.raises(ValueError, match="must be a JSON object, got an array"):
|
||||
await table.create_index("id", config=config)
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="No scalar index plugin found for name 'nosuchplugin'"
|
||||
):
|
||||
await table.create_index("id", config=ScalarPlugin("NoSuchPlugin"))
|
||||
with pytest.raises(ValueError, match="ngram index can only be created on a Utf8"):
|
||||
await table.create_index("id", config=ScalarPlugin("ngram"))
|
||||
with pytest.raises(RuntimeError, match='invalid type: string "many"'):
|
||||
await table.create_index(
|
||||
"text",
|
||||
config=ScalarPlugin("bloomfilter", {"number_of_items": "many"}),
|
||||
)
|
||||
assert await table.list_indices() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bitmap_index(some_table: AsyncTable):
|
||||
await some_table.create_index("id", config=Bitmap())
|
||||
@@ -591,9 +1126,53 @@ def test_index_statistics_index_type_lists_all_supported_values():
|
||||
"BITMAP",
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
"ZONEMAP",
|
||||
"RTREE",
|
||||
}
|
||||
|
||||
assert (
|
||||
set(get_args(get_type_hints(IndexStatistics)["index_type"]))
|
||||
== expected_index_types
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))]
|
||||
)
|
||||
async def test_index_exist_ok_preserves_existing_index(
|
||||
some_table, background, column, config
|
||||
):
|
||||
await some_table.create_index(column, config=config, exist_ok=True)
|
||||
version = await some_table.version()
|
||||
original = await some_table.list_indices()
|
||||
if background:
|
||||
job = await some_table.create_index_async(
|
||||
column, config=config, replace=True, exist_ok=True
|
||||
)
|
||||
await job.wait()
|
||||
else:
|
||||
await some_table.create_index(
|
||||
column, config=config, replace=True, exist_ok=True
|
||||
)
|
||||
assert await some_table.version() == version
|
||||
assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [
|
||||
(i.name, i.index_type) for i in original
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
async def test_named_index_exist_ok_checks_before_column_validation(
|
||||
some_table, background
|
||||
):
|
||||
await some_table.create_index("id", config=BTree(), name="kept")
|
||||
version = await some_table.version()
|
||||
method = some_table.create_index_async if background else some_table.create_index
|
||||
result = await method("missing", config=BTree(), name="kept", exist_ok=True)
|
||||
if background:
|
||||
assert result.id() is None
|
||||
await result.wait()
|
||||
assert await some_table.version() == version
|
||||
assert [index.name for index in await some_table.list_indices()] == ["kept"]
|
||||
|
||||
@@ -2,17 +2,253 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
|
||||
from lancedb.exceptions import JobCancelledError, JobFailedError
|
||||
from lancedb.job import AsyncJob, Job, _progress_eta
|
||||
from lancedb.db import DBConnection
|
||||
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}
|
||||
result = {"rows_computed": 7, "details": [{"data": b"x" * 10000}] * 1000}
|
||||
inner = SimpleNamespace(
|
||||
id="job-repr",
|
||||
_state="failed",
|
||||
job_type="function_refresh",
|
||||
_description=SimpleNamespace(
|
||||
creation_ms=2000,
|
||||
spec=spec,
|
||||
result=result,
|
||||
failure="worker failed " + "x" * 10000,
|
||||
),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
if sync:
|
||||
job = Job(job)
|
||||
rendered = repr(job)
|
||||
assert len(rendered) < 1600
|
||||
assert len(rendered.splitlines()) <= 10
|
||||
assert "id='job-repr'" in rendered
|
||||
assert "state='failed'" in rendered
|
||||
assert "job_type='function_refresh'" in rendered
|
||||
assert "rows_computed" in rendered
|
||||
assert "worker failed" in rendered
|
||||
assert "..." in rendered
|
||||
assert len(repr(job.status)) < 1700
|
||||
assert job.spec() is spec
|
||||
assert job.result() is result
|
||||
assert len(job.spec()["initialization"]) == 100000
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
def test_job_repr_handles_unobserved_and_local_jobs(sync):
|
||||
unobserved = AsyncJob(SimpleNamespace(id="job-pending", _state=None))
|
||||
local = AsyncJob(None)
|
||||
if sync:
|
||||
unobserved, local = Job(unobserved), Job(local)
|
||||
assert "id='job-pending', not refreshed" in repr(unobserved)
|
||||
assert "state='finished'" in repr(local)
|
||||
assert "failure=" not in repr(local)
|
||||
|
||||
|
||||
@pytest.fixture(params=["async", "sync"])
|
||||
def wait_job(request):
|
||||
async def wait(inner, timeout=None, result_decoder=None):
|
||||
@@ -683,15 +919,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
|
||||
@pytest.mark.parametrize("progress", [False, None])
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
|
||||
class NoProgressArgument:
|
||||
id = "job-legacy"
|
||||
job_type = None
|
||||
|
||||
@property
|
||||
def job_type(self):
|
||||
raise AssertionError("quiet waits must not inspect progress metadata")
|
||||
|
||||
async def wait(self):
|
||||
return None
|
||||
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
|
||||
|
||||
|
||||
class _RegistrationQuery:
|
||||
id = "registration-query"
|
||||
job_type = "query"
|
||||
_description = None
|
||||
|
||||
def __init__(self, error=None):
|
||||
self.ready = asyncio.Event()
|
||||
self.error = error
|
||||
self.state = "running"
|
||||
self.wait_calls = 0
|
||||
self.cancel_calls = 0
|
||||
|
||||
async def status(self):
|
||||
return self.state
|
||||
|
||||
async def wait(self, progress=None):
|
||||
self.wait_calls += 1
|
||||
await self.ready.wait()
|
||||
if self.error is not None:
|
||||
self.state = (
|
||||
"cancelled" if isinstance(self.error, JobCancelledError) else "failed"
|
||||
)
|
||||
raise self.error
|
||||
self.state = "finished"
|
||||
return '{"version": "1"}'
|
||||
|
||||
async def cancel(self):
|
||||
self.cancel_calls += 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
|
||||
monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
|
||||
inner = _RegistrationQuery()
|
||||
job = AsyncJob(inner, json.loads)
|
||||
updates = []
|
||||
|
||||
def observe(snapshot):
|
||||
updates.append(snapshot)
|
||||
if len(updates) == 2:
|
||||
inner.ready.set()
|
||||
|
||||
if sync:
|
||||
result = await asyncio.to_thread(Job(job).wait, progress=observe)
|
||||
else:
|
||||
result = await job.wait(progress=observe)
|
||||
assert result == {"version": "1"}
|
||||
assert inner.wait_calls == 1
|
||||
assert inner.cancel_calls == 0
|
||||
assert updates[0]["state"] == "running"
|
||||
assert updates[-1]["state"] == "finished"
|
||||
assert all(snapshot["job_id"] == inner.id for snapshot in updates)
|
||||
elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
|
||||
assert elapsed == sorted(elapsed)
|
||||
assert elapsed[0] >= 0
|
||||
assert all("phase" not in snapshot for snapshot in updates)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
JobFailedError("bake failed", job_id="registration-query"),
|
||||
JobCancelledError("cancelled"),
|
||||
],
|
||||
)
|
||||
async def test_query_progress_preserves_terminal_exceptions(error):
|
||||
inner = _RegistrationQuery(error)
|
||||
inner.ready.set()
|
||||
updates = []
|
||||
with pytest.raises(type(error)) as raised:
|
||||
await AsyncJob(inner).wait(progress=updates.append)
|
||||
assert raised.value is error
|
||||
assert updates[-1]["state"] == inner.state
|
||||
assert inner.wait_calls == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
|
||||
monkeypatch,
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
bar = SimpleNamespace(
|
||||
n=0,
|
||||
total=None,
|
||||
update=MagicMock(),
|
||||
set_postfix_str=MagicMock(),
|
||||
close=MagicMock(),
|
||||
)
|
||||
constructor = MagicMock(return_value=bar)
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", constructor)
|
||||
inner = _RegistrationQuery(JobFailedError("bake failed"))
|
||||
inner.ready.set()
|
||||
|
||||
with pytest.raises(JobFailedError, match="bake failed"):
|
||||
await AsyncJob(inner).wait(progress=True)
|
||||
assert "elapsed" in constructor.call_args.kwargs["bar_format"]
|
||||
assert "rows" not in str(constructor.call_args)
|
||||
assert bar.set_postfix_str.call_args.args == ("failed",)
|
||||
bar.close.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failed", [False, True])
|
||||
@pytest.mark.parametrize("observer_error", ["status", "callback"])
|
||||
async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
|
||||
failed, observer_error, caplog
|
||||
):
|
||||
error = (
|
||||
JobFailedError("bake failed", job_id="registration-query") if failed else None
|
||||
)
|
||||
inner = _RegistrationQuery(error)
|
||||
inner.ready.set()
|
||||
if observer_error == "status":
|
||||
inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
|
||||
|
||||
def observe(snapshot):
|
||||
if observer_error == "callback":
|
||||
raise RuntimeError("observer failed")
|
||||
|
||||
job = AsyncJob(inner, json.loads)
|
||||
if failed:
|
||||
with pytest.raises(JobFailedError) as raised:
|
||||
await job.wait(progress=observe)
|
||||
assert raised.value is error
|
||||
else:
|
||||
assert await job.wait(progress=observe) == {"version": "1"}
|
||||
assert inner.wait_calls == 1
|
||||
assert inner.cancel_calls == 0
|
||||
assert "job progress observer failed" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
|
||||
inner = _RegistrationQuery()
|
||||
job = AsyncJob(inner, json.loads)
|
||||
updates = []
|
||||
with pytest.raises(TimeoutError, match="keep this handle"):
|
||||
await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
|
||||
assert inner.state == "running"
|
||||
assert inner.cancel_calls == 0
|
||||
inner.ready.set()
|
||||
assert await job.wait(progress=updates.append) == {"version": "1"}
|
||||
assert inner.wait_calls == 2
|
||||
assert updates[-1]["state"] == "finished"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("refresh_lock", [False, True])
|
||||
def test_blocking_create_function_forwards_progress_to_registration_handle(
|
||||
refresh_lock,
|
||||
):
|
||||
connection = MagicMock()
|
||||
definition = object()
|
||||
progress = object()
|
||||
result = DBConnection.create_function(
|
||||
connection, definition, refresh_lock=refresh_lock, progress=progress
|
||||
)
|
||||
connection.create_function_async.assert_called_once_with(
|
||||
definition,
|
||||
secrets=None,
|
||||
exist_ok=False,
|
||||
namespace_path=None,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
connection.create_function_async.return_value.wait.assert_called_once_with(
|
||||
progress=progress
|
||||
)
|
||||
assert result is connection.create_function_async.return_value.wait.return_value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("progress", [False, None])
|
||||
def test_blocking_create_function_preserves_quiet_wait_call(progress):
|
||||
connection = MagicMock()
|
||||
result = DBConnection.create_function(connection, object(), progress=progress)
|
||||
connection.create_function_async.return_value.wait.assert_called_once_with()
|
||||
assert result is connection.create_function_async.return_value.wait.return_value
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -706,3 +1125,298 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
|
||||
assert "continues on the server" in message
|
||||
assert "keep this handle to continue waiting" in message
|
||||
assert "db.open_job" not in message
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys):
|
||||
reports = [
|
||||
None,
|
||||
"Function job: finished\nWorker utilization: unavailable\n",
|
||||
"Function job: finished\nWorker utilization: 25.0%\n",
|
||||
]
|
||||
inner = SimpleNamespace(
|
||||
stats=AsyncMock(side_effect=reports),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
for expected in reports:
|
||||
actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats()
|
||||
assert actual == expected
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
assert capsys.readouterr().out == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync):
|
||||
error = RuntimeError("run reports are unavailable on this server")
|
||||
job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error)))
|
||||
with pytest.raises(RuntimeError) as exc:
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).stats)
|
||||
else:
|
||||
await job.stats()
|
||||
assert exc.value is error
|
||||
with pytest.raises(NotImplementedError, match="server-side Function job"):
|
||||
if sync:
|
||||
Job(None).stats()
|
||||
else:
|
||||
await AsyncJob(None).stats()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path):
|
||||
trace = {
|
||||
"traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}],
|
||||
"metadata": {"partial": True},
|
||||
}
|
||||
inner = SimpleNamespace(
|
||||
timeline=AsyncMock(return_value=json.dumps(trace)),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
path = tmp_path / "job.trace.json"
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).export_timeline, str(path))
|
||||
else:
|
||||
await job.export_timeline(path)
|
||||
assert json.loads(path.read_text()) == trace
|
||||
inner.timeline.assert_awaited_once_with()
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_timeline_failure_preserves_existing_file(tmp_path):
|
||||
path = tmp_path / "job.trace.json"
|
||||
path.write_text("previous recording")
|
||||
job = AsyncJob(
|
||||
SimpleNamespace(
|
||||
timeline=AsyncMock(side_effect=RuntimeError("unsupported server"))
|
||||
)
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="unsupported server"):
|
||||
await job.export_timeline(path)
|
||||
assert path.read_text() == "previous recording"
|
||||
with pytest.raises(NotImplementedError, match="server-side Function job"):
|
||||
await AsyncJob(None).export_timeline(path)
|
||||
with pytest.raises(NotImplementedError, match="server-side Function job"):
|
||||
Job(None).export_timeline(path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_export_timeline_reports_filesystem_errors(tmp_path):
|
||||
job = AsyncJob(
|
||||
SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}'))
|
||||
)
|
||||
with pytest.raises(FileNotFoundError):
|
||||
await job.export_timeline(tmp_path / "missing" / "trace.json")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stack_preserves_evidence_and_does_not_wait(sync):
|
||||
evidence = {
|
||||
"worker_id": "worker",
|
||||
"status": "unavailable",
|
||||
"execution_epoch": 1,
|
||||
"stacks": [],
|
||||
"omitted_sessions": 0,
|
||||
}
|
||||
inner = SimpleNamespace(
|
||||
stack=AsyncMock(return_value=json.dumps(evidence)),
|
||||
wait=AsyncMock(),
|
||||
cancel=AsyncMock(),
|
||||
)
|
||||
job = AsyncJob(inner)
|
||||
actual = (
|
||||
await asyncio.to_thread(Job(job).stack, "worker")
|
||||
if sync
|
||||
else await job.stack("worker")
|
||||
)
|
||||
assert actual == evidence
|
||||
inner.stack.assert_awaited_once_with("worker")
|
||||
inner.wait.assert_not_awaited()
|
||||
inner.cancel.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_stack_propagates_errors_and_rejects_local_handles(sync):
|
||||
error = RuntimeError("system operate privilege required")
|
||||
job = AsyncJob(SimpleNamespace(stack=AsyncMock(side_effect=error)))
|
||||
with pytest.raises(RuntimeError) as failure:
|
||||
if sync:
|
||||
await asyncio.to_thread(Job(job).stack, "worker")
|
||||
else:
|
||||
await job.stack("worker")
|
||||
assert failure.value is error
|
||||
with pytest.raises(NotImplementedError):
|
||||
if sync:
|
||||
Job(None).stack("worker")
|
||||
else:
|
||||
await AsyncJob(None).stack("worker")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"kind,planned_key,completed_key,unit",
|
||||
[
|
||||
("compact", "rows_planned", "rows_rewritten", " rows"),
|
||||
(
|
||||
"prewarm_page_cache",
|
||||
"executors_targeted",
|
||||
"executors_completed",
|
||||
" executors",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_maintenance_progress_bar_uses_operation_counters_and_handles_retry(
|
||||
monkeypatch, kind, planned_key, completed_key, unit
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
total = None
|
||||
n = 0
|
||||
unit = " rows"
|
||||
closed = False
|
||||
|
||||
def update(self, delta):
|
||||
self.n += delta
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
class MaintenanceJob:
|
||||
id = "maintenance-job"
|
||||
job_type = kind
|
||||
|
||||
async def wait(self, progress):
|
||||
progress({"job_type": kind, "phase": "planning"})
|
||||
assert bar.total is None
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 2})
|
||||
assert bar.n == 2
|
||||
# Older responses can omit an epoch; revised observations still
|
||||
# replace the previous attempt's displayed work.
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 1})
|
||||
assert bar.n == 1
|
||||
progress({"job_type": kind, planned_key: 4, completed_key: 4})
|
||||
|
||||
assert await AsyncJob(MaintenanceJob()).wait(progress=True) is None
|
||||
assert bar.n == 4
|
||||
assert bar.total == 4
|
||||
assert bar.unit == unit
|
||||
assert bar.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("known_empty", [False, True])
|
||||
async def test_prewarm_progress_bar_preserves_unknown_and_zero_totals(
|
||||
monkeypatch, known_empty
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
total = None
|
||||
n = 0
|
||||
unit = " rows"
|
||||
|
||||
def update(self, delta):
|
||||
self.n += delta
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
class PrewarmJob:
|
||||
id = "prewarm-job"
|
||||
job_type = "prewarm_page_cache"
|
||||
|
||||
async def wait(self, progress):
|
||||
snapshot = {"job_type": self.job_type, "phase": "succeeded"}
|
||||
if known_empty:
|
||||
snapshot.update(executors_targeted=0, executors_completed=0)
|
||||
progress(snapshot)
|
||||
|
||||
assert await AsyncJob(PrewarmJob()).wait(progress=True) is None
|
||||
assert bar.n == 0
|
||||
assert bar.total == (0 if known_empty else None)
|
||||
assert bar.unit == " executors"
|
||||
|
||||
|
||||
@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.args == error.args
|
||||
# On Python 3.11 and 3.12, run_coroutine_threadsafe re-creates TimeoutError
|
||||
# when copying it across futures, so identity only holds on the async path.
|
||||
if not sync:
|
||||
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)
|
||||
|
||||
@@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
|
||||
if kind == "jobs":
|
||||
assert verb == "POST"
|
||||
assert path.path == "/v1/jobs/list"
|
||||
assert body == {"page_token": token, "limit": 2}
|
||||
assert body == {"database": "dev", "page_token": token, "limit": 2}
|
||||
else:
|
||||
namespace = "team"
|
||||
resource = kind.removesuffix("s")
|
||||
@@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l
|
||||
with pytest.raises(ValueError, match="limit"):
|
||||
await items.__anext__()
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [[], ["team", "project"]])
|
||||
@pytest.mark.parametrize("multiple_types", [False, True])
|
||||
async def test_job_filters_persist_across_pages_and_resume(
|
||||
listing_server, asynchronous, namespace, multiple_types
|
||||
):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)]
|
||||
)
|
||||
db = await connection(endpoint, asynchronous)
|
||||
types = ["column_refresh", "materialized_view_refresh"]
|
||||
filters = dict(
|
||||
table="events",
|
||||
namespace_path=namespace,
|
||||
state="in_progress",
|
||||
created_at_gte_millis=100,
|
||||
created_at_lt_millis=200,
|
||||
**({"job_types": types} if multiple_types else {"job_type": types[0]}),
|
||||
)
|
||||
items = db.list_jobs(page_limit=1, **filters)
|
||||
assert requests == []
|
||||
assert (await advance(items, asynchronous)).job_id == "a"
|
||||
assert len(requests) == 1
|
||||
resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters)
|
||||
assert (await advance(resumed, asynchronous)).job_id == "b"
|
||||
assert resumed.page_token() is None
|
||||
assert len(requests) == 3
|
||||
expected = dict(
|
||||
database="dev",
|
||||
limit=1,
|
||||
table_ref={
|
||||
"db_name": "dev",
|
||||
"table_id": {"namespace_path": namespace, "table_name": "events"},
|
||||
},
|
||||
state="in_progress",
|
||||
job_types=types if multiple_types else types[:1],
|
||||
created_at_gte_millis=100,
|
||||
created_at_lt_millis=200,
|
||||
)
|
||||
for (_, path, body), token in zip(requests, [None, "empty", "last"]):
|
||||
assert path == "/v1/jobs/list"
|
||||
assert body == {**expected, **({"page_token": token} if token else {})}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"filters",
|
||||
[
|
||||
{},
|
||||
{"state": "failed"},
|
||||
{"job_types": ["column_refresh"]},
|
||||
{"created_at_lt_millis": 200},
|
||||
],
|
||||
)
|
||||
async def test_job_listing_without_table_stays_in_connected_database(
|
||||
listing_server, asynchronous, filters
|
||||
):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.append((200, response_page("jobs", ["a"], None)))
|
||||
db = await connection(endpoint, asynchronous)
|
||||
items = db.list_jobs(**filters)
|
||||
assert (await advance(items, asynchronous)).job_id == "a"
|
||||
assert requests[0][2] == {"database": "dev", **filters}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"filters, message",
|
||||
[
|
||||
({"namespace_path": ["team"]}, "requires a table"),
|
||||
({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"),
|
||||
({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"),
|
||||
({"job_type": "column_refresh", "job_types": []}, "only one"),
|
||||
({"state": "unknown"}, "state must be"),
|
||||
],
|
||||
)
|
||||
async def test_invalid_job_filters_do_not_fetch(
|
||||
listing_server, asynchronous, filters, message
|
||||
):
|
||||
endpoint, requests, _ = listing_server
|
||||
db = await connection(endpoint, asynchronous)
|
||||
with pytest.raises(ValueError, match=message):
|
||||
items = db.list_jobs(**filters)
|
||||
await advance(items, asynchronous)
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a", "b"], "second"), (["c", "d"], "last")]
|
||||
)
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(table="events", page_limit=2)
|
||||
assert items[:0] == []
|
||||
assert items[5:2] == []
|
||||
assert requests == []
|
||||
assert [job.job_id for job in items[:2]] == ["a", "b"]
|
||||
assert len(requests) == 1
|
||||
assert items.num_page_results() == 2
|
||||
assert items.page_token() == "second"
|
||||
assert items[1].job_id == "b"
|
||||
assert next(items).job_id == "a"
|
||||
assert [job.job_id for job in items[:2]] == ["b", "c"]
|
||||
assert len(requests) == 2
|
||||
assert items.num_page_results() == 3
|
||||
assert items.page_token() == "last"
|
||||
assert [job.job_id for job in items[0:3:2][:1]] == ["b"]
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_length_and_slices_preserve_remaining_items(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)]
|
||||
)
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(page_limit=2)
|
||||
assert bool(items)
|
||||
assert len(requests) == 1
|
||||
assert next(items).job_id == "a"
|
||||
assert len(items) == 3
|
||||
assert len(requests) == 3
|
||||
assert items.num_page_results() == 3
|
||||
assert items.page_token() is None
|
||||
assert items[-1].job_id == "d"
|
||||
assert [job.job_id for job in items[::-1]] == ["d", "c", "b"]
|
||||
assert [job.job_id for job in items[1:]] == ["c", "d"]
|
||||
assert [job.job_id for job in items[:100:2]] == ["b", "d"]
|
||||
assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"]
|
||||
with pytest.raises(IndexError):
|
||||
_ = items[3]
|
||||
assert [job.job_id for job in items] == ["b", "c", "d"]
|
||||
assert len(items) == 0
|
||||
assert not items
|
||||
assert len(requests) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_invalid_slice_does_not_fetch(listing_server):
|
||||
endpoint, requests, _ = listing_server
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs()
|
||||
with pytest.raises(ValueError, match="step"):
|
||||
_ = items[::0]
|
||||
with pytest.raises(TypeError):
|
||||
_ = items["invalid"]
|
||||
with pytest.raises(TypeError):
|
||||
_ = items[:1.5]
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})])
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(page_limit=2)
|
||||
with pytest.raises(HttpError):
|
||||
_ = items[:3]
|
||||
assert items.page_token() == "retry"
|
||||
assert items.num_page_results() == 2
|
||||
assert [job.job_id for job in items[:2]] == ["a", "b"]
|
||||
assert [job.job_id for job in items] == ["a", "b"]
|
||||
assert len(requests) == 2
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [False, True])
|
||||
@pytest.mark.parametrize("defining_query", [False, True])
|
||||
async def test_exist_ok_preserves_materialized_data(
|
||||
tmp_path, asynchronous, background, namespace, defining_query
|
||||
):
|
||||
source_args = (
|
||||
{"query": "SELECT * FROM source"} if defining_query else {"source": "source"}
|
||||
)
|
||||
replacement_args = {
|
||||
**(
|
||||
{"query": "SELECT * FROM missing"}
|
||||
if defining_query
|
||||
else {"source": "missing"}
|
||||
),
|
||||
"auto_refresh_enabled": True,
|
||||
"auto_refresh_interval_seconds": 1,
|
||||
}
|
||||
options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}}
|
||||
if asynchronous:
|
||||
db = (
|
||||
lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options)
|
||||
if namespace
|
||||
else await lancedb.connect_async(tmp_path, **options)
|
||||
)
|
||||
source = await db.create_table("source", [{"id": 1}])
|
||||
original = await db.create_materialized_view(
|
||||
"saved", **source_args, exist_ok=True
|
||||
)
|
||||
definition = await original.definition()
|
||||
version = await original.table.version()
|
||||
await source.add([{"id": 2}])
|
||||
if background:
|
||||
job = await db.create_materialized_view_async(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
await job.wait()
|
||||
kept = await db.open_materialized_view("saved")
|
||||
else:
|
||||
kept = await db.create_materialized_view(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
assert (await kept.definition()).query == definition.query
|
||||
assert await kept.table.version() == version
|
||||
assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}]
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
await db.create_materialized_view("saved", **source_args)
|
||||
else:
|
||||
db = (
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options)
|
||||
if namespace
|
||||
else lancedb.connect(tmp_path, **options)
|
||||
)
|
||||
source = db.create_table("source", [{"id": 1}])
|
||||
original = db.create_materialized_view("saved", **source_args, exist_ok=True)
|
||||
definition = original.definition
|
||||
version = original.table.version
|
||||
source.add([{"id": 2}])
|
||||
if background:
|
||||
job = db.create_materialized_view_async(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
job.wait()
|
||||
kept = db.open_materialized_view("saved")
|
||||
else:
|
||||
kept = db.create_materialized_view(
|
||||
"saved", **replacement_args, exist_ok=True
|
||||
)
|
||||
assert kept.definition.query == definition.query
|
||||
assert kept.table.version == version
|
||||
assert kept.table.to_arrow().to_pylist() == [{"id": 1}]
|
||||
with pytest.raises(ValueError, match="already exists"):
|
||||
db.create_materialized_view("saved", **source_args)
|
||||
@@ -10,6 +10,7 @@ import lancedb
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
from lancedb.db import AsyncConnection
|
||||
from lancedb.exceptions import JobFailedError
|
||||
from lancedb.materialized_view import MaterializedViewDefinition
|
||||
from lancedb.remote.db import RemoteDBConnection
|
||||
from utils import start_server_thread
|
||||
@@ -63,7 +64,21 @@ def mock_remote_materialized_view_refresh():
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize("full", [False, True])
|
||||
async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
@pytest.mark.parametrize(
|
||||
"resources",
|
||||
[
|
||||
{},
|
||||
{"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(
|
||||
sync, background, full, resources
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class RefreshServer(flight.FlightServerBase):
|
||||
@@ -77,10 +92,13 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
return flight.RecordBatchStream(
|
||||
pa.table(
|
||||
{
|
||||
"name": ["view"],
|
||||
"query": ["SELECT * FROM source"],
|
||||
"description": [
|
||||
json.dumps(
|
||||
{"name": "view", "query": "SELECT * FROM source"}
|
||||
)
|
||||
],
|
||||
}
|
||||
)
|
||||
).replace_schema_metadata({b"lancedb.describe.format": b"json"})
|
||||
)
|
||||
assert b"REFRESH MATERIALIZED VIEW" in ticket.ticket
|
||||
# SQL completion carries no refresh statistics.
|
||||
@@ -90,7 +108,7 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
mock_remote_materialized_view_refresh() as (host, requests),
|
||||
RefreshServer() as server,
|
||||
):
|
||||
options = {"full": True} if full else {}
|
||||
options = {"full": full, **resources}
|
||||
connect = lancedb.connect if sync else lancedb.connect_async
|
||||
db = connect(
|
||||
"db://dev",
|
||||
@@ -136,15 +154,37 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
assert len(describes) == 2
|
||||
assert len(refreshes) == 1
|
||||
assert all(
|
||||
b'DESCRIBE MATERIALIZED VIEW "view"' in command for command in describes
|
||||
b'DESCRIBE MATERIALIZED VIEW "view" FORMAT JSON' in command
|
||||
for command in describes
|
||||
)
|
||||
(refresh,) = refreshes
|
||||
assert b'REFRESH MATERIALIZED VIEW "view"' in refresh
|
||||
assert (b"WITH (full = true)" in refresh) is full
|
||||
assert (b"full = true" in refresh) is full
|
||||
for key, value in resources.items():
|
||||
expected = (
|
||||
f"{key} = '{value}'" if key == "gpu_class" else f"{key} = {value}"
|
||||
)
|
||||
assert expected.encode() in refresh
|
||||
previous = len(server.commands)
|
||||
for invalid in [
|
||||
{"total_cpu_millis": 0},
|
||||
{"total_gpu_count": -1},
|
||||
{"total_gpu_count": True},
|
||||
{"total_gpu_count": 2**32},
|
||||
{"gpu_class": "H200:8"},
|
||||
{"total_gpu_count": 0, "gpu_class": "h100"},
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
if sync:
|
||||
view.refresh(**invalid)
|
||||
else:
|
||||
await view.refresh(**invalid)
|
||||
assert len(server.commands) == previous
|
||||
assert not any("count_rows" in path for path in requests)
|
||||
|
||||
|
||||
def test_sync_remote_create_uses_public_async_connection():
|
||||
@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"])
|
||||
def test_sync_remote_create_uses_public_async_connection(query):
|
||||
calls = []
|
||||
|
||||
class StubAsyncTable:
|
||||
@@ -159,17 +199,25 @@ def test_sync_remote_create_uses_public_async_connection():
|
||||
name,
|
||||
source,
|
||||
*,
|
||||
query=None,
|
||||
select=None,
|
||||
where=None,
|
||||
limit=None,
|
||||
with_no_data=False,
|
||||
exist_ok=False,
|
||||
auto_refresh_enabled=None,
|
||||
auto_refresh_interval_seconds=None,
|
||||
total_cpu_millis=None,
|
||||
total_memory_bytes=None,
|
||||
total_gpu_count=None,
|
||||
gpu_class=None,
|
||||
gpu_count=None,
|
||||
):
|
||||
calls.append(
|
||||
(
|
||||
name,
|
||||
source,
|
||||
query,
|
||||
select,
|
||||
where,
|
||||
limit,
|
||||
@@ -188,18 +236,24 @@ def test_sync_remote_create_uses_public_async_connection():
|
||||
db.db_name = "example"
|
||||
db.serialize = lambda: "{}"
|
||||
|
||||
view = db.create_materialized_view(
|
||||
"adults",
|
||||
"people",
|
||||
select=["name"],
|
||||
where="age >= 18",
|
||||
limit=10,
|
||||
with_no_data=True,
|
||||
auto_refresh_enabled=True,
|
||||
auto_refresh_interval_seconds=0.5,
|
||||
)
|
||||
if query is None:
|
||||
view = db.create_materialized_view(
|
||||
"adults",
|
||||
"people",
|
||||
select=["name"],
|
||||
where="age >= 18",
|
||||
limit=10,
|
||||
with_no_data=True,
|
||||
auto_refresh_enabled=True,
|
||||
auto_refresh_interval_seconds=0.5,
|
||||
)
|
||||
assert calls == [
|
||||
("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5)
|
||||
]
|
||||
else:
|
||||
view = db.create_materialized_view("adults", query=query)
|
||||
assert calls == [("adults", None, query, None, None, None, False, None, None)]
|
||||
assert view.name == "adults"
|
||||
assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)]
|
||||
|
||||
db.drop_materialized_view("adults", namespace_path=["analytics"])
|
||||
assert calls[-1] == ("drop", "adults", ["analytics"])
|
||||
@@ -227,21 +281,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())
|
||||
|
||||
@@ -400,20 +454,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()]
|
||||
|
||||
@@ -667,6 +721,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):
|
||||
@@ -674,8 +733,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"
|
||||
@@ -688,6 +747,12 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
|
||||
"filter": None,
|
||||
"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"
|
||||
@@ -704,8 +769,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"
|
||||
@@ -740,18 +805,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
|
||||
@@ -759,3 +840,144 @@ def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path):
|
||||
db = make_db(tmp_path)
|
||||
view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False)
|
||||
assert view.table.count_rows() == 3
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query, expected",
|
||||
[
|
||||
(
|
||||
"SELECT kind, count(*) AS n FROM events GROUP BY kind",
|
||||
[{"kind": "a", "n": 2}, {"kind": "b", "n": 1}],
|
||||
),
|
||||
(
|
||||
"SELECT id, tag FROM events, UNNEST(tags) AS tag",
|
||||
[{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}],
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_query_defined_materialized_view(
|
||||
tmp_path, sync, namespace, background, query, expected
|
||||
):
|
||||
if namespace:
|
||||
connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async
|
||||
db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS)
|
||||
elif sync:
|
||||
db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS)
|
||||
else:
|
||||
db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
|
||||
rows = [
|
||||
{"id": 1, "kind": "a", "tags": ["x", "y"]},
|
||||
{"id": 2, "kind": "a", "tags": []},
|
||||
{"id": 3, "kind": "b", "tags": ["z"]},
|
||||
]
|
||||
if sync:
|
||||
db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
|
||||
if background:
|
||||
db.create_materialized_view_async("result", query=query).wait()
|
||||
view = db.open_materialized_view("result")
|
||||
else:
|
||||
view = db.create_materialized_view("result", query=query)
|
||||
actual = view.table.to_arrow().to_pylist()
|
||||
assert view.definition.query == query
|
||||
view.refresh()
|
||||
refreshed = view.table.to_arrow().to_pylist()
|
||||
else:
|
||||
await db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
|
||||
if background:
|
||||
job = await db.create_materialized_view_async("result", query=query)
|
||||
await job.wait()
|
||||
view = await db.open_materialized_view("result")
|
||||
else:
|
||||
view = await db.create_materialized_view("result", query=query)
|
||||
actual = (await view.table.to_arrow()).to_pylist()
|
||||
assert (await view.definition()).query == query
|
||||
await view.refresh()
|
||||
refreshed = (await view.table.to_arrow()).to_pylist()
|
||||
assert sorted(actual, key=str) == sorted(expected, key=str)
|
||||
assert sorted(refreshed, key=str) == sorted(expected, key=str)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"clauses",
|
||||
[{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}],
|
||||
)
|
||||
async def test_query_rejects_source_clauses_before_submission(
|
||||
sync, background, clauses
|
||||
):
|
||||
connect = lancedb.connect if sync else lancedb.connect_async
|
||||
db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1")
|
||||
if not sync:
|
||||
db = await db
|
||||
create = (
|
||||
db.create_materialized_view_async if background else db.create_materialized_view
|
||||
)
|
||||
with pytest.raises(ValueError, match="query cannot be combined"):
|
||||
if sync:
|
||||
create("invalid", query="SELECT * FROM people", **clauses)
|
||||
else:
|
||||
await create("invalid", query="SELECT * FROM people", **clauses)
|
||||
with pytest.raises(ValueError, match="either source or query"):
|
||||
if sync:
|
||||
create("missing")
|
||||
else:
|
||||
await create("missing")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"SELECT kind, count(*) AS n FROM events GROUP BY kind",
|
||||
"SELECT id, c.text FROM docs, chunk(body) AS c",
|
||||
"SELECT id, tag FROM events, UNNEST(tags) AS tag",
|
||||
"SELECT a.id FROM a JOIN b ON a.id = b.id",
|
||||
],
|
||||
)
|
||||
async def test_remote_create_forwards_defining_query(sync, query):
|
||||
native = CapturingCreateConnection()
|
||||
db = AsyncConnection(native)
|
||||
if sync:
|
||||
remote = RemoteDBConnection.__new__(RemoteDBConnection)
|
||||
remote._conn = db
|
||||
job = remote.create_materialized_view_async("result", query=query)
|
||||
job.wait()
|
||||
else:
|
||||
job = await db.create_materialized_view_async("result", query=query)
|
||||
await job.wait()
|
||||
assert native.calls[0][0:2] == ("result", None)
|
||||
assert native.calls[0][2]["query"] == query
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
def test_query_with_no_data_and_invalid_query(tmp_path, background):
|
||||
db = make_db(tmp_path)
|
||||
query = "SELECT name FROM people WHERE age >= 18"
|
||||
if background:
|
||||
db.create_materialized_view_async(
|
||||
"adults", query=query, with_no_data=True
|
||||
).wait()
|
||||
view = db.open_materialized_view("adults")
|
||||
else:
|
||||
view = db.create_materialized_view("adults", query=query, with_no_data=True)
|
||||
assert view.table.count_rows() == 0
|
||||
view.refresh()
|
||||
assert view.table.count_rows() == 2
|
||||
create = (
|
||||
db.create_materialized_view_async if background else db.create_materialized_view
|
||||
)
|
||||
error = JobFailedError if background else ValueError
|
||||
with pytest.raises(error, match="unsupported clause"):
|
||||
result = create("invalid", query="SELECT * FROM people ORDER BY age")
|
||||
if background:
|
||||
result.wait()
|
||||
assert "invalid" not in db.table_names()
|
||||
|
||||
@@ -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
|
||||
@@ -278,7 +297,7 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path):
|
||||
|
||||
# with_row_id is unsupported by the LSM scanner; on an RTE table the default
|
||||
# (auto-routed) read hard-errors instead of silently reading a stale base.
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(Exception, match=r"with_row_id.*use_rte\(false\)"):
|
||||
table.search().with_row_id(True).to_arrow()
|
||||
|
||||
# use_rte(False) is the escape hatch: it reads the base table only.
|
||||
@@ -563,19 +582,28 @@ def test_lsm_read_time_travel_errors(tmp_path):
|
||||
assert sorted(base["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_take_row_ids_errors(tmp_path):
|
||||
@pytest.mark.parametrize("with_row_id", [False, True])
|
||||
@pytest.mark.parametrize("use_rte", [None, True])
|
||||
def test_lsm_read_take_row_ids_errors(tmp_path, with_row_id, use_rte):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
_lsm_upsert(table, [4])
|
||||
# take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid,
|
||||
# so it hard-errors instead of failing with an opaque column-not-found error.
|
||||
with pytest.raises(Exception, match="row id"):
|
||||
table.take_row_ids([0, 1]).to_arrow()
|
||||
# Automatic and explicit RTE routing must explain the unsupported take,
|
||||
# including when row IDs are only requested internally for ordering.
|
||||
take = table.take_row_ids([1, 0, 1, 2**64 - 1], with_row_id=with_row_id)
|
||||
if use_rte is not None:
|
||||
take = take.use_rte(use_rte)
|
||||
with pytest.raises(Exception, match=r"take by row id.*use_rte\(false\)"):
|
||||
take.to_arrow()
|
||||
# use_rte(False) is the escape hatch: it reads the base table.
|
||||
base = table.take_row_ids([0, 1]).use_rte(False).to_arrow()
|
||||
assert base.num_rows == 2
|
||||
base = take.use_rte(False).to_arrow()
|
||||
assert base["id"].to_pylist() == [2, 1, 2]
|
||||
assert base["value"].to_pylist() == [1, 0, 1]
|
||||
assert ("_rowid" in base.column_names) == with_row_id
|
||||
if with_row_id:
|
||||
assert base["_rowid"].to_pylist() == [1, 0, 1]
|
||||
|
||||
|
||||
def test_lsm_read_fts_postfilter_errors(tmp_path):
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
import tempfile
|
||||
import shutil
|
||||
import importlib
|
||||
import asyncio
|
||||
import pickle
|
||||
import warnings
|
||||
import http.server
|
||||
import json
|
||||
@@ -16,8 +18,10 @@ import copy
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
from lance_namespace import DescribeTableResponse
|
||||
from utils import start_server_thread
|
||||
from lancedb.listing import AsyncListing, Listing
|
||||
from lancedb.index import FTS
|
||||
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
|
||||
from lancedb.namespace import (
|
||||
_MAX_QUERY_K,
|
||||
@@ -25,7 +29,7 @@ from lancedb.namespace import (
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import Query
|
||||
from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
|
||||
@@ -34,6 +38,122 @@ PUSHDOWN_DATA = pa.table(
|
||||
)
|
||||
|
||||
|
||||
class _RefreshNamespaceWithExpiringOptions(LanceNamespace):
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
|
||||
def namespace_id(self):
|
||||
return f"refresh-test:{self.root}"
|
||||
|
||||
def describe_table(self, request):
|
||||
from pathlib import Path
|
||||
|
||||
return DescribeTableResponse(
|
||||
location=str(Path(self.root) / "t.lance"),
|
||||
storage_options={"vended": "fresh", "expires_at_millis": "1"},
|
||||
)
|
||||
|
||||
|
||||
class _DeclaredNamespaceWithoutProperties(LanceNamespace):
|
||||
root = None
|
||||
|
||||
def __init__(self):
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
self.client = DirectoryNamespace(root=self.root)
|
||||
|
||||
def namespace_id(self):
|
||||
return self.client.namespace_id()
|
||||
|
||||
def describe_table(self, request):
|
||||
return self.client.describe_table(request)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]])
|
||||
async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
|
||||
class ExistenceNamespace(LanceNamespace):
|
||||
def namespace_id(self):
|
||||
return "existence-test"
|
||||
|
||||
def table_exists(self, request):
|
||||
if request.id == ["missing"]:
|
||||
raise TableNotFoundError("Table not found")
|
||||
|
||||
def describe_table(self, request):
|
||||
raise AssertionError("Custom existence checks must not open tables")
|
||||
|
||||
namespace = ExistenceNamespace()
|
||||
db = LanceNamespaceDBConnection(namespace)
|
||||
adb = lancedb.AsyncLanceNamespaceDBConnection(namespace)
|
||||
assert db.table_exists(table_id) is (table_id != ["missing"])
|
||||
assert await adb.table_exists(table_id) is (table_id != ["missing"])
|
||||
|
||||
|
||||
def test_table_pickle_rejects_custom_namespace_connection(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
|
||||
"t", [{"id": 1}]
|
||||
)
|
||||
|
||||
class UnserializableNamespace(LanceNamespace):
|
||||
def __init__(self, root):
|
||||
from threading import Lock
|
||||
|
||||
self.client = DirectoryNamespace(root=str(root))
|
||||
self.lock = Lock()
|
||||
|
||||
def namespace_id(self):
|
||||
return self.client.namespace_id()
|
||||
|
||||
def describe_table(self, request):
|
||||
return self.client.describe_table(request)
|
||||
|
||||
db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path))
|
||||
table = db.open_table("t")
|
||||
|
||||
with pytest.raises(TypeError, match="namespace"):
|
||||
pickle.dumps(table)
|
||||
|
||||
|
||||
def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path):
|
||||
lancedb.connect(tmp_path).create_table("t", [{"id": 1}])
|
||||
db = lancedb.connect_namespace(
|
||||
f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)}
|
||||
)
|
||||
table = db.open_table("t", storage_options={"caller_only": "keep"})
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_only"] == "keep"
|
||||
assert options["vended"] == "fresh"
|
||||
|
||||
|
||||
def test_table_pickle_allows_declared_namespace_without_properties(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
|
||||
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
|
||||
"t", [{"id": 1}]
|
||||
)
|
||||
_DeclaredNamespaceWithoutProperties.root = str(tmp_path)
|
||||
try:
|
||||
impl = f"{__name__}._DeclaredNamespaceWithoutProperties"
|
||||
db = LanceNamespaceDBConnection(
|
||||
_DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl
|
||||
)
|
||||
table = db.open_table("t")
|
||||
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
assert restored.to_arrow()["id"].to_pylist() == [1]
|
||||
finally:
|
||||
_DeclaredNamespaceWithoutProperties.root = None
|
||||
|
||||
|
||||
class TestNamespaceCreateTableOptions:
|
||||
@pytest.mark.parametrize("version", ["legacy", "stable"])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
@@ -287,6 +407,328 @@ def paginated_rest_namespace():
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path):
|
||||
from time import time
|
||||
|
||||
local = lancedb.connect(tmp_path)
|
||||
local.create_table("t", [{"id": 1}])
|
||||
location = str(tmp_path / "t.lance")
|
||||
ipc = _ipc_file(pa.table({"id": [42]}))
|
||||
seen = []
|
||||
current_options = {
|
||||
"block_size": "4096",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
seen.append(path)
|
||||
if path.endswith("/describe"):
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": current_options}
|
||||
).encode()
|
||||
content_type = "application/json"
|
||||
elif path.endswith("/query"):
|
||||
body = ipc
|
||||
content_type = "application/vnd.apache.arrow.file"
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": f"http://127.0.0.1:{server.server_port}"},
|
||||
namespace_client_pushdown_operations=["QueryTable"],
|
||||
)
|
||||
table = db.open_table("t")
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
seen.clear()
|
||||
assert restored.search().limit(1).to_list() == [{"id": 42}]
|
||||
assert seen == ["/v1/table/t/query"]
|
||||
|
||||
current_options = {
|
||||
"block_size": "8192",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
}
|
||||
assert table.latest_storage_options()["block_size"] == "8192"
|
||||
assert restored.latest_storage_options()["block_size"] == "8192"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path):
|
||||
from time import time
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
current_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if not (path.endswith("/declare") or path.endswith("/describe")):
|
||||
self.send_error(404)
|
||||
return
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": current_options}
|
||||
).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest", {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
)
|
||||
table = db.create_table("t", [{"id": 1}])
|
||||
payload = pickle.dumps(table)
|
||||
assert b"short-lived" not in payload
|
||||
restored = pickle.loads(payload)
|
||||
|
||||
current_options = {}
|
||||
assert table.latest_storage_options() == {}
|
||||
assert restored.latest_storage_options() == {}
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entrypoint", ["create", "open"])
|
||||
def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint):
|
||||
from time import time
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
caller_options = {"caller_option": "kept", "conflict": "caller"}
|
||||
vended_options = {
|
||||
"vended_1": "old",
|
||||
"conflict": "vended",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if path.endswith("/declare") or path.endswith("/describe"):
|
||||
body = json.dumps(
|
||||
{"location": location, "storage_options": vended_options}
|
||||
).encode()
|
||||
else:
|
||||
self.send_error(404)
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
db = lancedb.connect_namespace(
|
||||
"rest",
|
||||
{"uri": f"http://127.0.0.1:{server.server_port}"},
|
||||
)
|
||||
if entrypoint == "create":
|
||||
table = db.create_table(
|
||||
"t", [{"id": 1}], storage_options=caller_options
|
||||
)
|
||||
else:
|
||||
db.create_table("t", [{"id": 1}])
|
||||
table = db.open_table("t", storage_options=caller_options)
|
||||
restored = pickle.loads(pickle.dumps(table))
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_option"] == "kept"
|
||||
assert options["conflict"] == "vended"
|
||||
|
||||
vended_options.update(
|
||||
{
|
||||
"vended_2": "new",
|
||||
"conflict": "vended-new",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
}
|
||||
)
|
||||
|
||||
for current in (table, restored):
|
||||
options = current.latest_storage_options()
|
||||
assert options["caller_option"] == "kept"
|
||||
assert options["vended_2"] == "new"
|
||||
assert options["conflict"] == "vended-new"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_namespace_open_uses_explicit_storage_options_provider(tmp_path):
|
||||
from time import time
|
||||
|
||||
from lancedb._lancedb import connect_namespace as connect_namespace_inner
|
||||
from lancedb.db import AsyncConnection
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
seed_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
if not (path.endswith("/declare") or path.endswith("/describe")):
|
||||
self.send_error(404)
|
||||
return
|
||||
result = {"location": location, "storage_options": seed_options}
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class ExplicitClient(LanceNamespace):
|
||||
calls = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return "explicit-storage-options-provider"
|
||||
|
||||
def describe_table(self, request):
|
||||
self.calls += 1
|
||||
return DescribeTableResponse(
|
||||
location=location,
|
||||
storage_options={
|
||||
"explicit_provider": "fresh",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
},
|
||||
)
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
db = lancedb.connect_namespace("rest", properties)
|
||||
db.create_table("t", [{"id": 1}])
|
||||
|
||||
async def check():
|
||||
connection = AsyncConnection(
|
||||
connect_namespace_inner("rest", properties)
|
||||
)
|
||||
client = ExplicitClient()
|
||||
table = await connection.open_table("t", namespace_client=client)
|
||||
options = await table.latest_storage_options()
|
||||
assert client.calls > 0
|
||||
assert options["explicit_provider"] == "fresh"
|
||||
|
||||
asyncio.run(check())
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def test_namespace_create_without_seed_uses_connection_provider(tmp_path):
|
||||
from time import time
|
||||
|
||||
from lancedb._lancedb import connect_namespace as connect_namespace_inner
|
||||
from lancedb.db import AsyncConnection
|
||||
|
||||
location = str(tmp_path / "t.lance")
|
||||
seed_options = {
|
||||
"vended_seed": "short-lived",
|
||||
"expires_at_millis": str(int(time() * 1000) + 30_000),
|
||||
}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
||||
path = urlparse(self.path).path
|
||||
result = {"location": location}
|
||||
if path.endswith("/describe"):
|
||||
result["storage_options"] = seed_options
|
||||
elif not path.endswith("/declare"):
|
||||
self.send_error(404)
|
||||
return
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
class ExplicitClient(LanceNamespace):
|
||||
calls = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return "explicit-storage-options-provider"
|
||||
|
||||
def describe_table(self, request):
|
||||
self.calls += 1
|
||||
return DescribeTableResponse(
|
||||
location=location,
|
||||
storage_options={
|
||||
"explicit_provider": "fresh",
|
||||
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
|
||||
},
|
||||
)
|
||||
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
|
||||
|
||||
async def check():
|
||||
connection = AsyncConnection(
|
||||
connect_namespace_inner("rest", properties)
|
||||
)
|
||||
client = ExplicitClient()
|
||||
table = await connection.create_table(
|
||||
"t", [{"id": 1}], namespace_client=client
|
||||
)
|
||||
options = await table.latest_storage_options()
|
||||
assert client.calls == 0
|
||||
assert options["vended_seed"] == "short-lived"
|
||||
|
||||
asyncio.run(check())
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("namespace_path", [[], ["n"]])
|
||||
async def test_rest_namespace_table_names_collects_pages(
|
||||
@@ -411,8 +853,16 @@ class TestNamespaceConnection:
|
||||
assert "test_ns" in db.list_namespaces().namespaces
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
db.create_table("root_table", schema=schema)
|
||||
assert db.table_exists(["root_table"]) is True
|
||||
assert "root_table" in db
|
||||
assert db.table_exists(["missing"]) is False
|
||||
assert "missing" not in db
|
||||
table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"])
|
||||
assert table.namespace == ["test_ns"]
|
||||
assert db.table_exists(["test_ns", "test_table"]) is True
|
||||
assert db.table_exists(["test_ns", "missing"]) is False
|
||||
assert "test_table" not in db
|
||||
assert "test_table" in db.table_names(namespace_path=["test_ns"])
|
||||
assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables
|
||||
|
||||
@@ -420,7 +870,10 @@ class TestNamespaceConnection:
|
||||
assert opened.namespace == ["test_ns"]
|
||||
|
||||
db.drop_table("test_table", namespace_path=["test_ns"])
|
||||
assert db.table_exists(["test_ns", "test_table"]) is False
|
||||
assert db.list_tables(namespace_path=["test_ns"]).tables == []
|
||||
db.drop_table("root_table")
|
||||
assert "root_table" not in db
|
||||
db.drop_namespace(["test_ns"])
|
||||
assert "test_ns" not in db.list_namespaces().namespaces
|
||||
|
||||
@@ -942,12 +1395,18 @@ class TestAsyncNamespaceConnection:
|
||||
assert "test_ns" in (await db.list_namespaces()).namespaces
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
await db.create_table("root_table", schema=schema)
|
||||
assert await db.table_exists(["root_table"]) is True
|
||||
assert await db.table_exists(["missing"]) is False
|
||||
table = await db.create_table(
|
||||
"test_table", schema=schema, namespace_path=["test_ns"]
|
||||
)
|
||||
assert table._namespace_path == ["test_ns"]
|
||||
assert table._namespace_client is None
|
||||
assert table._route_pushdown_to_rust is True
|
||||
assert await db.table_exists(["test_ns", "test_table"]) is True
|
||||
assert await db.table_exists(["test_ns", "missing"]) is False
|
||||
assert await db.table_exists(["test_table"]) is False
|
||||
assert "test_table" in await db.table_names(namespace_path=["test_ns"])
|
||||
assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables
|
||||
|
||||
@@ -955,7 +1414,10 @@ class TestAsyncNamespaceConnection:
|
||||
assert opened._namespace_path == ["test_ns"]
|
||||
|
||||
await db.drop_table("test_table", namespace_path=["test_ns"])
|
||||
assert await db.table_exists(["test_ns", "test_table"]) is False
|
||||
assert (await db.list_tables(namespace_path=["test_ns"])).tables == []
|
||||
await db.drop_table("root_table")
|
||||
assert await db.table_exists(["root_table"]) is False
|
||||
await db.drop_namespace(["test_ns"])
|
||||
assert "test_ns" not in (await db.list_namespaces()).namespaces
|
||||
|
||||
@@ -1310,6 +1772,48 @@ class TestPushdownOperations:
|
||||
assert request.maximum_nprobes == 0
|
||||
assert request.to_dict()["maximum_nprobes"] == 0
|
||||
|
||||
def test_lance_table_order_by_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = table._execute_query(
|
||||
Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
|
||||
).read_all()
|
||||
|
||||
# Pushing this query down would drop order_by and return id 3.
|
||||
assert result.column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
).read_all()
|
||||
|
||||
# The namespace request has no scan-order field. Local execution keeps
|
||||
# membership order, projection and limit; a dropped order or a sort
|
||||
# would return [1, 3] or [1, 2].
|
||||
assert result.column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAsyncPushdownOperations:
|
||||
@@ -1372,6 +1876,47 @@ class TestAsyncPushdownOperations:
|
||||
assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K]
|
||||
assert all(r.k <= 2**31 - 1 for r in namespace_client.requests)
|
||||
|
||||
async def test_async_table_order_by_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = await lancedb.connect_async(str(tmp_path / "db"))
|
||||
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = await table._execute_query(
|
||||
Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
|
||||
)
|
||||
|
||||
# Pushing this query down would drop order_by and return id 3.
|
||||
batches = await result.read_all()
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path):
|
||||
namespace_client = _NamespaceClient()
|
||||
db = await lancedb.connect_async(str(tmp_path / "db"))
|
||||
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}])
|
||||
await table.add([{"id": 2}])
|
||||
table._namespace_path = ["geneva"]
|
||||
table._namespace_client = namespace_client
|
||||
table._pushdown_operations = {"QueryTable"}
|
||||
table._route_pushdown_to_rust = False
|
||||
|
||||
result = await table._execute_query(
|
||||
Query(
|
||||
limit=2,
|
||||
filter="id >= 1",
|
||||
columns=["id"],
|
||||
scan_in_order=True,
|
||||
)
|
||||
)
|
||||
|
||||
batches = await result.read_all()
|
||||
assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1]
|
||||
assert namespace_client.requests == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query_kwargs",
|
||||
[
|
||||
@@ -1483,3 +2028,42 @@ def test_python_namespace_attribute_access(tmp_path):
|
||||
# Missing dunder lookups still raise, so copy/hasattr probes work.
|
||||
assert not hasattr(request, "__missing_dunder__")
|
||||
assert copy.deepcopy(request) == request
|
||||
|
||||
|
||||
@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
|
||||
def test_namespace_fts_operator_is_preserved(columns):
|
||||
request = _query_to_namespace_request(
|
||||
["matches"],
|
||||
Query(
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query="gripper closed", columns=columns, operator="AND"
|
||||
)
|
||||
),
|
||||
)
|
||||
structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
|
||||
if columns and len(columns) > 1:
|
||||
assert all(
|
||||
query["operator"] == "And"
|
||||
for query in structured["multi_match"]["match_queries"]
|
||||
)
|
||||
else:
|
||||
assert structured["match"]["operator"] == "And"
|
||||
assert structured["match"].get("column") == (columns[0] if columns else None)
|
||||
|
||||
|
||||
def test_namespace_fts_count_fast_search(tmp_path):
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace("dir", properties)
|
||||
table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
pushed = lancedb.connect_namespace(
|
||||
"dir", properties, namespace_client_pushdown_operations=["QueryTable"]
|
||||
).open_table("matches")
|
||||
assert pushed.search("gripper", query_type="fts").count_rows() == 20
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.use_rte(False).count_rows() == 15
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.count_rows() == 15
|
||||
assert len(query.limit(100).to_list()) == 15
|
||||
|
||||
@@ -68,8 +68,17 @@ def test_windows_wheel_tag_and_native_import():
|
||||
if not wheels:
|
||||
pytest.skip("no wheel artifact is available in this development environment")
|
||||
|
||||
# The wheel is tagged with the abi3 floor, which follows requires-python.
|
||||
minimum_python = re.search(
|
||||
r'^requires-python\s*=\s*">=(\d+)\.(\d+)"$',
|
||||
(project_dir / "pyproject.toml").read_text(),
|
||||
re.MULTILINE,
|
||||
)
|
||||
assert minimum_python is not None
|
||||
major, minor = minimum_python.groups()
|
||||
|
||||
assert len(wheels) == 1
|
||||
assert wheels[0].name.endswith("-cp310-abi3-win_amd64.whl")
|
||||
assert wheels[0].name.endswith(f"-cp{major}{minor}-abi3-win_amd64.whl")
|
||||
|
||||
native_module = importlib.import_module("lancedb._lancedb")
|
||||
assert Path(native_module.__file__).suffix == ".pyd"
|
||||
|
||||
@@ -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)})
|
||||
@@ -1416,3 +1856,244 @@ def test_from_tables_split_without_permutation_table(mem_db):
|
||||
|
||||
with pytest.raises(ValueError, match="permutation on split `train` because no"):
|
||||
Permutation.from_tables(tbl, split="train")
|
||||
|
||||
|
||||
def _double_value_row(row):
|
||||
return {"id": row["id"], "value": row["value"] * 2}
|
||||
|
||||
|
||||
def _double_value_batch(batch):
|
||||
return {"id": batch["id"], "value": [value * 2 for value in batch["value"]]}
|
||||
|
||||
|
||||
def test_map_row_by_row(some_permutation: Permutation):
|
||||
"""Test .map() applies fn to each row individually."""
|
||||
mapped = some_permutation.map(_double_value_row)
|
||||
batches = list(mapped.iter(10, skip_last_batch=False))
|
||||
first_batch = batches[0]
|
||||
assert len(first_batch) == 10
|
||||
assert isinstance(first_batch[0], dict)
|
||||
for row in first_batch:
|
||||
assert row["value"] == row["id"] * 2
|
||||
|
||||
|
||||
def test_map_batched(some_permutation: Permutation):
|
||||
"""Test batched only changes what fn receives, not what is yielded."""
|
||||
seen = []
|
||||
|
||||
def double_value(batch):
|
||||
seen.append(batch)
|
||||
return _double_value_batch(batch)
|
||||
|
||||
mapped = some_permutation.map(double_value, batched=True)
|
||||
first_batch = next(mapped.iter(10, skip_last_batch=False))
|
||||
assert isinstance(seen[0], dict)
|
||||
assert len(seen[0]["id"]) == 10
|
||||
assert first_batch == next(
|
||||
some_permutation.map(_double_value_row).iter(10, skip_last_batch=False)
|
||||
)
|
||||
|
||||
|
||||
def test_map_chain(some_permutation: Permutation):
|
||||
"""Test chained maps run in order and each one replaces the whole row."""
|
||||
|
||||
def add_doubled(row):
|
||||
return {**row, "doubled": row["value"] * 2}
|
||||
|
||||
def to_total(batch):
|
||||
return {
|
||||
"total": [a + b for a, b in zip(batch["value"], batch["doubled"])],
|
||||
}
|
||||
|
||||
def add_label(row):
|
||||
return {**row, "label": str(row["total"])}
|
||||
|
||||
first = some_permutation.map(add_doubled)
|
||||
mapped = first.map(to_total, batched=True).map(add_label)
|
||||
expected = [
|
||||
{"total": row["value"] * 3, "label": str(row["value"] * 3)}
|
||||
for row in some_permutation.take_offsets([0, 1, 2])
|
||||
]
|
||||
assert mapped.take_offsets([0, 1, 2]) == expected
|
||||
assert next(mapped.iter(3, skip_last_batch=False)) == expected
|
||||
# Extending a chain does not change the permutation it was derived from
|
||||
assert set(first.take_offsets([0])[0]) == {"id", "value", "doubled"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"explicit",
|
||||
[
|
||||
lambda permutation: permutation.with_format("python"),
|
||||
lambda permutation: permutation.with_format("arrow"),
|
||||
lambda permutation: permutation.with_transform(Transforms.arrow2arrow),
|
||||
],
|
||||
)
|
||||
def test_map_rejects_format_and_transform(some_permutation: Permutation, explicit):
|
||||
"""Test .map() cannot be mixed with with_format or with_transform."""
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
explicit(some_permutation).map(_double_value_row)
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
explicit(some_permutation.map(_double_value_row))
|
||||
|
||||
|
||||
def test_map_rejects_format_without_optional_dependency(
|
||||
some_permutation: Permutation, monkeypatch
|
||||
):
|
||||
"""Test the map check runs before a format imports an optional dependency."""
|
||||
import sys
|
||||
|
||||
# Make polars fail to import, as it does on an install without extras
|
||||
monkeypatch.setitem(sys.modules, "polars", None)
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
some_permutation.map(_double_value_row).with_format("polars")
|
||||
|
||||
|
||||
def test_map_rejects_explicit_transform_from_old_pickle(
|
||||
some_permutation: Permutation,
|
||||
):
|
||||
"""Test pickles written before explicit_transform existed keep the guard."""
|
||||
|
||||
def restore_without_flag(permutation):
|
||||
state = permutation.__getstate__()
|
||||
del state["explicit_transform"]
|
||||
restored = Permutation.__new__(Permutation)
|
||||
restored.__setstate__(state)
|
||||
return restored
|
||||
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
restore_without_flag(some_permutation.with_format("arrow")).map(
|
||||
_double_value_row
|
||||
)
|
||||
# The default transform is indistinguishable from an explicit "python" format
|
||||
mapped = restore_without_flag(some_permutation).map(_double_value_row)
|
||||
assert mapped.take_offsets([0]) == [
|
||||
_double_value_row(row) for row in some_permutation.take_offsets([0])
|
||||
]
|
||||
|
||||
|
||||
def test_map_rejects_transform_passed_to_constructor(some_table: Table):
|
||||
"""Test a transform given to the constructor counts as explicit too."""
|
||||
permutation = Permutation(
|
||||
some_table,
|
||||
None,
|
||||
0,
|
||||
{"id": "id"},
|
||||
DEFAULT_BATCH_SIZE,
|
||||
Transforms.arrow2arrow,
|
||||
)
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
permutation.map(_double_value_row)
|
||||
|
||||
|
||||
def test_map_take_offsets(some_permutation: Permutation):
|
||||
"""Test .map() keeps the positions and duplicates of the requested offsets."""
|
||||
calls = []
|
||||
|
||||
def record(batch):
|
||||
calls.append(batch)
|
||||
return batch
|
||||
|
||||
mapped = some_permutation.map(_double_value_row).map(record, batched=True)
|
||||
offsets = [5, 0, 5, 2]
|
||||
expected = [
|
||||
_double_value_row(row) for row in some_permutation.take_offsets(offsets)
|
||||
]
|
||||
assert mapped.take_offsets(offsets) == expected
|
||||
assert mapped.__getitems__(offsets) == expected
|
||||
|
||||
calls.clear()
|
||||
assert mapped.take_offsets([]) == []
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_map_validates_output(some_permutation: Permutation):
|
||||
"""Test .map() rejects callback output that would break the batch shape."""
|
||||
with pytest.raises(ValueError, match="returned 1 values for column `id`"):
|
||||
some_permutation.map(
|
||||
lambda batch: {"id": batch["id"][:1]}, batched=True
|
||||
).take_offsets([0, 1])
|
||||
with pytest.raises(TypeError, match="must return a dict of columns, got list"):
|
||||
some_permutation.map(
|
||||
lambda batch: list(batch.values()), batched=True
|
||||
).take_offsets([0, 1])
|
||||
# A str has the right length here but is still not a column of values
|
||||
for value in (2, "ab"):
|
||||
with pytest.raises(TypeError, match="list of values for column `n`, got"):
|
||||
some_permutation.map(lambda batch: {"n": value}, batched=True).take_offsets(
|
||||
[0, 1]
|
||||
)
|
||||
with pytest.raises(
|
||||
TypeError, match="must return a dict for each row, got NoneType"
|
||||
):
|
||||
some_permutation.map(lambda row: None).take_offsets([0, 1])
|
||||
with pytest.raises(ValueError, match="did not return the same keys for every row"):
|
||||
some_permutation.map(
|
||||
lambda row: row if row["id"] % 2 else {"id": row["id"]}
|
||||
).map(lambda batch: batch, batched=True).take_offsets(list(range(10)))
|
||||
|
||||
|
||||
def test_map_projection_and_schema(some_permutation: Permutation):
|
||||
"""Test the selection and schema describe the read that feeds the callbacks."""
|
||||
|
||||
def to_str(row):
|
||||
return {name: str(value) for name, value in row.items()}
|
||||
|
||||
mapped = some_permutation.map(to_str)
|
||||
assert mapped.schema == some_permutation.schema
|
||||
assert mapped.column_names == ["id", "value"]
|
||||
|
||||
for projected in (
|
||||
some_permutation.select_columns(["id"]).map(to_str),
|
||||
mapped.select_columns(["id"]),
|
||||
mapped.remove_columns(["value"]),
|
||||
):
|
||||
assert projected.schema == some_permutation.select_columns(["id"]).schema
|
||||
assert list(projected.take_offsets([0])[0]) == ["id"]
|
||||
|
||||
renamed = mapped.rename_column("value", "data")
|
||||
assert renamed.column_names == ["id", "data"]
|
||||
assert list(renamed.take_offsets([0])[0]) == ["id", "data"]
|
||||
|
||||
|
||||
def test_map_is_lazy(some_permutation: Permutation):
|
||||
"""Test .map() does not call fn until iteration."""
|
||||
call_count = [0]
|
||||
|
||||
def counting_fn(row):
|
||||
call_count[0] += 1
|
||||
return row
|
||||
|
||||
mapped = some_permutation.map(counting_fn)
|
||||
assert call_count[0] == 0
|
||||
|
||||
mapped.__getitems__([0])
|
||||
assert call_count[0] == 1
|
||||
|
||||
|
||||
def test_map_non_callable(some_permutation: Permutation):
|
||||
"""Test .map() raises TypeError for non-callable fn."""
|
||||
with pytest.raises(TypeError, match="fn must be callable"):
|
||||
some_permutation.map("not a function")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fn, batched", [(_double_value_row, False), (_double_value_batch, True)]
|
||||
)
|
||||
def test_map_pickle_round_trip(some_permutation: Permutation, fn, batched):
|
||||
"""Test a mapped permutation reads the same data after a pickle round trip."""
|
||||
import pickle
|
||||
|
||||
mapped = some_permutation.map(fn, batched=batched)
|
||||
restored = pickle.loads(pickle.dumps(mapped))
|
||||
|
||||
offsets = [3, 1, 3]
|
||||
assert restored.take_offsets(offsets) == mapped.take_offsets(offsets)
|
||||
assert restored.take_offsets(offsets)[0]["value"] == (
|
||||
some_permutation.take_offsets(offsets)[0]["value"] * 2
|
||||
)
|
||||
# The restored permutation keeps enforcing the map / format constraint
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
restored.with_format("arrow")
|
||||
explicit = pickle.loads(pickle.dumps(some_permutation.with_format("arrow")))
|
||||
with pytest.raises(ValueError, match="map cannot be combined"):
|
||||
explicit.map(fn, batched=batched)
|
||||
|
||||
@@ -69,6 +69,36 @@ def _blob_query_data():
|
||||
)
|
||||
|
||||
|
||||
def _fragment_query_data():
|
||||
return pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
||||
"text": pa.array(["one", "two", "three", "four"], pa.utf8()),
|
||||
"vector": pa.array(
|
||||
[[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]],
|
||||
type=pa.list_(pa.float32(), list_size=2),
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _fragment_query_table(db, name):
|
||||
data = _fragment_query_data()
|
||||
table = db.create_table(name, data.slice(0, 2))
|
||||
table.add(data.slice(2, 2))
|
||||
return table
|
||||
|
||||
|
||||
def _apply_fragment_restriction(query, restriction, fragment):
|
||||
if restriction == "ids":
|
||||
return query.fragment_ids([fragment.fragment_id])
|
||||
if restriction == "empty":
|
||||
return query.fragment_ids([])
|
||||
if restriction == "fragments":
|
||||
return query.with_fragments([fragment])
|
||||
raise AssertionError(f"unknown restriction: {restriction}")
|
||||
|
||||
|
||||
def _create_blob_v2_query_table(db, name):
|
||||
schema = pa.schema(
|
||||
[
|
||||
@@ -348,7 +378,7 @@ def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
||||
def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
|
||||
def test_plain_scan_query_to_pandas_blob_mode_uses_native_path(
|
||||
tmp_db, monkeypatch, blob_mode
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
@@ -362,7 +392,8 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
|
||||
def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("to_arrow should not be called before native pandas")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
if blob_mode == "descriptions":
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
df = query.to_pandas(blob_mode=blob_mode)
|
||||
|
||||
@@ -434,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db):
|
||||
)
|
||||
assert df_by_fragment["id"].tolist() == [1, 2]
|
||||
|
||||
empty = (
|
||||
table.search()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([])
|
||||
.to_pandas(blob_mode="descriptions")
|
||||
)
|
||||
assert empty.empty
|
||||
with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"):
|
||||
(
|
||||
table.search()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([999])
|
||||
.to_pandas(blob_mode="descriptions")
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"terminal",
|
||||
[
|
||||
"to_arrow",
|
||||
"to_batches",
|
||||
"to_pandas",
|
||||
"to_polars",
|
||||
"to_list",
|
||||
"explain_plan",
|
||||
"analyze_plan",
|
||||
],
|
||||
)
|
||||
def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal):
|
||||
pytest.importorskip("lance")
|
||||
table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}")
|
||||
fragment_id = table.to_lance().get_fragments()[0].fragment_id
|
||||
query = table.search().fragment_ids([fragment_id])
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
getattr(query, terminal)()
|
||||
|
||||
|
||||
def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db):
|
||||
pytest.importorskip("lance")
|
||||
table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments")
|
||||
fragment = table.to_lance().get_fragments()[0]
|
||||
|
||||
for query in (
|
||||
table.search().with_fragments([fragment]),
|
||||
table.search([0.0, 0.0]).with_fragments([fragment]),
|
||||
):
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
||||
def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction):
|
||||
pytest.importorskip("lance")
|
||||
table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}")
|
||||
table.create_index("text", config=FTS(with_position=False))
|
||||
fragment = table.to_lance().get_fragments()[1]
|
||||
query = _apply_fragment_restriction(
|
||||
table.search("one", query_type="fts"), restriction, fragment
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
query.count_rows()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"terminal",
|
||||
[
|
||||
"to_arrow",
|
||||
"to_batches",
|
||||
"to_pandas",
|
||||
"to_polars",
|
||||
"to_list",
|
||||
"explain_plan",
|
||||
"analyze_plan",
|
||||
],
|
||||
)
|
||||
async def test_async_fragment_constraints_fail_loud_on_unsupported_paths(
|
||||
tmp_db_async, terminal
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
f"async_fragment_guard_{terminal}", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
query = table.query().fragment_ids([fragments[0].fragment_id])
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await getattr(query, terminal)()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries(
|
||||
tmp_db_async,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"async_fragment_guard_with_fragments", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
|
||||
for query in (
|
||||
table.query().with_fragments([fragments[0]]),
|
||||
table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]),
|
||||
):
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"async_fragment_supported",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
|
||||
df = await (
|
||||
table.query()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([fragments[1].fragment_id])
|
||||
.to_pandas(blob_mode="descriptions")
|
||||
)
|
||||
|
||||
assert df["id"].tolist() == [3, 4]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
||||
async def test_async_fts_count_rows_rejects_fragment_constraints(
|
||||
tmp_db_async, restriction
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
f"async_fts_count_rows_{restriction}", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.create_index("text", config=FTS(with_position=False))
|
||||
fragment = (await table.to_lance()).get_fragments()[1]
|
||||
query = _apply_fragment_restriction(
|
||||
table.query().nearest_to_text("one"), restriction, fragment
|
||||
)
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.count_rows()
|
||||
|
||||
transitioned = _apply_fragment_restriction(
|
||||
table.query(), restriction, fragment
|
||||
).nearest_to_text("one")
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await transitioned.count_rows()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
|
||||
@pytest.mark.parametrize(
|
||||
"transition",
|
||||
["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"],
|
||||
)
|
||||
async def test_async_fragment_constraints_survive_query_transitions(
|
||||
tmp_db_async, transition, restriction
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _fragment_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
f"async_transition_{transition}_{restriction}", data.slice(0, 2)
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.create_index("text", config=FTS(with_position=False))
|
||||
fragment = (await table.to_lance()).get_fragments()[1]
|
||||
|
||||
if transition == "query_to_vector":
|
||||
query = _apply_fragment_restriction(
|
||||
table.query(), restriction, fragment
|
||||
).nearest_to([0.0, 0.0])
|
||||
elif transition == "query_to_fts":
|
||||
query = _apply_fragment_restriction(
|
||||
table.query(), restriction, fragment
|
||||
).nearest_to_text("one")
|
||||
elif transition == "fts_to_hybrid":
|
||||
query = _apply_fragment_restriction(
|
||||
table.query().nearest_to_text("one"), restriction, fragment
|
||||
).nearest_to([0.0, 0.0])
|
||||
else:
|
||||
query = _apply_fragment_restriction(
|
||||
table.query().nearest_to([0.0, 0.0]), restriction, fragment
|
||||
).nearest_to_text("one")
|
||||
|
||||
with pytest.raises(NotImplementedError, match="fragment selection"):
|
||||
await query.to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async):
|
||||
@@ -488,7 +720,7 @@ async def test_async_plain_scan_query_to_pandas_blob_bytes_projection(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
||||
async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
|
||||
async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path(
|
||||
tmp_db_async, monkeypatch, blob_mode
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
@@ -502,7 +734,8 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow
|
||||
async def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("to_arrow should not be called before native pandas")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
if blob_mode == "descriptions":
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
df = await query.to_pandas(blob_mode=blob_mode)
|
||||
|
||||
@@ -541,12 +774,14 @@ def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db):
|
||||
df = query.to_pandas(blob_mode="descriptions")
|
||||
assert df["blob"].tolist() == [{"position": 0, "size": 3}]
|
||||
|
||||
with pytest.raises(ValueError, match="legacy blob columns"):
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
||||
query.to_pandas(blob_mode="bytes")
|
||||
with pytest.raises(ValueError, match="legacy blob columns"):
|
||||
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
|
||||
query.to_arrow(blob_mode="bytes")
|
||||
with pytest.raises(ValueError, match="legacy blob columns"):
|
||||
table.to_arrow(blob_mode="bytes")
|
||||
table_arrow = table.to_arrow(blob_mode="bytes")
|
||||
assert table_arrow.schema.field("blob").type == pa.large_binary()
|
||||
assert "_rowid" not in table_arrow.column_names
|
||||
assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"]
|
||||
assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [
|
||||
b"one",
|
||||
b"two",
|
||||
@@ -740,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
|
||||
|
||||
df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
|
||||
assert set(df["blob"]) == {b"two", b"three"}
|
||||
ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["blob"].tolist() == [b"three", b"two"]
|
||||
|
||||
|
||||
def test_order_by_plain_query(mem_db):
|
||||
@@ -807,6 +1046,308 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection):
|
||||
]
|
||||
|
||||
|
||||
def test_order_by_accepts_strings_tuples_and_dicts(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"test_order_by_forms",
|
||||
pa.table(
|
||||
{
|
||||
"group": [1, 1, 1, 2],
|
||||
"score": [None, 1.0, 1.0, 0.5],
|
||||
"name": ["z", "b", "a", "c"],
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
rows = (
|
||||
table.search()
|
||||
.order_by(
|
||||
[
|
||||
"group",
|
||||
("score", "desc"),
|
||||
{"column_name": "name", "ascending": True},
|
||||
]
|
||||
)
|
||||
.select(["name"])
|
||||
.to_list()
|
||||
)
|
||||
assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}]
|
||||
|
||||
# A bare tuple is one direction pair; a list holds separate orderings.
|
||||
assert table.search().order_by("name").select(["name"]).to_list() == [
|
||||
{"name": "a"},
|
||||
{"name": "b"},
|
||||
{"name": "c"},
|
||||
{"name": "z"},
|
||||
]
|
||||
assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [
|
||||
{"name": "z"},
|
||||
{"name": "c"},
|
||||
{"name": "b"},
|
||||
{"name": "a"},
|
||||
]
|
||||
assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [
|
||||
{"name": "a"},
|
||||
{"name": "b"},
|
||||
{"name": "z"},
|
||||
{"name": "c"},
|
||||
]
|
||||
|
||||
|
||||
def test_order_by_clears_with_none_and_empty_list(mem_db):
|
||||
table = mem_db.create_table("test_order_by_clear", [{"name": "a"}])
|
||||
|
||||
query = table.search().order_by("name")
|
||||
assert query.to_query_object().order_by is not None
|
||||
assert query.order_by(None).to_query_object().order_by is None
|
||||
assert query.order_by([]).to_query_object().order_by is None
|
||||
|
||||
|
||||
def test_scan_in_order_plain_query(tmp_db):
|
||||
table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]}))
|
||||
table.add(pa.table({"id": [2, 3]}))
|
||||
table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
assert len(fragments) == 3, "the test needs real multi-fragment data"
|
||||
|
||||
version = table.version
|
||||
table.checkout(version)
|
||||
|
||||
default = table.search().select(["id"]).to_arrow()["id"].to_pylist()
|
||||
assert default == [0, 1, 2, 3, 4, 5]
|
||||
assert table.search().to_query_object().scan_in_order is None
|
||||
|
||||
ordered = table.search().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
repeated = table.search().scan_in_order(True).select(["id"]).to_arrow()
|
||||
assert repeated.equals(ordered)
|
||||
|
||||
unordered = (
|
||||
table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist()
|
||||
)
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
sorted_desc = (
|
||||
table.search()
|
||||
.scan_in_order(False)
|
||||
.order_by(("id", "desc"))
|
||||
.select(["id"])
|
||||
.to_arrow()["id"]
|
||||
.to_pylist()
|
||||
)
|
||||
assert sorted_desc == [5, 4, 3, 2, 1, 0]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
table.search().scan_in_order().order_by("id").to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection):
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_async", pa.table({"id": [0, 1]})
|
||||
)
|
||||
await table.add(pa.table({"id": [2, 3]}))
|
||||
await table.add(pa.table({"id": [4, 5]}))
|
||||
|
||||
assert len((await table.to_lance()).get_fragments()) == 3
|
||||
version = await table.version()
|
||||
await table.checkout(version)
|
||||
|
||||
ordered = await table.query().scan_in_order().select(["id"]).to_arrow()
|
||||
assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5]
|
||||
assert table.query().to_query_object().scan_in_order is None
|
||||
|
||||
unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[
|
||||
"id"
|
||||
].to_pylist()
|
||||
assert sorted(unordered) == [0, 1, 2, 3, 4, 5]
|
||||
|
||||
with pytest.raises(ValueError, match="nonempty order_by"):
|
||||
await table.query().scan_in_order().order_by("id").to_arrow()
|
||||
with pytest.raises(ValueError, match="ranked results"):
|
||||
await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ordered", [False, True])
|
||||
def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
f"scan_in_order_scanner_{ordered}",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
|
||||
query = table.search().select(["id", "blob"]).scan_in_order(ordered)
|
||||
|
||||
def fail_to_arrow(*args, **kwargs):
|
||||
raise AssertionError("scanner-backed pandas must not collect through to_arrow")
|
||||
|
||||
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
|
||||
|
||||
dataset = table.to_lance()
|
||||
dataset_cls = type(dataset)
|
||||
real_scanner = dataset_cls.scanner
|
||||
captured = {}
|
||||
|
||||
def capture_scanner(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return real_scanner(self, **kwargs)
|
||||
|
||||
monkeypatch.setattr(dataset_cls, "scanner", capture_scanner)
|
||||
|
||||
df = query.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
|
||||
assert captured["scan_in_order"] is ordered
|
||||
assert captured.get("use_scalar_index") is (False if ordered else None)
|
||||
assert sorted(df["id"].tolist()) == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("storage_version", ["legacy", "stable"])
|
||||
def test_scan_in_order_indexed_filter_preserves_manifest_order(
|
||||
tmp_path, storage_version
|
||||
):
|
||||
lance = pytest.importorskip("lance")
|
||||
data = pa.table({"id": list(range(20)), "value": list(range(20))})
|
||||
dataset = lance.write_dataset(
|
||||
data,
|
||||
tmp_path / "t.lance",
|
||||
data_storage_version=storage_version,
|
||||
max_rows_per_file=10,
|
||||
)
|
||||
dataset.create_scalar_index("value", "BTREE")
|
||||
version_before_update = dataset.version
|
||||
dataset.update({"value": "100"}, where="id = 0")
|
||||
|
||||
table = lancedb.connect(str(tmp_path)).open_table("t")
|
||||
for version in (version_before_update, dataset.version):
|
||||
table.checkout(version)
|
||||
base = table.search().scan_in_order(True).select(["id"]).limit(100)
|
||||
expected = base.to_arrow()["id"].to_pylist()
|
||||
actual = base.where("value < 1000").to_arrow()["id"].to_pylist()
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = tmp_db.create_table(
|
||||
"scan_in_order_fragments",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
table.add(data.slice(2, 2))
|
||||
table.checkout(table.version)
|
||||
|
||||
fragments = table.to_lance().get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
(
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.with_fragments(reversed_fragments)
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
# fragment_ids is already resolved from the manifest and stays ordered.
|
||||
df_by_id = (
|
||||
table.search()
|
||||
.scan_in_order()
|
||||
.select(["id", "blob"])
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(
|
||||
tmp_db_async,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
data = _blob_query_data()
|
||||
table = await tmp_db_async.create_table(
|
||||
"scan_in_order_fragments_async",
|
||||
data.slice(0, 2),
|
||||
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
|
||||
)
|
||||
await table.add(data.slice(2, 2))
|
||||
await table.checkout(await table.version())
|
||||
|
||||
fragments = (await table.to_lance()).get_fragments()
|
||||
reversed_fragments = fragments[::-1]
|
||||
with pytest.raises(ValueError, match="use fragment_ids"):
|
||||
await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.with_fragments(fragments[::-1])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
|
||||
df_by_id = await (
|
||||
table.query()
|
||||
.scan_in_order()
|
||||
.fragment_ids([fragment.fragment_id for fragment in reversed_fragments])
|
||||
.select(["id", "blob"])
|
||||
.to_pandas(blob_mode="descriptions", flatten=True)
|
||||
)
|
||||
assert df_by_id["id"].tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_order_by_rejects_invalid_input_early(mem_db):
|
||||
table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
|
||||
|
||||
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
||||
table.search().order_by([{"column": "name", "ascending": True}])
|
||||
with pytest.raises(ValueError, match="missing 'column_name'"):
|
||||
table.search().order_by({"ascending": True})
|
||||
with pytest.raises(ValueError, match="invalid direction"):
|
||||
table.search().order_by([("name", "sideways")])
|
||||
with pytest.raises(TypeError, match="must be a column name"):
|
||||
table.search().order_by([42])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection):
|
||||
table = await mem_db_async.create_table(
|
||||
"test_order_by_async_forms",
|
||||
pa.table({"name": ["z", "b", "a", "c"]}),
|
||||
)
|
||||
|
||||
rows = await (
|
||||
table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow()
|
||||
)
|
||||
assert rows["name"].to_pylist() == ["z", "c", "b", "a"]
|
||||
|
||||
query = table.query().order_by("name")
|
||||
assert query.to_query_object().order_by is not None
|
||||
assert query.order_by(None).to_query_object().order_by is None
|
||||
assert query.order_by([]).to_query_object().order_by is None
|
||||
|
||||
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
||||
table.query().order_by([{"column": "name"}])
|
||||
|
||||
|
||||
def test_column_ordering_is_exported_at_top_level():
|
||||
assert lancedb.ColumnOrdering is ColumnOrdering
|
||||
|
||||
|
||||
def test_order_by_hybrid_sync_is_explicitly_unsupported(table):
|
||||
query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a")
|
||||
|
||||
with pytest.raises(NotImplementedError, match="order_by is not supported"):
|
||||
query.order_by(["id"])
|
||||
|
||||
# Clearing is still allowed, and invalid input still fails on its own terms.
|
||||
query.order_by(None)
|
||||
query.order_by([])
|
||||
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
|
||||
query.order_by([{"column": "id"}])
|
||||
|
||||
|
||||
def test_query_builder(table):
|
||||
rs = (
|
||||
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
||||
@@ -1397,18 +1938,16 @@ def test_query_builder_with_different_vector_column():
|
||||
ds = mock.Mock()
|
||||
table.to_lance.return_value = ds
|
||||
builder.to_arrow()
|
||||
table._execute_query.assert_called_once_with(
|
||||
Query(
|
||||
vector=query,
|
||||
filter="b < 10",
|
||||
limit=2,
|
||||
distance_type="cosine",
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
),
|
||||
batch_size=None,
|
||||
timeout=None,
|
||||
expected = Query(
|
||||
vector=query,
|
||||
filter="b < 10",
|
||||
limit=2,
|
||||
distance_type="cosine",
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
)
|
||||
expected._blob_row_id_prepared = True
|
||||
table._execute_arrow.assert_called_once_with(expected, timeout=None)
|
||||
|
||||
|
||||
def cosine_distance(vec1, vec2):
|
||||
@@ -2316,6 +2855,61 @@ def test_query_schema(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"test",
|
||||
pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"vector": pa.array(
|
||||
[[1, 2], [3, 4], [5, 6]],
|
||||
pa.list_(pa.float32(), list_size=2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
calls = 0
|
||||
original = AsyncTable._schema_sync
|
||||
|
||||
def counted(self):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return original(self)
|
||||
|
||||
monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
|
||||
|
||||
table.search().where("id = 1").select(["id"]).to_arrow()
|
||||
assert calls <= 1
|
||||
|
||||
calls = 0
|
||||
table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
|
||||
assert calls <= 1
|
||||
|
||||
calls = 0
|
||||
table.search([1, 2]).limit(1).to_arrow()
|
||||
# At most one lookup infers the vector column, one prepares execution.
|
||||
assert calls <= 2
|
||||
|
||||
calls = 0
|
||||
table.search().where("id = 1").select(["id"]).to_batches().read_all()
|
||||
assert calls <= 1
|
||||
|
||||
builder = table.search().where("id = 1")
|
||||
before = builder.to_arrow()
|
||||
assert "extra" not in before.column_names
|
||||
assert "image" not in before.column_names
|
||||
|
||||
table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
|
||||
calls = 0
|
||||
after = builder.to_arrow()
|
||||
assert calls <= 1
|
||||
assert after["extra"].to_pylist() == [None]
|
||||
assert "_lance_row_id" in str(after.schema)
|
||||
assert "_rowid" not in after.column_names
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_schema_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
@@ -2417,13 +3011,116 @@ def test_take_queries(tmp_path):
|
||||
assert sorted(converted["idx"].to_pylist()) == [2, 5, 5, 17]
|
||||
|
||||
# Take by row id
|
||||
assert list(
|
||||
sorted(table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list())
|
||||
) == [
|
||||
2,
|
||||
5,
|
||||
17,
|
||||
]
|
||||
assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
|
||||
|
||||
|
||||
def test_take_offsets_preserve_order_sync(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test", pa.table({"idx": range(4)}))
|
||||
table.add(pa.table({"idx": range(4, 8)}))
|
||||
table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
batches = list(
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
# The default path keeps its unspecified-order behavior.
|
||||
default = table.take_offsets(requested).select(["idx"]).to_arrow()
|
||||
assert sorted(default["idx"].to_pylist()) == sorted(expected)
|
||||
|
||||
assert table.take_offsets(requested).to_query_object().preserve_order is None
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
|
||||
|
||||
empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
|
||||
assert empty.num_rows == 0
|
||||
assert empty.column_names == ["idx"]
|
||||
|
||||
query.order_by = [ColumnOrdering(column_name="idx")]
|
||||
with pytest.raises(
|
||||
ValueError, match="preserve_order cannot be combined with an explicit order_by"
|
||||
):
|
||||
table._execute_query(query)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_take_offsets_preserve_order_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", pa.table({"idx": range(4)}))
|
||||
await table.add(pa.table({"idx": range(4, 8)}))
|
||||
await table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
reader = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
batches = [batch async for batch in reader]
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
|
||||
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": [0, 1]}))
|
||||
table.add(pa.table({"idx": [2, 3]}))
|
||||
rows = table.search().with_row_id(True).to_arrow().to_pylist()
|
||||
row_ids = {row["idx"]: row["_rowid"] for row in rows}
|
||||
table.delete("idx = 1")
|
||||
requested = (
|
||||
[] if empty else [row_ids[3], row_ids[1], row_ids[3], 2**64 - 1, row_ids[0]]
|
||||
)
|
||||
take = table.take_row_ids(requested)
|
||||
if selection is not None:
|
||||
take = take.select(selection)
|
||||
actual = take.to_arrow()
|
||||
assert actual.num_rows == (0 if empty else 3)
|
||||
if selection == {"_rowid": "100 - idx"}:
|
||||
assert actual.column_names == ["_rowid"]
|
||||
assert actual["_rowid"].to_pylist() == ([] if empty else [97, 97, 100])
|
||||
elif selection == []:
|
||||
assert actual.num_columns == 0
|
||||
else:
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == ([] if empty else [3, 3, 0])
|
||||
query = take.to_query_object()
|
||||
assert query.take_row_ids == requested
|
||||
assert table._execute_query(query).read_all() == actual
|
||||
|
||||
|
||||
def test_take_queries_with_row_id(tmp_path):
|
||||
@@ -2432,6 +3129,7 @@ def test_take_queries_with_row_id(tmp_path):
|
||||
|
||||
by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_row_id.column_names
|
||||
assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
|
||||
by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_offset.column_names
|
||||
|
||||
@@ -2446,6 +3144,7 @@ async def test_take_queries_with_row_id_async(tmp_path):
|
||||
|
||||
by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_row_id.column_names
|
||||
assert by_row_id["_rowid"].to_pylist() == [5, 2, 17]
|
||||
by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
|
||||
assert "_rowid" in by_offset.column_names
|
||||
|
||||
@@ -2472,16 +3171,12 @@ def test_take_queries_to_batches(tmp_path):
|
||||
rs = list(table.take_row_ids([5, 2, 17]).to_batches())
|
||||
assert all(isinstance(b, pa.RecordBatch) for b in rs)
|
||||
assert sum(b.num_rows for b in rs) == 3
|
||||
assert sorted(v for b in rs for v in b.column("idx").to_pylist()) == [2, 5, 17]
|
||||
assert [v for b in rs for v in b.column("idx").to_pylist()] == [5, 2, 17]
|
||||
|
||||
# Take with select projection → to_batches preserves the projection
|
||||
rs = list(table.take_row_ids([5, 2, 17]).select(["label"]).to_batches())
|
||||
assert all(b.schema.names == ["label"] for b in rs)
|
||||
assert sorted(v for b in rs for v in b.column("label").to_pylist()) == [
|
||||
"17",
|
||||
"2",
|
||||
"5",
|
||||
]
|
||||
assert [v for b in rs for v in b.column("label").to_pylist()] == ["5", "2", "17"]
|
||||
|
||||
|
||||
def test_getitems(tmp_path):
|
||||
@@ -2505,6 +3200,13 @@ def test_getitems(tmp_path):
|
||||
assert table.__getitems__(offsets) == pa.table({"idx": offsets})
|
||||
|
||||
|
||||
def test_getitems_rejects_missing_offsets(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
|
||||
|
||||
with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
|
||||
table.__getitems__([0, 99])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_timeout_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
@@ -2637,17 +3339,24 @@ def test_blob_v2_to_batches_row_id(tmp_db):
|
||||
assert [blobs[i].as_py() for i in range(len(blobs))] == [b"one", b"two"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metric", ["l2", "cosine", "dot"])
|
||||
@pytest.mark.parametrize(
|
||||
"effort,probes", [(None, 4), (0, 1), (0.25, 2), (0.5, 4), (0.75, 8), (1, 16)]
|
||||
"metric,probes80,probes90", [("l2", 2, 3), ("cosine", 1, 2), ("dot", 1, 2)]
|
||||
)
|
||||
def test_search_effort_probe_budget(tmp_path, monkeypatch, metric, effort, probes):
|
||||
@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
|
||||
def test_search_effort_probe_budget(
|
||||
tmp_path, monkeypatch, metric, effort, probes80, probes90
|
||||
):
|
||||
import re
|
||||
from lancedb.index import IvfFlat
|
||||
|
||||
monkeypatch.setenv("LANCE_AUTO_PROBE_MARGIN", "0")
|
||||
monkeypatch.setenv("LANCE_AUTO_MIN_INITIAL_NPROBES", "4")
|
||||
monkeypatch.setenv("LANCE_AUTO_MAX_INITIAL_NPROBES", "4")
|
||||
# The lower tiers use metric/k calibration; Auto and the upper tiers retain
|
||||
# their existing budgets. Keep exact execution counts and precedence checks.
|
||||
probes = {None: 4, 0: 1, 0.1: probes80, 0.25: probes90, 0.5: 4, 0.75: 8, 1: 16}[
|
||||
effort
|
||||
]
|
||||
rng = np.random.default_rng(42)
|
||||
vectors = np.repeat(np.eye(16, dtype=np.float32), 32, axis=0)
|
||||
vectors += rng.normal(0, 0.001, vectors.shape).astype(np.float32)
|
||||
@@ -2731,7 +3440,7 @@ def test_search_effort_invalid_sync(table, effort):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("hybrid", [False, True])
|
||||
@pytest.mark.parametrize("effort", [None, 0, 0.25, 0.5, 0.75, 1])
|
||||
@pytest.mark.parametrize("effort", [None, 0, 0.1, 0.25, 0.5, 0.75, 1])
|
||||
async def test_search_effort_async_roundtrip(table_async, hybrid, effort):
|
||||
query = table_async.vector_search([0, 0])
|
||||
if hybrid:
|
||||
|
||||
+3688
-156
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)
|
||||
@@ -20,25 +22,48 @@ NIL_QUERY_ID = UUID(int=0)
|
||||
|
||||
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())
|
||||
|
||||
@@ -68,6 +93,15 @@ def test_query_id_is_uuid():
|
||||
assert Query(query).id == query.id
|
||||
|
||||
|
||||
def test_query_job_id_is_optional_and_separate_from_query_id():
|
||||
native = FakeNativeQuery()
|
||||
native.job_id = "j1-durable"
|
||||
query = AsyncQuery(native)
|
||||
assert query.id != query.job_id
|
||||
assert query.job_id == "j1-durable"
|
||||
assert Query(query).job_id == "j1-durable"
|
||||
|
||||
|
||||
def test_connection_serializes_sql_host_override():
|
||||
endpoint = "grpc+tls://sql.example.com:10026"
|
||||
restored = lancedb.deserialize_conn(
|
||||
@@ -283,6 +317,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent():
|
||||
assert echoed.column("k").to_pylist() == [10]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("exist_ok", "status"),
|
||||
[
|
||||
(None, "created"),
|
||||
(False, "created"),
|
||||
(True, "created"),
|
||||
(True, "already_exists"),
|
||||
],
|
||||
)
|
||||
async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class SecretServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.writes = []
|
||||
|
||||
def do_exchange(self, context, descriptor, reader, writer):
|
||||
self.writes.append((descriptor.command, reader.read_all()))
|
||||
result = pa.table({"status": [status]})
|
||||
writer.begin(result.schema)
|
||||
writer.write_table(result)
|
||||
writer.close()
|
||||
|
||||
with SecretServer() as server:
|
||||
options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {"namespace_path": ["team", "production"]}
|
||||
if exist_ok is not None:
|
||||
kwargs["exist_ok"] = exist_ok
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async("db://analytics", **options)
|
||||
await db.create_secret("api-key", "credential's value", **kwargs)
|
||||
else:
|
||||
db = lancedb.connect("db://analytics", **options)
|
||||
db.create_secret("api-key", "credential's value", **kwargs)
|
||||
((command, parameters),) = server.writes
|
||||
|
||||
prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET"
|
||||
sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1'
|
||||
assert sql.encode() in command
|
||||
assert b"credential's value" not in command
|
||||
assert parameters.column(0).to_pylist() == ["credential's value"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("job_id", [None, "sql-job-1"])
|
||||
def test_sql_input_error_metadata_crosses_native_boundary(job_id):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
@@ -341,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)]
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -39,9 +40,37 @@ def remote_server(text_type=pa.string()):
|
||||
command = ticket.ticket
|
||||
calls.append(command)
|
||||
if b"SHOW STORAGE INTEGRATIONS" in command:
|
||||
result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
|
||||
match = re.search(
|
||||
rb'SHOW STORAGE INTEGRATIONS IN "public" '
|
||||
rb"LIMIT (\d+)(?: FROM '([^']+)')?",
|
||||
command,
|
||||
)
|
||||
assert match is not None, command
|
||||
limit = int(match.group(1))
|
||||
names = [NAME, "zeta"]
|
||||
if match.group(2) is not None:
|
||||
assert match.group(2) == b"server-storage-page", command
|
||||
names = names[1:]
|
||||
page = names[:limit]
|
||||
result = pa.table(
|
||||
{
|
||||
"namespace_path": pa.array(
|
||||
["[]"] * len(page), type=pa.string()
|
||||
),
|
||||
"name": pa.array(page, type=text_type),
|
||||
}
|
||||
)
|
||||
if len(names) > limit:
|
||||
result = result.replace_schema_metadata(
|
||||
{b"lancedb.next_page_token": b"server-storage-page"}
|
||||
)
|
||||
elif b"DROP STORAGE INTEGRATION" in command:
|
||||
result = pa.table({"dropped": [True]})
|
||||
elif b"DESCRIBE STORAGE INTEGRATION" in command:
|
||||
assert b"FORMAT JSON" in command
|
||||
result = pa.table(
|
||||
{"description": [json.dumps(info)]}
|
||||
).replace_schema_metadata({b"lancedb.describe.format": b"json"})
|
||||
else:
|
||||
if b"STORAGE_PROVIDER = 'HUGGINGFACE'" in command:
|
||||
info.update(
|
||||
@@ -94,14 +123,23 @@ def remote_server(text_type=pa.string()):
|
||||
trust_policy=None,
|
||||
permissions_policy=None,
|
||||
)
|
||||
for field, name in (
|
||||
("azure_tenant_id_secret", "tenant"),
|
||||
("azure_client_id_secret", "client"),
|
||||
("azure_client_secret_secret", "credential"),
|
||||
):
|
||||
info[field] = dict(
|
||||
database="shared", namespace_path=["credentials"], name=name
|
||||
if b"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET" in command:
|
||||
info["azure_storage_account_access_key_secret"] = dict(
|
||||
database="shared",
|
||||
namespace_path=["credentials"],
|
||||
name="blob_key",
|
||||
)
|
||||
else:
|
||||
for field, name in (
|
||||
("azure_tenant_id_secret", "tenant"),
|
||||
("azure_client_id_secret", "client"),
|
||||
("azure_client_secret_secret", "credential"),
|
||||
):
|
||||
info[field] = dict(
|
||||
database="shared",
|
||||
namespace_path=["credentials"],
|
||||
name=name,
|
||||
)
|
||||
if b"STORAGE_AWS_ACCESS_KEY_ID_SECRET" in command:
|
||||
info["aws_role_arn"] = None
|
||||
info["trust_policy"] = None
|
||||
@@ -125,6 +163,7 @@ def remote_server(text_type=pa.string()):
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
"azure_storage_account_access_key_secret",
|
||||
"gcp_credentials_json_secret",
|
||||
"huggingface_token_secret",
|
||||
]:
|
||||
@@ -195,6 +234,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
|
||||
assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0]
|
||||
assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0]
|
||||
assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1]
|
||||
listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call]
|
||||
assert len(listings) == 2
|
||||
assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0]
|
||||
assert b"FROM 'server-storage-page'" in listings[1]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -311,6 +354,44 @@ def test_azure_lifecycle_uses_three_qualified_secret_references(text_type):
|
||||
assert b"STORAGE_AWS" not in sql
|
||||
|
||||
|
||||
def test_azure_lifecycle_uses_one_qualified_account_access_key_secret():
|
||||
with remote_server() as (host, calls):
|
||||
db = connect(host)
|
||||
key = SecretReference(
|
||||
"blob_key", database="shared", namespace_path=("credentials",)
|
||||
)
|
||||
config = {
|
||||
"storage_provider": "AZURE",
|
||||
"azure_storage_account": "customeraccount",
|
||||
"azure_storage_account_access_key_secret": key,
|
||||
}
|
||||
with pytest.raises(ValueError, match="service principal"):
|
||||
db.create_storage_integration(
|
||||
"blobs",
|
||||
"az://customer-data/raw/",
|
||||
azure_client_id_secret="client",
|
||||
**config,
|
||||
)
|
||||
assert calls == []
|
||||
|
||||
info = db.create_storage_integration(
|
||||
"blobs", "az://customer-data/raw/", **config
|
||||
)
|
||||
reference = info.azure_storage_account_access_key_secret
|
||||
assert reference is not None
|
||||
assert reference.name == key.name
|
||||
assert reference.database == key.database
|
||||
assert tuple(reference.namespace_path) == key.namespace_path
|
||||
assert info.azure_tenant_id_secret is None
|
||||
assert info.azure_client_id_secret is None
|
||||
assert info.azure_client_secret_secret is None
|
||||
assert db.describe_storage_integration("blobs") == info
|
||||
assert (
|
||||
b"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET = "
|
||||
b'"shared"."credentials"."blob_key"' in calls[0]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_azure_requires_account_and_all_three_secret_references():
|
||||
with remote_server() as (host, calls):
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("exist_ok", "existing"),
|
||||
[(None, False), (False, False), (True, False), (True, True)],
|
||||
)
|
||||
async def test_storage_integration_exist_ok_preserves_server_metadata(
|
||||
asynchronous, exist_ok, existing
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
fixture = (
|
||||
Path(__file__).parents[3]
|
||||
/ "rust/lancedb/tests/fixtures/storage_integration.json"
|
||||
)
|
||||
stored = json.loads(fixture.read_text())
|
||||
stored["namespace_path"] = ["team"]
|
||||
columns = {}
|
||||
for key, value in stored.items():
|
||||
if isinstance(value, (dict, list)):
|
||||
value = json.dumps(value)
|
||||
columns[key] = pa.array([None], type=pa.string()) if value is None else [value]
|
||||
result = pa.table(columns)
|
||||
prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"]
|
||||
role = (
|
||||
"arn:aws:iam::999999999999:role/replacement"
|
||||
if existing
|
||||
else stored["aws_role_arn"]
|
||||
)
|
||||
|
||||
class IntegrationServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with IntegrationServer() as server:
|
||||
connection_options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
|
||||
kwargs.update(
|
||||
storage_provider="S3",
|
||||
storage_prefix=prefix,
|
||||
aws_role_arn=role,
|
||||
namespace_path=["team"],
|
||||
)
|
||||
uri = f"db://{stored['database']}"
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(uri, **connection_options)
|
||||
info = await db.create_storage_integration(stored["name"], **kwargs)
|
||||
else:
|
||||
db = lancedb.connect(uri, **connection_options)
|
||||
info = db.create_storage_integration(stored["name"], **kwargs)
|
||||
(request,) = server.requests
|
||||
|
||||
command = (
|
||||
"CREATE STORAGE INTEGRATION IF NOT EXISTS"
|
||||
if exist_ok
|
||||
else "CREATE STORAGE INTEGRATION"
|
||||
)
|
||||
assert f'{command} "raw"'.encode() in request
|
||||
assert prefix.encode() in request
|
||||
assert role.encode() in request
|
||||
assert info.storage_prefix == stored["storage_prefix"]
|
||||
assert info.aws_role_arn == stored["aws_role_arn"]
|
||||
assert info.aws_external_id == stored["aws_external_id"]
|
||||
assert info.created_at_millis == stored["created_at_millis"]
|
||||
assert info.namespace_path == ["team"]
|
||||
@@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table):
|
||||
]
|
||||
|
||||
|
||||
def respond(request, body):
|
||||
request.send_response(200)
|
||||
def respond(request, body, status=200):
|
||||
request.send_response(status)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(json.dumps(body).encode())
|
||||
@@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tables", [[], ["first", "last"]])
|
||||
def test_remote_len_and_contains_follow_pages(tables):
|
||||
def test_remote_len_paginates_and_contains_looks_up_table(tables):
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request.path)
|
||||
query = parse_qs(urlparse(request.path).query)
|
||||
url = urlparse(request.path)
|
||||
if request.command == "POST":
|
||||
name = url.path.split("/")[3]
|
||||
assert url.path == f"/v1/table/{name}/describe/"
|
||||
respond(request, {}, status=200 if name in tables else 404)
|
||||
return
|
||||
assert request.command == "GET"
|
||||
assert url.path == "/v1/namespace/$/table/list"
|
||||
query = parse_qs(url.query)
|
||||
if tables and "page_token" not in query:
|
||||
respond(request, {"tables": [tables[0]], "page_token": "opaque-next"})
|
||||
else:
|
||||
@@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables):
|
||||
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
assert len(db) == len(tables)
|
||||
assert ("last" in db) == bool(tables)
|
||||
assert "missing" not in db
|
||||
assert len(requests) == (2 if tables else 1)
|
||||
requests.clear()
|
||||
assert ("first" in db) == bool(tables)
|
||||
assert len(requests) == 1
|
||||
for name in ("last", "missing", "first"):
|
||||
assert (name in db) is (name in tables)
|
||||
assert requests == [f"/v1/table/{name}/describe/"]
|
||||
requests.clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("namespace", [[], ["parent", "child"]])
|
||||
|
||||
@@ -0,0 +1,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()
|
||||
@@ -1837,6 +2391,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Test with target_partition_size
|
||||
@@ -1862,6 +2417,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# target_partition_size has a default value,
|
||||
@@ -1886,6 +2442,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
table.create_index(
|
||||
@@ -1902,6 +2459,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
table.create_index(
|
||||
@@ -1922,6 +2480,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
table.create_index(
|
||||
@@ -1942,6 +2501,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -2073,6 +2633,7 @@ def test_create_index_name_and_train_parameters(
|
||||
wait_timeout=None,
|
||||
name="my_custom_index",
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Test with train=False
|
||||
@@ -2084,6 +2645,7 @@ def test_create_index_name_and_train_parameters(
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=False,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Test with both name and train
|
||||
@@ -2095,6 +2657,7 @@ def test_create_index_name_and_train_parameters(
|
||||
wait_timeout=None,
|
||||
name="my_index_name",
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -2132,6 +2695,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# Scalar index via new API
|
||||
@@ -2143,6 +2707,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
# FTS index via new API
|
||||
@@ -2154,6 +2719,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
|
||||
wait_timeout=None,
|
||||
name=None,
|
||||
train=True,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -3436,7 +4002,8 @@ def test_merge_insert(mem_db: DBConnection):
|
||||
table.merge_insert("a")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(new_data, timeout=timedelta(seconds=10))
|
||||
.use_index(False)
|
||||
.execute(new_data, timeout=timedelta(seconds=10), retries=0)
|
||||
)
|
||||
assert merge_insert_res.version == 2
|
||||
assert merge_insert_res.num_inserted_rows == 1
|
||||
@@ -3515,7 +4082,7 @@ def test_merge_insert(mem_db: DBConnection):
|
||||
# timeout
|
||||
with pytest.raises(Exception, match="merge insert timed out"):
|
||||
table.merge_insert("a").when_matched_update_all().execute(
|
||||
new_data, timeout=timedelta(0)
|
||||
new_data, timeout=timedelta(0), retries=255
|
||||
)
|
||||
|
||||
|
||||
@@ -5984,6 +6551,62 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
|
||||
getattr(table, method)("x", batch_size=batch_size)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
|
||||
@pytest.mark.parametrize(
|
||||
"refresh_kwargs,option",
|
||||
[
|
||||
({"retry_policy": lancedb.FunctionRetryPolicy(transient=True)}, "retry_policy"),
|
||||
({"where": "x > 0"}, "where"),
|
||||
({"error_policy": "skip"}, "error_policy"),
|
||||
({"max_failed_fraction": 0.5}, "max_failed_fraction"),
|
||||
({"max_failed_rows": 10}, "max_failed_rows"),
|
||||
({"row_timeout_seconds": 30}, "row_timeout_seconds"),
|
||||
({"init_timeout_seconds": 60}, "init_timeout_seconds"),
|
||||
({"max_concurrency": 4}, "max_concurrency"),
|
||||
({"publication_interval_rows": 60}, "publication_interval_rows"),
|
||||
(
|
||||
{"total_cpu_millis": 1000, "total_memory_bytes": 1024},
|
||||
"total_cpu_millis",
|
||||
),
|
||||
(
|
||||
{
|
||||
"supervisor_resources": {
|
||||
"cpu_millis": 1000,
|
||||
"memory_bytes": 1024,
|
||||
"ephemeral_storage_bytes": 2048,
|
||||
}
|
||||
},
|
||||
"supervisor_resources",
|
||||
),
|
||||
(
|
||||
{
|
||||
"planning_workers": {
|
||||
"resources": {
|
||||
"cpu_millis": 1000,
|
||||
"memory_bytes": 1024,
|
||||
"ephemeral_storage_bytes": 2048,
|
||||
},
|
||||
"max_workers": 2,
|
||||
"rows_per_worker": 100,
|
||||
"fragments_per_worker": 1,
|
||||
}
|
||||
},
|
||||
"planning_workers",
|
||||
),
|
||||
({"num_workers": 2}, "num_workers"),
|
||||
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
|
||||
],
|
||||
)
|
||||
def test_local_refresh_rejects_enterprise_options(
|
||||
tmp_path, method, refresh_kwargs, option
|
||||
):
|
||||
table = lancedb.connect(tmp_path).create_table("rows", [{"x": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match=f"{option} requires a LanceDB Enterprise refresh"
|
||||
):
|
||||
getattr(table, method)("x", **refresh_kwargs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
|
||||
@pytest.mark.parametrize("batch_size", [0, -1])
|
||||
@@ -6005,6 +6628,16 @@ def test_function_errors_are_remote_only(tmp_path):
|
||||
table.function_errors()
|
||||
|
||||
|
||||
def test_function_column_status_is_remote_only(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", [{"x": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError,
|
||||
match="exact Function column status is supported only in LanceDB Enterprise",
|
||||
):
|
||||
table.wait_fresh("x")
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.parametrize("batch_size", [None, 8])
|
||||
def test_refresh_column_async_returns_job(tmp_path, batch_size):
|
||||
@@ -6013,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
|
||||
@@ -6225,6 +6858,19 @@ def test_auto_refresh_options_require_computed_columns(tmp_path):
|
||||
table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True)
|
||||
|
||||
|
||||
def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("invalid_budget", [{"x": 1}])
|
||||
before = table.version
|
||||
with pytest.raises(ValueError, match="registered Function"):
|
||||
table.add_columns(
|
||||
computed={"doubled": "x * 2"},
|
||||
total_cpu_millis=1_000,
|
||||
total_memory_bytes=1_024,
|
||||
)
|
||||
assert table.version == before
|
||||
assert table.schema.names == ["x"]
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
|
||||
@@ -6236,3 +6882,108 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
|
||||
metadata = (await table.schema()).field("doubled").metadata
|
||||
assert metadata[b"computed_column.auto_refresh_enabled"] == b"true"
|
||||
assert b"computed_column.auto_refresh_interval_seconds" not in metadata
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method",
|
||||
["create_index", "create_index_async", "create_scalar_index", "create_fts_index"],
|
||||
)
|
||||
@pytest.mark.parametrize("name", [None, "kept_index"])
|
||||
def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name):
|
||||
table = mem_db.create_table(
|
||||
"keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)]
|
||||
)
|
||||
column = "text" if method == "create_fts_index" else "id"
|
||||
config = FTS() if column == "text" else BTree()
|
||||
table.create_index(column, config=config, name=name, exist_ok=True)
|
||||
before = table.version
|
||||
original = table.list_indices()
|
||||
kwargs = dict(name=name, exist_ok=True)
|
||||
if method in ("create_index", "create_index_async"):
|
||||
kwargs["config"] = config
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", DeprecationWarning)
|
||||
result = getattr(table, method)(column, **kwargs)
|
||||
if method == "create_index_async":
|
||||
result.wait()
|
||||
assert table.version == before
|
||||
assert [(index.name, index.index_type) for index in table.list_indices()] == [
|
||||
(index.name, index.index_type) for index in original
|
||||
]
|
||||
with pytest.raises((ValueError, RuntimeError), match="already exists"):
|
||||
table.create_index(column, config=config, name=name, replace=False)
|
||||
table.create_index(column, config=config, name=name)
|
||||
assert table.version > before
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"column,name,existing",
|
||||
[
|
||||
("vector", "kept", "kept"),
|
||||
("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"),
|
||||
],
|
||||
)
|
||||
def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing):
|
||||
dataset = MagicMock()
|
||||
dataset.list_indices.return_value = [{"name": existing}]
|
||||
with patch("lancedb.table._validate_index_accelerator") as validate:
|
||||
table_module._create_accelerated_index(
|
||||
dataset, column=column, accelerator="cuda", name=name, exist_ok=True
|
||||
)
|
||||
validate.assert_not_called()
|
||||
dataset.create_index.assert_not_called()
|
||||
|
||||
|
||||
def test_accelerated_index_exist_ok_preserves_concurrent_winner():
|
||||
dataset = MagicMock()
|
||||
dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]]
|
||||
dataset.create_index.side_effect = RuntimeError("concurrent create")
|
||||
with patch("lancedb.table._validate_index_accelerator"):
|
||||
table_module._create_accelerated_index(
|
||||
dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True
|
||||
)
|
||||
assert dataset.create_index.call_args.kwargs["replace"] is False
|
||||
assert dataset.create_index.call_args.kwargs["name"] == "vector_idx"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"])
|
||||
def test_index_exist_ok_matches_lance_default_name(mem_db, column):
|
||||
table = mem_db.create_table(
|
||||
"quoted_index",
|
||||
[{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}],
|
||||
)
|
||||
table.create_index(column, config=BTree())
|
||||
before = table.version
|
||||
table.create_index(column, config=BTree(), exist_ok=True)
|
||||
assert table.version == before
|
||||
assert len(table.list_indices()) == 1
|
||||
|
||||
|
||||
def test_fts_exist_ok_matches_quoted_default_name(mem_db):
|
||||
table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}])
|
||||
table.create_index("`body-text`", config=FTS())
|
||||
before = table.version
|
||||
table.create_index("`body-text`", config=FTS(), exist_ok=True)
|
||||
assert table.version == before
|
||||
assert len(table.list_indices()) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"method", ["prewarm_data", "prewarm_data_async", "explain_prewarm_data"]
|
||||
)
|
||||
async def test_data_prewarm_job_is_unsupported_locally(tmp_path, asynchronous, method):
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
await getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
else:
|
||||
table = lancedb.connect(tmp_path).create_table("prewarm", [{"id": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="only supported on remote tables"
|
||||
):
|
||||
getattr(table, method)(filter="id > 0", concurrency=2)
|
||||
|
||||
@@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table):
|
||||
}.items():
|
||||
assert getattr(config, name) == value
|
||||
assert kwargs == dict(
|
||||
wait_timeout=timeout, name="custom_idx", replace=False, train=False
|
||||
wait_timeout=timeout,
|
||||
name="custom_idx",
|
||||
replace=False,
|
||||
train=False,
|
||||
exist_ok=False,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -8,13 +8,15 @@ import json
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb.permutation import Permutation, Permutations, permutation_builder
|
||||
from lancedb.util import tbl_to_tensor
|
||||
from lancedb.util import batch_to_tensor, batch_to_tensor_columns, tbl_to_tensor
|
||||
from utils import start_server_thread
|
||||
|
||||
torch = pytest.importorskip("torch")
|
||||
@@ -23,6 +25,43 @@ torch = pytest.importorskip("torch")
|
||||
REMOTE_ROWS = list(range(100))
|
||||
|
||||
|
||||
def _identity_collate(batch):
|
||||
return batch
|
||||
|
||||
|
||||
class _LanceBFloat16Type(pa.ExtensionType):
|
||||
def __init__(self):
|
||||
pa.ExtensionType.__init__(self, pa.binary(2), "lance.bfloat16")
|
||||
|
||||
def __arrow_ext_serialize__(self):
|
||||
return b""
|
||||
|
||||
@classmethod
|
||||
def __arrow_ext_deserialize__(cls, storage_type, serialized):
|
||||
return cls()
|
||||
|
||||
|
||||
def _bf16_storage(values):
|
||||
bits = torch.tensor(values, dtype=torch.bfloat16).view(torch.int16).tolist()
|
||||
return [struct.pack("<H", bit & 0xFFFF) for bit in bits]
|
||||
|
||||
|
||||
def _bf16_array(values):
|
||||
storage = pa.array(_bf16_storage(values), type=pa.binary(2))
|
||||
return pa.ExtensionArray.from_storage(_LanceBFloat16Type(), storage)
|
||||
|
||||
|
||||
def _fixed_shape_tensor_array(physical_values, shape, permutation=None):
|
||||
tensor_type = pa.fixed_shape_tensor(
|
||||
pa.float32(), shape, permutation=permutation or []
|
||||
)
|
||||
flat_values = np.asarray(physical_values, dtype=np.float32).reshape(-1)
|
||||
storage = pa.FixedSizeListArray.from_arrays(
|
||||
pa.array(flat_values), int(np.prod(shape))
|
||||
)
|
||||
return pa.ExtensionArray.from_storage(tensor_type, storage)
|
||||
|
||||
|
||||
def _make_mock_http_handler(handler):
|
||||
class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
@@ -135,6 +174,23 @@ def _open_native_table(uri: str, table_name: str):
|
||||
return lancedb.connect(uri).open_table(table_name)
|
||||
|
||||
|
||||
class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset):
|
||||
"""User-style Dataset that keeps both the connection and table."""
|
||||
|
||||
def __init__(self, db, table):
|
||||
self._db = db
|
||||
self._table = table
|
||||
|
||||
def __len__(self):
|
||||
return self._table.count_rows()
|
||||
|
||||
def __getitem__(self, index):
|
||||
row = self._table.take_offsets([index]).to_arrow().to_pylist()[0]
|
||||
# Touch the connection too, so workers prove both objects were restored.
|
||||
row["db_uri"] = self._db.uri
|
||||
return row
|
||||
|
||||
|
||||
def test_table_dataloader(mem_db):
|
||||
table = mem_db.create_table("test_table", pa.table({"a": range(1000)}))
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
@@ -229,6 +285,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db):
|
||||
assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("start_method", ["spawn", "forkserver"])
|
||||
def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method):
|
||||
if start_method not in mp.get_all_start_methods():
|
||||
pytest.skip(f"{start_method} start method is not available")
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test_table", pa.table({"a": range(20)}))
|
||||
dataset = _DatasetHoldingConnectionAndTable(db, table)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
dataset,
|
||||
batch_size=4,
|
||||
num_workers=2,
|
||||
multiprocessing_context=start_method,
|
||||
)
|
||||
|
||||
seen = []
|
||||
expected_uri = str(tmp_path)
|
||||
for batch in dataloader:
|
||||
seen.extend(batch["a"].tolist())
|
||||
assert all(uri == expected_uri for uri in batch["db_uri"])
|
||||
assert sorted(seen) == list(range(20))
|
||||
|
||||
|
||||
def test_permutation_dataloader_multiprocessing(tmp_db):
|
||||
"""Using a Permutation with a PyTorch DataLoader that has num_workers > 0
|
||||
must work end-to-end. Each worker process gets a pickled copy of the
|
||||
@@ -455,3 +535,504 @@ 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 _map_add_scaled(row):
|
||||
return {**row, "scaled": row["a"] * 2}
|
||||
|
||||
|
||||
def _map_add_total(batch):
|
||||
total = [a + scaled for a, scaled in zip(batch["a"], batch["scaled"])]
|
||||
return {**batch, "total": total}
|
||||
|
||||
|
||||
def test_permutation_map_dataloader_spawn(tmp_db):
|
||||
"""A map chain must be picklable so spawned DataLoader workers can run it."""
|
||||
table = tmp_db.create_table("test_table", pa.table({"a": range(100)}))
|
||||
permutation = (
|
||||
Permutation.identity(table)
|
||||
.map(_map_add_scaled)
|
||||
.map(_map_add_total, batched=True)
|
||||
)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation,
|
||||
batch_size=10,
|
||||
num_workers=1,
|
||||
multiprocessing_context="spawn",
|
||||
)
|
||||
seen = []
|
||||
for batch in dataloader:
|
||||
assert set(batch) == {"a", "scaled", "total"}
|
||||
assert torch.equal(batch["total"], batch["a"] * 3)
|
||||
seen.extend(batch["a"].tolist())
|
||||
assert seen == list(range(100))
|
||||
|
||||
|
||||
def test_batch_to_tensor_columns_zero_copy_and_slice_offsets():
|
||||
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
|
||||
nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2)
|
||||
batch = pa.record_batch(
|
||||
[
|
||||
pa.array(range(5), type=pa.int64()),
|
||||
pa.array(vectors, type=pa.list_(pa.float32(), 3)),
|
||||
pa.array(
|
||||
nested_values.tolist(),
|
||||
type=pa.list_(pa.list_(pa.float32(), 2), 3),
|
||||
),
|
||||
pa.array([True, False, True, False, True]),
|
||||
],
|
||||
names=["id", "vector", "nested", "active"],
|
||||
).slice(2, 2)
|
||||
|
||||
tensors = batch_to_tensor_columns(batch)
|
||||
assert tensors["id"].tolist() == [2, 3]
|
||||
assert torch.equal(tensors["vector"], torch.tensor(vectors[2:4]))
|
||||
assert torch.equal(tensors["nested"], torch.from_numpy(nested_values[2:4].copy()))
|
||||
assert tensors["active"].dtype == torch.bool
|
||||
assert tensors["active"].tolist() == [True, False]
|
||||
|
||||
id_array = batch.column("id")
|
||||
assert tensors["id"].data_ptr() == (
|
||||
id_array.buffers()[1].address + id_array.offset * 8
|
||||
)
|
||||
vector_array = batch.column("vector")
|
||||
vector_values = vector_array.values
|
||||
expected_vector_offset = (vector_array.offset * 3 + vector_values.offset) * 4
|
||||
assert tensors["vector"].data_ptr() == (
|
||||
vector_values.buffers()[1].address + expected_vector_offset
|
||||
)
|
||||
|
||||
single_column = pa.record_batch([batch.column("vector")], names=["vector"])
|
||||
column_tensor = batch_to_tensor(single_column)
|
||||
assert column_tensor.shape == (1, 2, 3)
|
||||
assert column_tensor.data_ptr() == tensors["vector"].data_ptr()
|
||||
|
||||
|
||||
def test_permutation_torch_col_and_row_vector_layouts(mem_db):
|
||||
left = [[float(i), float(i) + 0.5] for i in range(4)]
|
||||
right = [[float(i) + 1.0, float(i) + 1.5] for i in range(4)]
|
||||
table = mem_db.create_table(
|
||||
"uniform",
|
||||
pa.table(
|
||||
{
|
||||
"left": pa.array(left, type=pa.list_(pa.float32(), 2)),
|
||||
"right": pa.array(right, type=pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
|
||||
column_batch = next(
|
||||
permutation.with_format("torch_col").iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert column_batch.shape == (2, 4, 2)
|
||||
assert column_batch.dtype == torch.float32
|
||||
assert torch.equal(column_batch[0], torch.tensor(left))
|
||||
|
||||
row_batch = next(
|
||||
permutation.with_format("torch_row").iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert len(row_batch) == 4
|
||||
assert row_batch[0].shape == (2, 2)
|
||||
assert torch.equal(
|
||||
row_batch[0], torch.stack([torch.tensor(left[0]), torch.tensor(right[0])])
|
||||
)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation.with_format("torch_row"), batch_size=4, shuffle=False
|
||||
)
|
||||
stacked = next(iter(dataloader))
|
||||
assert stacked.shape == (4, 2, 2)
|
||||
|
||||
scalar_table = mem_db.create_table(
|
||||
"single_scalar", pa.table({"x": pa.array(range(4), type=pa.int64())})
|
||||
)
|
||||
scalar_rows = next(
|
||||
Permutation.identity(scalar_table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert scalar_rows[0].shape == (1,)
|
||||
assert scalar_rows[0].dtype == torch.int64
|
||||
|
||||
vector_table = mem_db.create_table(
|
||||
"single_vector",
|
||||
pa.table({"v": pa.array(left, type=pa.list_(pa.float32(), 2))}),
|
||||
)
|
||||
vector_rows = next(
|
||||
Permutation.identity(vector_table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert vector_rows[0].shape == (1, 2)
|
||||
vector_column = next(
|
||||
Permutation.identity(vector_table)
|
||||
.with_format("torch_col")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert vector_column.shape == (1, 4, 2)
|
||||
|
||||
|
||||
def test_torch_col_and_row_reject_heterogeneous_shapes(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"heterogeneous",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(4), type=pa.int64()),
|
||||
"vector": pa.array(
|
||||
[[float(i), float(i) + 1.0, float(i) + 2.0] for i in range(4)],
|
||||
type=pa.list_(pa.float32(), 3),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
for format_name in ("torch_col", "torch_row"):
|
||||
with pytest.raises(ValueError, match="torch_dict") as exc_info:
|
||||
next(permutation.with_format(format_name).iter(2, skip_last_batch=False))
|
||||
message = str(exc_info.value)
|
||||
assert "`vector`" in message
|
||||
assert "(3,)" in message
|
||||
assert "`id`" in message
|
||||
assert "()" in message
|
||||
|
||||
different_dims = mem_db.create_table(
|
||||
"different_dims",
|
||||
pa.table(
|
||||
{
|
||||
"left": pa.array(
|
||||
[[1.0, 2.0] for _ in range(4)],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
"right": pa.array(
|
||||
[[1.0, 2.0, 3.0] for _ in range(4)],
|
||||
type=pa.list_(pa.float32(), 3),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="torch_dict") as exc_info:
|
||||
next(
|
||||
Permutation.identity(different_dims)
|
||||
.with_format("torch_row")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
message = str(exc_info.value)
|
||||
assert "`right`" in message and "(3,)" in message
|
||||
assert "`left`" in message and "(2,)" in message
|
||||
|
||||
|
||||
def test_torch_row_uses_pytorch_numeric_promotion(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"promotion",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(4), type=pa.int64()),
|
||||
"score": pa.array([i / 2 for i in range(4)], type=pa.float32()),
|
||||
"count": pa.array(range(4), type=pa.int32()),
|
||||
}
|
||||
),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].shape == (3,)
|
||||
assert rows[0].dtype == torch.float32
|
||||
assert rows[0].tolist() == [0.0, 0.0, 0.0]
|
||||
assert rows[2].tolist() == [2.0, 1.0, 2.0]
|
||||
|
||||
|
||||
def test_torch_row_preserves_nullable_numeric_scalar_nan(mem_db):
|
||||
nullable_int = mem_db.create_table(
|
||||
"nullable_int",
|
||||
pa.table({"value": pa.array([1, None, 3], type=pa.int64())}),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_int)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].shape == (1,)
|
||||
assert rows[0].dtype == torch.float64
|
||||
assert rows[0].tolist() == [1.0]
|
||||
assert torch.isnan(rows[1]).all()
|
||||
assert rows[2].tolist() == [3.0]
|
||||
|
||||
nullable_float = mem_db.create_table(
|
||||
"nullable_float",
|
||||
pa.table({"value": pa.array([0.5, None, 2.5], type=pa.float32())}),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_float)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].dtype == torch.float32
|
||||
assert rows[0].tolist() == [0.5]
|
||||
assert torch.isnan(rows[1]).all()
|
||||
assert rows[2].tolist() == [2.5]
|
||||
|
||||
nullable_mixed = mem_db.create_table(
|
||||
"nullable_mixed",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array([1, None, 3], type=pa.int64()),
|
||||
"score": pa.array([0.5, 1.5, 2.5], type=pa.float32()),
|
||||
}
|
||||
),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_mixed)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].dtype == torch.float64
|
||||
assert rows[0].tolist() == [1.0, 0.5]
|
||||
assert torch.isnan(rows[1][0])
|
||||
assert rows[1][1].item() == 1.5
|
||||
assert rows[2].tolist() == [3.0, 2.5]
|
||||
|
||||
|
||||
def test_permutation_torch_formats_fixed_shape_tensor_permutation(mem_db):
|
||||
physical_values = np.arange(2 * 2 * 3 * 4, dtype=np.float32).reshape(2, 2, 3, 4)
|
||||
tensor_array = _fixed_shape_tensor_array(
|
||||
physical_values, shape=(2, 3, 4), permutation=[0, 2, 1]
|
||||
)
|
||||
table = mem_db.create_table(
|
||||
"tensor_permutation",
|
||||
pa.table({"id": range(2), "tensor": tensor_array}),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
expected = np.transpose(physical_values, (0, 1, 3, 2))
|
||||
|
||||
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
|
||||
assert batch["tensor"].shape == (2, 2, 4, 3)
|
||||
assert torch.equal(batch["tensor"], torch.from_numpy(expected.copy()))
|
||||
|
||||
tensor_only = permutation.select_columns(["tensor"])
|
||||
rows = next(tensor_only.with_format("torch_row").iter(2, skip_last_batch=False))
|
||||
assert rows[0].shape == (1, 2, 4, 3)
|
||||
assert torch.equal(rows[0][0], torch.from_numpy(expected[0].copy()))
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
tensor_only.with_format("torch"), batch_size=2, shuffle=False
|
||||
)
|
||||
default_collated = next(iter(dataloader))
|
||||
assert default_collated["tensor"].shape == (2, 2, 4, 3)
|
||||
|
||||
|
||||
def test_permutation_torch_formats_bfloat16(mem_db):
|
||||
values = [1.0, -1.5, 2.5, 0.0]
|
||||
scalar_values = _bf16_array(values)
|
||||
vector_values = pa.FixedSizeListArray.from_arrays(
|
||||
_bf16_array([value for value in values for _ in range(2)]), 2
|
||||
)
|
||||
table = mem_db.create_table(
|
||||
"bfloat16",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(4),
|
||||
"scalar": scalar_values,
|
||||
"vector": vector_values,
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
|
||||
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
|
||||
assert batch["scalar"].dtype == torch.bfloat16
|
||||
assert batch["vector"].dtype == torch.bfloat16
|
||||
assert torch.equal(batch["scalar"], torch.tensor(values[:2], dtype=torch.bfloat16))
|
||||
assert torch.equal(
|
||||
batch["vector"],
|
||||
torch.tensor([[value, value] for value in values[:2]], dtype=torch.bfloat16),
|
||||
)
|
||||
|
||||
arrow_batch = next(permutation.with_format("arrow").iter(2, skip_last_batch=False))
|
||||
arrow_tensors = batch_to_tensor_columns(arrow_batch)
|
||||
scalar_array = arrow_batch.column("scalar")
|
||||
assert arrow_tensors["scalar"].data_ptr() == (
|
||||
scalar_array.buffers()[1].address + scalar_array.offset * 2
|
||||
)
|
||||
|
||||
sliced = arrow_batch.slice(1, 1)
|
||||
sliced_tensors = batch_to_tensor_columns(sliced)
|
||||
assert torch.equal(
|
||||
sliced_tensors["scalar"],
|
||||
torch.tensor([values[1]], dtype=torch.bfloat16),
|
||||
)
|
||||
assert torch.equal(
|
||||
sliced_tensors["vector"],
|
||||
torch.tensor([[values[1], values[1]]], dtype=torch.bfloat16),
|
||||
)
|
||||
|
||||
skipped = next(
|
||||
permutation.with_skip(1)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
assert torch.equal(
|
||||
skipped["scalar"], torch.tensor(values[1:3], dtype=torch.bfloat16)
|
||||
)
|
||||
|
||||
empty = permutation.with_format("torch_dict").take_offsets([])
|
||||
assert empty["scalar"].shape == (0,)
|
||||
assert empty["scalar"].dtype == torch.bfloat16
|
||||
assert empty["vector"].shape == (0, 2)
|
||||
assert empty["vector"].dtype == torch.bfloat16
|
||||
|
||||
unmarked = mem_db.create_table(
|
||||
"unmarked_bfloat16",
|
||||
pa.table(
|
||||
{
|
||||
"vector": pa.FixedSizeListArray.from_arrays(
|
||||
pa.array(_bf16_storage(values), type=pa.binary(2)), 2
|
||||
)
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="not marked.*lance.bfloat16"):
|
||||
next(
|
||||
Permutation.identity(unmarked)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
|
||||
|
||||
def test_torch_formats_reject_nulls(mem_db):
|
||||
parent_nulls = mem_db.create_table(
|
||||
"parent_nulls",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(3),
|
||||
"values": pa.array(
|
||||
[[1.0, 2.0], None, [5.0, 6.0]],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(
|
||||
Permutation.identity(parent_nulls)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
|
||||
leaf_nulls = mem_db.create_table(
|
||||
"leaf_nulls",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(2),
|
||||
"values": pa.FixedSizeListArray.from_arrays(
|
||||
pa.array([1.0, None, 5.0, 6.0], type=pa.float32()), 2
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(
|
||||
Permutation.identity(leaf_nulls)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
leaf_only = Permutation.identity(leaf_nulls).select_columns(["values"])
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(leaf_only.with_format("torch_row").iter(2, skip_last_batch=False))
|
||||
|
||||
@@ -407,6 +407,33 @@ def test_value_to_sql_nan_and_infinity(tmp_path):
|
||||
assert rows[4]["f64"] == 4.0 and rows[4]["f32"] == 4.0
|
||||
|
||||
|
||||
def test_value_to_sql_enum_members(tmp_path):
|
||||
# str() of an int- or float-valued Enum member is its name, which SQL reads
|
||||
# as a field access, and a plain Enum member raised NotImplementedError.
|
||||
import enum
|
||||
|
||||
class Priority(int, enum.Enum):
|
||||
LOW = 1
|
||||
HIGH = 2
|
||||
|
||||
class Weight(float, enum.Enum):
|
||||
HALF = 0.5
|
||||
|
||||
class Color(enum.Enum):
|
||||
RED = "red"
|
||||
|
||||
assert value_to_sql(Priority.HIGH) == "2"
|
||||
assert value_to_sql(Weight.HALF) == "0.5"
|
||||
assert value_to_sql(Color.RED) == "'red'"
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"test", pa.table({"id": [1], "p": [1], "w": [1.0], "c": ["blue"]})
|
||||
)
|
||||
table.update(values={"p": Priority.HIGH, "w": Weight.HALF, "c": Color.RED})
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1, "p": 2, "w": 0.5, "c": "red"}]
|
||||
|
||||
|
||||
def test_append_vector_columns():
|
||||
registry = EmbeddingFunctionRegistry.get_instance()
|
||||
registry.register("test")(MockTextEmbeddingFunction)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("exist_ok", "existing"),
|
||||
[(None, False), (False, False), (True, False), (True, True)],
|
||||
)
|
||||
async def test_create_view_exist_ok_preserves_server_metadata(
|
||||
asynchronous, exist_ok, existing
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
original_query = "SELECT 'original' AS original"
|
||||
submitted_query = (
|
||||
"SELECT 'replacement' AS replacement" if existing else original_query
|
||||
)
|
||||
schema = {
|
||||
"fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}],
|
||||
"metadata": {
|
||||
"lancedb::view::default_db": "analytics",
|
||||
"lancedb::view::default_namespace": "team",
|
||||
},
|
||||
}
|
||||
result = pa.table(
|
||||
{"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]}
|
||||
)
|
||||
|
||||
class ViewServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
self.requests = []
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
self.requests.append(ticket.ticket)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with ViewServer() as server:
|
||||
connection_options = {
|
||||
"api_key": "test-key",
|
||||
"host_override": "http://localhost:10024",
|
||||
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
|
||||
}
|
||||
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async("db://analytics", **connection_options)
|
||||
view = await db.create_view(
|
||||
"saved", submitted_query, namespace_path=["team"], **kwargs
|
||||
)
|
||||
else:
|
||||
db = lancedb.connect("db://analytics", **connection_options)
|
||||
view = db.create_view(
|
||||
"saved", submitted_query, namespace_path=["team"], **kwargs
|
||||
)
|
||||
(request,) = server.requests
|
||||
|
||||
prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW"
|
||||
assert f'{prefix} "saved" AS {submitted_query}'.encode() in request
|
||||
assert view.name == "saved"
|
||||
assert view.namespace_path == ["team"]
|
||||
assert view.default_namespace_path == ["team"]
|
||||
assert view.query == original_query
|
||||
assert view.schema.names == ["original"]
|
||||
@@ -120,7 +120,7 @@ def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
|
||||
with_row_ids=True,
|
||||
)
|
||||
results = builder._finish_hybrid_results(
|
||||
combined, blob_mode="lazy", blob_sources={}
|
||||
combined, blob_mode="lazy", blob_sources={}, schema=None
|
||||
)
|
||||
|
||||
assert "_rowid" not in results.column_names, "the surrogate is internal"
|
||||
|
||||
@@ -36,6 +36,15 @@ def is_row_id_take(body) -> bool:
|
||||
return "_rowid" in (body.get("filter") or "")
|
||||
|
||||
|
||||
def is_row_offset_take(body) -> bool:
|
||||
"""True when a query body fetches specific rows by ``_rowoffset``.
|
||||
|
||||
This is the request shape ``Table.take_offsets`` sends on the remote
|
||||
backend, distinct from ``is_row_id_take``'s ``_rowid IN (...)``.
|
||||
"""
|
||||
return "_rowoffset" in (body.get("filter") or "")
|
||||
|
||||
|
||||
def arrow_file_bytes(table: pa.Table) -> bytes:
|
||||
"""Serialize to the Arrow IPC *file* framing the /query/ route answers with."""
|
||||
sink = pa.BufferOutputStream()
|
||||
@@ -51,21 +60,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 +108,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 +154,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 +175,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
|
||||
@@ -149,6 +184,37 @@ class MockPermutationServer:
|
||||
pa.table({"_rowid": pa.array(row_ids, pa.uint64())}),
|
||||
)
|
||||
|
||||
if is_row_offset_take(body):
|
||||
# A _rowoffset take (2-phase's filtered block reads): this
|
||||
# table's rows are never deleted/reordered, so id == _rowoffset
|
||||
# for every row, same invariant as id == _rowid above.
|
||||
row_offsets = sorted(parse_in_list(body["filter"]))
|
||||
columns = body.get("columns") or ["id", "_rowoffset"]
|
||||
values = {"id": row_offsets, "_rowoffset": row_offsets}
|
||||
return self._arrow(
|
||||
request,
|
||||
pa.table(
|
||||
{
|
||||
col: pa.array(
|
||||
values[col],
|
||||
pa.uint64() if col == "_rowoffset" else pa.int64(),
|
||||
)
|
||||
for col in columns
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
if body.get("columns") == ["_rowoffset"] and "IN" in (body.get("filter") or ""):
|
||||
# 2-phase's live-offset precompute scan: a user filter over
|
||||
# "_rowoffset" alone. This mock only understands `<col> IN
|
||||
# (...)` filters (not arbitrary SQL), and since id == _rowoffset
|
||||
# for every row here, reuses parse_in_list regardless of which
|
||||
# column the filter actually names.
|
||||
row_offsets = sorted(parse_in_list(body["filter"]))
|
||||
return self._arrow(
|
||||
request, pa.table({"_rowoffset": pa.array(row_offsets, pa.uint64())})
|
||||
)
|
||||
|
||||
# The schema probe: filtered to nothing, so it carries schema and no rows.
|
||||
return self._arrow(request, pa.table({"id": pa.array([], pa.int64())}))
|
||||
|
||||
|
||||
@@ -4,12 +4,30 @@
|
||||
from typing import assert_type
|
||||
|
||||
import lancedb
|
||||
from lancedb import AsyncConnection, DBConnection
|
||||
from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection
|
||||
|
||||
|
||||
def check_connect_type() -> None:
|
||||
assert_type(lancedb.connect("memory://"), DBConnection)
|
||||
assert_type(
|
||||
lancedb.connect_catalog(
|
||||
uri="db://analytics",
|
||||
api_key="secret",
|
||||
region="us-west-2",
|
||||
host_override="https://my-server.example",
|
||||
),
|
||||
Catalog,
|
||||
)
|
||||
|
||||
|
||||
async def check_connect_async_type() -> None:
|
||||
assert_type(await lancedb.connect_async("memory://"), AsyncConnection)
|
||||
assert_type(
|
||||
await lancedb.connect_catalog_async(
|
||||
uri="db://analytics",
|
||||
api_key="secret",
|
||||
region="us-west-2",
|
||||
host_override="https://my-server.example",
|
||||
),
|
||||
AsyncCatalog,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user