mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings
# Conflicts: # python/python/tests/test_table.py
This commit is contained in:
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.41.0-beta.17"
|
||||
version = "0.42.0-beta.9"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
@@ -36,6 +36,7 @@ pyo3-async-runtimes = { version = "0.29", features = [
|
||||
"attributes",
|
||||
"tokio-runtime",
|
||||
] }
|
||||
reqwest.workspace = true
|
||||
pin-project.workspace = true
|
||||
futures.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
+5
-3
@@ -20,7 +20,7 @@ For those hosts, install the `lancedb-compat` package instead:
|
||||
pip install lancedb-compat
|
||||
```
|
||||
|
||||
Same Python API (`import lancedb` works as usual). The compat wheel is compiled at the `x86-64-v2` baseline (Nehalem-class) and uses runtime SIMD dispatch in the embedded lance crate to pick the right kernel tier (scalar / AVX / AVX+FMA / AVX2+FMA / AVX-512) at load time, so it still goes fast on modern hardware while running cleanly on the pre-Haswell silicon. Use `lance.simd_info()` from Python to verify which tier was selected.
|
||||
Same Python API (`import lancedb` works as usual). The compat wheel is compiled at the `x86-64-v2` baseline (Nehalem-class) and uses runtime SIMD dispatch in the embedded lance crate to pick the right kernel tier (scalar / AVX / AVX+FMA / AVX2+FMA / AVX-512) at load time, so it still goes fast on modern hardware while running cleanly on the pre-Haswell silicon (if `pylance` is installed, `lance.simd_info()` reports which tier was selected).
|
||||
|
||||
`lancedb` and `lancedb-compat` install to the same `lancedb/` namespace and conflict at install time. Pick one. To switch, `pip uninstall lancedb` first, then `pip install lancedb-compat` (or vice-versa).
|
||||
|
||||
@@ -40,8 +40,10 @@ Stable releases are created about every 2 weeks. For the latest features and bug
|
||||
pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb
|
||||
```
|
||||
|
||||
If you also need the optional `lance` Python API, install the `pylance` extra
|
||||
and include the Lance preview index:
|
||||
Most applications only need `lancedb`. Install the optional `pylance` extra and
|
||||
include the Lance preview index only when building query engines or connectors,
|
||||
calling format-level `lance` APIs directly, or converting plain-scan lazy or
|
||||
legacy blob columns with `to_pandas()`:
|
||||
|
||||
```bash
|
||||
pip install --pre \
|
||||
|
||||
@@ -62,9 +62,9 @@ tests = [
|
||||
"duckdb>=0.9.0",
|
||||
"pytz>=2023.3",
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow<25",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b6",
|
||||
"pylance==15.0.0b15",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
@@ -95,6 +95,7 @@ embeddings = [
|
||||
"awscli>=1.44.38",
|
||||
"botocore>=1.31.57",
|
||||
'ibm-watsonx-ai>=1.1.2; python_version >= "3.10"',
|
||||
"oci>=2.165.1",
|
||||
"ollama>=0.3.0",
|
||||
"sentencepiece>=0.1.99"
|
||||
]
|
||||
|
||||
@@ -3,16 +3,24 @@
|
||||
|
||||
|
||||
import os
|
||||
import warnings
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
from typing import Dict, Optional, Union, Any, List, Iterable, TYPE_CHECKING
|
||||
from typing import Dict, Optional, Union, Any, List, Iterable, Literal, TYPE_CHECKING
|
||||
|
||||
from packaging.version import Version as _Version
|
||||
|
||||
from ._lancedb import __version__ as _native_version
|
||||
|
||||
# Match Python package metadata without requiring the lancedb distribution.
|
||||
__version__ = str(_Version(_native_version))
|
||||
|
||||
from ._lancedb import __version__ as __version__
|
||||
from ._lancedb import connect as lancedb_connect
|
||||
from ._lancedb import FtsToken
|
||||
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
|
||||
from .common import URI, sanitize_uri
|
||||
@@ -32,21 +40,26 @@ from .functions import (
|
||||
FunctionArtifactRequest as FunctionArtifactRequest,
|
||||
FunctionApplication as FunctionApplication,
|
||||
FunctionBinding as FunctionBinding,
|
||||
FunctionDefinition as FunctionDefinition,
|
||||
FunctionRegistrationRequest as FunctionRegistrationRequest,
|
||||
FunctionRetryPolicy as FunctionRetryPolicy,
|
||||
FunctionVersion as FunctionVersion,
|
||||
HuggingFaceModel as HuggingFaceModel,
|
||||
PythonRuntimeSpec as PythonRuntimeSpec,
|
||||
RefreshColumnResult as RefreshColumnResult,
|
||||
UdfDefinition as UdfDefinition,
|
||||
function as function,
|
||||
udf as udf,
|
||||
)
|
||||
from .secrets import EnvVarSecret as EnvVarSecret
|
||||
from .secrets import SecretInfo as SecretInfo
|
||||
from .storage_integration import StorageIntegrationInfo as StorageIntegrationInfo
|
||||
from .materialized_view import (
|
||||
AsyncMaterializedView,
|
||||
MaterializedView,
|
||||
MaterializedViewDefinition,
|
||||
)
|
||||
from .view import ViewDescription as ViewDescription
|
||||
from .graph import PropertyGraph, PropertyGraphDescription
|
||||
from .table import AsyncTable, CompactionOptions, Table
|
||||
from .types import BaseTokenizerType
|
||||
from ._lancedb import Session
|
||||
@@ -67,6 +80,7 @@ from .catalog import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from lance.blob import BlobType as BlobType
|
||||
from .functions import UdfDefinition as UdfDefinition
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
@@ -75,6 +89,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}")
|
||||
|
||||
|
||||
@@ -297,11 +318,11 @@ def connect(
|
||||
raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}")
|
||||
if session is not None:
|
||||
raise NotImplementedError(
|
||||
"session is not supported for LanceDB Distributed connections"
|
||||
"session is not supported for LanceDB Enterprise connections"
|
||||
)
|
||||
if manifest_enabled:
|
||||
raise NotImplementedError(
|
||||
"manifest_enabled is not supported for LanceDB Distributed connections"
|
||||
"manifest_enabled is not supported for LanceDB Enterprise connections"
|
||||
)
|
||||
if api_key is None:
|
||||
api_key = os.environ.get("LANCEDB_API_KEY")
|
||||
@@ -354,13 +375,31 @@ def tokenize(
|
||||
ngram_min_length: int = 3,
|
||||
ngram_max_length: int = 3,
|
||||
prefix_only: bool = False,
|
||||
analyzer: Optional[Literal["text", "code"]] = None,
|
||||
split_identifiers: Optional[bool] = None,
|
||||
split_on_numerics: Optional[bool] = None,
|
||||
preserve_original: Optional[bool] = None,
|
||||
index_operators: Optional[bool] = None,
|
||||
) -> Iterable[FtsToken]:
|
||||
"""Tokenize a full-text search query using an explicit tokenizer.
|
||||
|
||||
This does not require an FTS index. The tokenizer options match
|
||||
:class:`lancedb.index.FTS`. ``custom_stop_words`` accepts a list of strings.
|
||||
When ``stem`` or ``remove_stop_words`` is None, the base tokenizer's default
|
||||
applies: False for ``code`` and ``ngram``, True otherwise.
|
||||
applies: False for ``code`` and ``ngram``, True otherwise. ``analyzer`` and the
|
||||
code flags (``split_identifiers``, ``split_on_numerics``, ``preserve_original``
|
||||
and ``index_operators``) behave as they do on :class:`lancedb.index.FTS`.
|
||||
|
||||
Examples
|
||||
--------
|
||||
Inspect the identifier and subwords produced by the code analyzer:
|
||||
|
||||
>>> import lancedb
|
||||
>>> tokens = lancedb.tokenize(
|
||||
... "parseHTTPRequest", analyzer="code", split_identifiers=True
|
||||
... )
|
||||
>>> [token.text for token in tokens]
|
||||
['parsehttprequest', 'parse', 'http', 'request']
|
||||
"""
|
||||
|
||||
return _tokenize(
|
||||
@@ -376,6 +415,11 @@ def tokenize(
|
||||
ngram_min_length=ngram_min_length,
|
||||
ngram_max_length=ngram_max_length,
|
||||
prefix_only=prefix_only,
|
||||
analyzer=analyzer,
|
||||
split_identifiers=split_identifiers,
|
||||
split_on_numerics=split_on_numerics,
|
||||
preserve_original=preserve_original,
|
||||
index_operators=index_operators,
|
||||
)
|
||||
|
||||
|
||||
@@ -621,6 +665,8 @@ __all__ = [
|
||||
"MaterializedView",
|
||||
"MaterializedViewDefinition",
|
||||
"ViewDescription",
|
||||
"PropertyGraph",
|
||||
"PropertyGraphDescription",
|
||||
"connect",
|
||||
"connect_async",
|
||||
"tokenize",
|
||||
|
||||
@@ -26,6 +26,26 @@ class BlobReader(io.RawIOBase):
|
||||
|
||||
For local calls, construct a reader from a range-reading callable and the
|
||||
blob's size. The callable accepts an offset and length and returns bytes.
|
||||
This is also the interface for a reader backed by another engine.
|
||||
|
||||
Examples
|
||||
--------
|
||||
```python
|
||||
payload = b"hello world"
|
||||
|
||||
def read_range(offset, length):
|
||||
return payload[offset : offset + length]
|
||||
|
||||
with BlobReader(read_range, len(payload)) as reader:
|
||||
assert reader.read_range(6, 5) == b"world"
|
||||
assert reader.tell() == 0
|
||||
assert reader.read(5) == b"hello"
|
||||
assert reader.tell() == 5
|
||||
```
|
||||
|
||||
``read_range`` does not change the sequential cursor. Use ``size()`` for
|
||||
the declared payload size and close the reader when done; a local reader
|
||||
owns no server state.
|
||||
"""
|
||||
|
||||
def __init__(self, read_range: Callable[[int, int], bytes], size: int):
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Dict, List, Optional, Sequence, Tuple, Any, TypedDict, Union, Literal
|
||||
from typing import (
|
||||
Callable,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Any,
|
||||
TypedDict,
|
||||
Union,
|
||||
Literal,
|
||||
)
|
||||
from uuid import UUID
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -13,6 +24,7 @@ from .index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -26,8 +38,13 @@ from lance_namespace import (
|
||||
from .remote import ClientConfig
|
||||
from .types import BaseTokenizerType
|
||||
|
||||
__version__: str
|
||||
_experimental_functions_enabled: bool
|
||||
|
||||
def _doc_url(campaign: str) -> str: ...
|
||||
def _append_doc_url(message: str, campaign: str) -> str: ...
|
||||
def _parse_field_path(path: str) -> List[str]: ...
|
||||
|
||||
IvfHnswPq: type[HnswPq] = HnswPq
|
||||
IvfHnswSq: type[HnswSq] = HnswSq
|
||||
IvfHnswFlat: type[HnswFlat] = HnswFlat
|
||||
@@ -66,6 +83,11 @@ def tokenize(
|
||||
ngram_min_length: int = 3,
|
||||
ngram_max_length: int = 3,
|
||||
prefix_only: bool = False,
|
||||
analyzer: Optional[Literal["text", "code"]] = None,
|
||||
split_identifiers: Optional[bool] = None,
|
||||
split_on_numerics: Optional[bool] = None,
|
||||
preserve_original: Optional[bool] = None,
|
||||
index_operators: Optional[bool] = None,
|
||||
) -> List["FtsToken"]: ...
|
||||
|
||||
class PyExpr:
|
||||
@@ -111,6 +133,16 @@ class Session:
|
||||
@property
|
||||
def approx_num_items(self) -> int: ...
|
||||
|
||||
class GpuClass:
|
||||
name: str
|
||||
resource_name: str
|
||||
gpu_model: Optional[str]
|
||||
gpu_memory_bytes: Optional[int]
|
||||
max_gpu_count_per_worker: Optional[int]
|
||||
cpu_millis: Optional[int]
|
||||
memory_bytes: Optional[int]
|
||||
ephemeral_storage_bytes: Optional[int]
|
||||
|
||||
class Connection(object):
|
||||
uri: str
|
||||
async def is_open(self): ...
|
||||
@@ -152,6 +184,7 @@ class Connection(object):
|
||||
limit: Optional[int],
|
||||
) -> list[str]: ... # Deprecated: Use list_tables instead
|
||||
async def open_job(self, job_id: str) -> Job: ...
|
||||
async def list_gpu_classes(self) -> list[GpuClass]: ...
|
||||
async def create_function_async(
|
||||
self, request_json: str, namespace_path: Optional[List[str]] = None
|
||||
) -> Job: ...
|
||||
@@ -168,9 +201,28 @@ 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]: ...
|
||||
async def create_storage_integration(
|
||||
self, name: str, request: str, namespace_path: Optional[List[str]] = None
|
||||
) -> str: ...
|
||||
async def describe_storage_integration(
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> str: ...
|
||||
def list_storage_integrations(
|
||||
self,
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
) -> NameListing: ...
|
||||
async def drop_storage_integration(
|
||||
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
|
||||
) -> None: ...
|
||||
@@ -209,6 +261,25 @@ class Connection(object):
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
) -> NameListing: ...
|
||||
async def create_property_graph(
|
||||
self,
|
||||
name: str,
|
||||
definition_json: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> str: ...
|
||||
async def describe_property_graph(
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> str: ...
|
||||
async def drop_property_graph(
|
||||
self, name: str, namespace_path: Optional[List[str]] = None
|
||||
) -> None: ...
|
||||
def list_property_graphs(
|
||||
self,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
) -> NameListing: ...
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
) -> JobListing: ...
|
||||
@@ -331,7 +402,10 @@ class Job:
|
||||
@property
|
||||
def _description(self) -> Optional[JobDescription]: ...
|
||||
async def status(self) -> str: ...
|
||||
async def wait(self) -> Optional[str]: ...
|
||||
async def wait(
|
||||
self,
|
||||
progress: Optional[Callable[[dict[str, Any]], None]] = None,
|
||||
) -> Optional[str]: ...
|
||||
async def cancel(self) -> None: ...
|
||||
async def refresh(self) -> None: ...
|
||||
async def events(
|
||||
@@ -352,6 +426,10 @@ class JobInfo:
|
||||
def state(self) -> str: ...
|
||||
@property
|
||||
def created_at_millis(self) -> int: ...
|
||||
@property
|
||||
def progress(self) -> Optional[dict[str, Any]]: ...
|
||||
@property
|
||||
def paused(self) -> bool: ...
|
||||
|
||||
class SessionStatus:
|
||||
@property
|
||||
@@ -390,7 +468,13 @@ 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
|
||||
@@ -410,6 +494,8 @@ class JobDescription:
|
||||
@property
|
||||
def result(self) -> Optional[Any]: ...
|
||||
@property
|
||||
def progress(self) -> Optional[dict[str, Any]]: ...
|
||||
@property
|
||||
def failure(self) -> Optional[JobFailureInfo]: ...
|
||||
|
||||
class SqlQuery:
|
||||
@@ -462,6 +548,7 @@ class Table:
|
||||
Bitmap,
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -484,6 +571,7 @@ class Table:
|
||||
Bitmap,
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
FTS,
|
||||
],
|
||||
replace: Optional[bool],
|
||||
@@ -509,6 +597,9 @@ class Table:
|
||||
) -> list[FtsToken]: ...
|
||||
async def delete(self, filter: Union[str, PyExpr]) -> DeleteResult: ...
|
||||
async def add_columns(self, columns: list[tuple[str, str]]) -> AddColumnsResult: ...
|
||||
async def add_columns_from_reader(
|
||||
self, data: pa.RecordBatchReader
|
||||
) -> AddColumnsResult: ...
|
||||
async def add_computed_columns(
|
||||
self,
|
||||
columns: list[tuple[str, str]],
|
||||
@@ -522,8 +613,40 @@ class Table:
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[int] = None,
|
||||
) -> AddColumnsResult: ...
|
||||
async def refresh_column(self, column: str) -> RefreshColumnResult: ...
|
||||
async def refresh_column_async(self, column: str) -> Job: ...
|
||||
async def refresh_column(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[str] = None,
|
||||
error_policy: Optional[str] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
) -> RefreshColumnResult: ...
|
||||
async def refresh_column_async(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[str] = None,
|
||||
error_policy: Optional[str] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
) -> Job: ...
|
||||
async def function_errors(
|
||||
self,
|
||||
job_id: Optional[str] = None,
|
||||
@@ -531,10 +654,24 @@ class Table:
|
||||
limit: Optional[int] = None,
|
||||
) -> FunctionErrors: ...
|
||||
async def refresh_materialized_view(
|
||||
self, source_version: Optional[int] = None, *, full: bool = False
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> RefreshMaterializedViewResult: ...
|
||||
async def refresh_materialized_view_async(
|
||||
self, source_version: Optional[int] = None, *, full: bool = False
|
||||
self,
|
||||
source_version: Optional[int] = None,
|
||||
*,
|
||||
full: bool = False,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> Job: ...
|
||||
async def materialized_view_definition(self) -> str: ...
|
||||
async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ...
|
||||
@@ -558,6 +695,9 @@ class Table:
|
||||
async def enable_rte(self, spec: RTEWriteSpec) -> None: ...
|
||||
async def disable_rte(self) -> None: ...
|
||||
async def get_rte_spec(self) -> Optional[RTEWriteSpec]: ...
|
||||
async def get_table_overrides(self) -> str: ...
|
||||
async def update_table_overrides(self, overrides_json: str) -> str: ...
|
||||
async def reset_table_overrides(self) -> str: ...
|
||||
# WAL-PK-FUSION: delete both.
|
||||
def hybrid_pk_fusion_learned(self) -> bool: ...
|
||||
def note_hybrid_pk_fusion(self) -> None: ...
|
||||
@@ -750,6 +890,7 @@ class VectorQuery:
|
||||
def search_effort(self, search_effort: Optional[float]): ...
|
||||
def minimum_nprobes(self, minimum_nprobes: int): ...
|
||||
def maximum_nprobes(self, maximum_nprobes: int): ...
|
||||
def approx_mode(self, approx_mode: str): ...
|
||||
def bypass_vector_index(self): ...
|
||||
def nearest_to_text(self, query: dict) -> HybridQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
@@ -776,6 +917,7 @@ class HybridQuery:
|
||||
def search_effort(self, search_effort: Optional[float]): ...
|
||||
def minimum_nprobes(self, minimum_nprobes: int): ...
|
||||
def maximum_nprobes(self, maximum_nprobes: int): ...
|
||||
def approx_mode(self, approx_mode: str): ...
|
||||
def bypass_vector_index(self): ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
def to_vector_query(self) -> VectorQuery: ...
|
||||
@@ -791,6 +933,7 @@ class PyQueryRequest:
|
||||
limit: Optional[int]
|
||||
offset: Optional[int]
|
||||
take_offsets: Optional[List[int]]
|
||||
take_row_ids: Optional[List[int]]
|
||||
filter: Optional[Union[str, bytes]]
|
||||
full_text_search: Optional[FullTextQuery]
|
||||
select: Optional[Union[str, List[str]]]
|
||||
@@ -807,6 +950,7 @@ class PyQueryRequest:
|
||||
lower_bound: Optional[float]
|
||||
upper_bound: Optional[float]
|
||||
ef: Optional[int]
|
||||
approx_mode: Optional[str]
|
||||
refine_factor: Optional[int]
|
||||
distance_type: Optional[str]
|
||||
bypass_vector_index: Optional[bool]
|
||||
@@ -900,15 +1044,20 @@ class RefreshColumnResult:
|
||||
version: int
|
||||
|
||||
class FunctionErrorRecord:
|
||||
attempts: Optional[int]
|
||||
job_id: str
|
||||
fragment_id: int
|
||||
row_offset: Optional[int]
|
||||
row_id: Optional[int]
|
||||
row_address: Optional[int]
|
||||
column: str
|
||||
function: str
|
||||
function_version: str
|
||||
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:
|
||||
@@ -1081,6 +1230,10 @@ class AuthzObject:
|
||||
database: str, namespace_path: Sequence[str], name: str
|
||||
) -> AuthzObject: ...
|
||||
@staticmethod
|
||||
def storage_integration(
|
||||
database: str, namespace: Sequence[str], name: str
|
||||
) -> AuthzObject: ...
|
||||
@staticmethod
|
||||
def secret(
|
||||
database: str, namespace_path: Sequence[str], name: str
|
||||
) -> AuthzObject: ...
|
||||
@@ -1090,3 +1243,5 @@ class AuthzObject:
|
||||
) -> AuthzObject: ...
|
||||
def __str__(self) -> str: ...
|
||||
def __repr__(self) -> str: ...
|
||||
|
||||
def validate_function_retry_policy(json: str) -> None: ...
|
||||
|
||||
@@ -172,6 +172,17 @@ class Object:
|
||||
"""A secret, defaulting to the database's public namespace."""
|
||||
return cls(str(_lancedb.AuthzObject.secret(database, namespace_path, name)))
|
||||
|
||||
@classmethod
|
||||
def storage_integration(
|
||||
cls, *, database: str, name: str, namespace_path: Sequence[str] = ("public",)
|
||||
) -> "Object":
|
||||
"""A database storage integration, defaulting to its public namespace."""
|
||||
return cls(
|
||||
str(
|
||||
_lancedb.AuthzObject.storage_integration(database, namespace_path, name)
|
||||
)
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def function(
|
||||
cls, *, database: str, name: str, namespace_path: Sequence[str] = ("public",)
|
||||
@@ -217,6 +228,7 @@ class Privilege(str, Enum):
|
||||
CREATE_SECRET = "CREATE_SECRET"
|
||||
CREATE_FUNCTION = "CREATE_FUNCTION"
|
||||
OPERATE = "OPERATE"
|
||||
CREATE_STORAGE_INTEGRATION = "CREATE_STORAGE_INTEGRATION"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Remote catalogs manage databases through a server's root namespace."""
|
||||
"""Remote catalogs manage databases."""
|
||||
|
||||
from functools import cached_property
|
||||
from datetime import timedelta
|
||||
|
||||
+767
-95
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@ from .bedrock import BedRockText
|
||||
from .cohere import CohereEmbeddingFunction
|
||||
from .gemini_text import GeminiText
|
||||
from .instructor import InstructorEmbeddingFunction
|
||||
from .oci_genai import OCIGenAIEmbeddings
|
||||
from .ollama import OllamaEmbeddings
|
||||
from .open_clip import OpenClipEmbeddings
|
||||
from .openai import OpenAIEmbeddings
|
||||
@@ -49,6 +50,7 @@ __all__ = [
|
||||
"GteEmbeddings",
|
||||
"InstructorEmbeddingFunction",
|
||||
"JinaEmbeddings",
|
||||
"OCIGenAIEmbeddings",
|
||||
"OllamaEmbeddings",
|
||||
"TransformersEmbeddingFunction",
|
||||
"ColbertEmbeddings",
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
|
||||
import os
|
||||
from functools import cached_property
|
||||
from typing import Any, List, Literal, Optional, Union
|
||||
|
||||
import numpy as np
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from ..util import attempt_import_or_raise
|
||||
from .base import TextEmbeddingFunction
|
||||
from .registry import register
|
||||
from .utils import TEXT
|
||||
|
||||
# The Generative AI embed-text API accepts at most 96 inputs per request:
|
||||
# https://docs.oracle.com/en-us/iaas/api/#/en/generative-ai-inference/latest/EmbedTextResult/EmbedText
|
||||
EMBEDDING_BATCH_SIZE = 96
|
||||
|
||||
# A ``name`` that is a dedicated AI cluster endpoint OCID is routed with
|
||||
# DedicatedServingMode instead of the on-demand model catalog.
|
||||
_DEDICATED_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint"
|
||||
_DEFAULT_REGION = "us-chicago-1"
|
||||
|
||||
_SERVICE_ERROR_HELP = """
|
||||
Common causes:
|
||||
- Expired session token (auth_type="SECURITY_TOKEN"): run
|
||||
`oci session authenticate --profile-name <profile>`.
|
||||
- Missing IAM policy: the caller needs
|
||||
`allow group <group> to use generative-ai-family in compartment <name>`.
|
||||
- Model not offered in the region behind `region` / `service_endpoint`, or
|
||||
a wrong `name` / `compartment_id`. List models with
|
||||
`oci generative-ai model-collection list-models --compartment-id <ocid>`.
|
||||
"""
|
||||
|
||||
|
||||
class OCIGenAIServiceError(ValueError):
|
||||
"""Raised when the Generative AI service rejects an ``embed_text`` request.
|
||||
|
||||
``status_code`` mirrors the HTTP status so LanceDB's retry helper treats
|
||||
401/403 responses as permanent instead of retrying them.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, status_code: Optional[int] = None):
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
@register("oci-genai")
|
||||
class OCIGenAIEmbeddings(TextEmbeddingFunction):
|
||||
"""
|
||||
An embedding function that uses the Oracle Cloud Infrastructure (OCI)
|
||||
Generative AI service.
|
||||
|
||||
https://docs.oracle.com/en-us/iaas/Content/generative-ai/embed-models.htm
|
||||
|
||||
Requires the OCI Python SDK (``pip install oci``). No credentials are stored
|
||||
on this object: requests are signed by the SDK using an API-key or
|
||||
session-token profile from the OCI config file, or the instance / resource
|
||||
principal of the host, so there are no sensitive keys to protect with
|
||||
``$var:``.
|
||||
|
||||
Cohere embedding models are asymmetric: the source column is embedded with
|
||||
``input_type="SEARCH_DOCUMENT"`` and queries with ``"SEARCH_QUERY"``.
|
||||
Inputs are sent in batches of at most 96 texts, the service limit.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str, default "cohere.embed-v4.0"
|
||||
Model ID of an on-demand embedding model: ``cohere.embed-v4.0``
|
||||
(1536 dims), ``cohere.embed-english-v3.0`` /
|
||||
``cohere.embed-multilingual-v3.0`` (1024 dims) or their ``-light-v3.0``
|
||||
variants (384 dims). A dedicated AI cluster endpoint OCID
|
||||
(``ocid1.generativeaiendpoint...``) is also accepted.
|
||||
compartment_id : str, optional
|
||||
OCID of the compartment the requests are authorized in and billed to.
|
||||
The service requires it; when not passed, the ``OCI_COMPARTMENT_ID``
|
||||
environment variable is used.
|
||||
region : str, default "us-chicago-1"
|
||||
OCI region used to derive the inference endpoint when
|
||||
``service_endpoint`` is not set.
|
||||
service_endpoint : str, optional
|
||||
Full inference endpoint, e.g.
|
||||
``https://inference.generativeai.us-chicago-1.oci.oraclecloud.com``.
|
||||
Takes precedence over ``region``; needed for realms with a different
|
||||
endpoint template.
|
||||
auth_type : str, default "API_KEY"
|
||||
One of ``"API_KEY"``, ``"SECURITY_TOKEN"``, ``"INSTANCE_PRINCIPAL"`` or
|
||||
``"RESOURCE_PRINCIPAL"``. The first two read profile ``auth_profile``
|
||||
from the OCI config file ``auth_file_location``; ``SECURITY_TOKEN``
|
||||
additionally uses the profile's ``security_token_file`` written by
|
||||
``oci session authenticate``. The principal types use the identity of
|
||||
the host (Compute instance, OKE workload, Functions, ...) and ignore
|
||||
the config file.
|
||||
auth_profile : str, default "DEFAULT"
|
||||
Profile name in the OCI config file.
|
||||
auth_file_location : str, default "~/.oci/config"
|
||||
Path of the OCI config file.
|
||||
truncate : str, default "END"
|
||||
How inputs longer than the model context are handled: ``"NONE"``
|
||||
(fail), ``"START"`` or ``"END"`` (drop tokens from that side).
|
||||
source_input_type : str, default "SEARCH_DOCUMENT"
|
||||
``input_type`` sent when embedding the source column.
|
||||
query_input_type : str, default "SEARCH_QUERY"
|
||||
``input_type`` sent when embedding queries.
|
||||
output_dimensions : int, optional
|
||||
Embedding size for models that support it (``cohere.embed-v4.0``:
|
||||
256, 512, 1024 or 1536). When set, ``ndims()`` returns it directly;
|
||||
otherwise the size is discovered with one probe request and cached.
|
||||
|
||||
Examples
|
||||
--------
|
||||
import lancedb
|
||||
from lancedb.embeddings import get_registry
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
|
||||
model = get_registry().get("oci-genai").create(
|
||||
name="cohere.embed-v4.0",
|
||||
compartment_id="ocid1.compartment.oc1..<your-compartment>",
|
||||
auth_profile="DEFAULT",
|
||||
)
|
||||
|
||||
class TextModel(LanceModel):
|
||||
text: str = model.SourceField()
|
||||
vector: Vector(model.ndims()) = model.VectorField()
|
||||
|
||||
db = lancedb.connect("~/.lancedb")
|
||||
tbl = db.create_table("docs", schema=TextModel, mode="overwrite")
|
||||
tbl.add([{"text": "hello world"}, {"text": "goodbye world"}])
|
||||
rs = tbl.search("hello").limit(1).to_pandas()
|
||||
|
||||
When restored from table metadata in a new process, an explicit
|
||||
``service_endpoint`` or non-default ``region`` must be approved with
|
||||
[allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint].
|
||||
The default region does not need approval.
|
||||
"""
|
||||
|
||||
name: str = "cohere.embed-v4.0"
|
||||
compartment_id: Optional[str] = None
|
||||
region: str = _DEFAULT_REGION
|
||||
service_endpoint: Optional[str] = None
|
||||
auth_type: Literal[
|
||||
"API_KEY", "SECURITY_TOKEN", "INSTANCE_PRINCIPAL", "RESOURCE_PRINCIPAL"
|
||||
] = "API_KEY"
|
||||
auth_profile: str = "DEFAULT"
|
||||
auth_file_location: str = "~/.oci/config"
|
||||
truncate: Literal["NONE", "START", "END"] = "END"
|
||||
source_input_type: str = "SEARCH_DOCUMENT"
|
||||
query_input_type: str = "SEARCH_QUERY"
|
||||
output_dimensions: Optional[int] = None
|
||||
|
||||
model_config = ConfigDict(ignored_types=(cached_property,))
|
||||
|
||||
@staticmethod
|
||||
def model_names() -> List[str]:
|
||||
"""On-demand text embedding models offered by the service."""
|
||||
return [
|
||||
"cohere.embed-v4.0",
|
||||
"cohere.embed-english-v3.0",
|
||||
"cohere.embed-multilingual-v3.0",
|
||||
"cohere.embed-english-light-v3.0",
|
||||
"cohere.embed-multilingual-light-v3.0",
|
||||
]
|
||||
|
||||
def endpoints(self) -> List[str]:
|
||||
# Metadata only selects the default endpoint by omitting both fields.
|
||||
if self.service_endpoint or self.region != _DEFAULT_REGION:
|
||||
return [self._resolve_service_endpoint()]
|
||||
return []
|
||||
|
||||
def ndims(self) -> int:
|
||||
return self._resolved_ndims
|
||||
|
||||
@cached_property
|
||||
def _resolved_ndims(self) -> int:
|
||||
if self.output_dimensions is not None:
|
||||
return self.output_dimensions
|
||||
# embed-v4.0 is variable-width and the catalog changes, so probe the
|
||||
# service once instead of hardcoding a model -> dimensions table.
|
||||
return len(self._embed_batch(["lancedb"], self.query_input_type)[0])
|
||||
|
||||
def compute_query_embeddings(
|
||||
self, query: str, *args, **kwargs
|
||||
) -> List[Union[List[float], None]]:
|
||||
return self.compute_source_embeddings(query, input_type=self.query_input_type)
|
||||
|
||||
def compute_source_embeddings(
|
||||
self, texts: TEXT, *args, **kwargs
|
||||
) -> List[Union[List[float], None]]:
|
||||
texts = self.sanitize_input(texts)
|
||||
# assume the source input type unless `compute_query_embeddings` set one
|
||||
kwargs["input_type"] = kwargs.get("input_type") or self.source_input_type
|
||||
return self.generate_embeddings(texts, **kwargs)
|
||||
|
||||
def generate_embeddings(
|
||||
self, texts: Union[List[str], np.ndarray], *args, **kwargs
|
||||
) -> List[Union[List[float], None]]:
|
||||
"""
|
||||
Get the embeddings for the given texts
|
||||
|
||||
Parameters
|
||||
----------
|
||||
texts: list[str] or np.ndarray (of str)
|
||||
The texts to embed
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[list[float] | None]
|
||||
One embedding per input, in order. Empty inputs are not sent to
|
||||
the service (it rejects them) and come back as ``None``.
|
||||
"""
|
||||
input_type = kwargs.get("input_type") or self.source_input_type
|
||||
texts = list(texts)
|
||||
valid = [(idx, text) for idx, text in enumerate(texts) if text]
|
||||
results: List[Union[List[float], None]] = [None] * len(texts)
|
||||
for start in range(0, len(valid), EMBEDDING_BATCH_SIZE):
|
||||
batch = valid[start : start + EMBEDDING_BATCH_SIZE]
|
||||
embeddings = self._embed_batch([text for _, text in batch], input_type)
|
||||
for (idx, _), embedding in zip(batch, embeddings):
|
||||
results[idx] = embedding
|
||||
return results
|
||||
|
||||
def _embed_batch(self, texts: List[str], input_type: str) -> List[List[float]]:
|
||||
"""Send one embed_text request (at most EMBEDDING_BATCH_SIZE inputs)."""
|
||||
oci = attempt_import_or_raise("oci")
|
||||
models = oci.generative_ai_inference.models
|
||||
if self.name.startswith(_DEDICATED_ENDPOINT_PREFIX):
|
||||
serving_mode = models.DedicatedServingMode(endpoint_id=self.name)
|
||||
else:
|
||||
serving_mode = models.OnDemandServingMode(model_id=self.name)
|
||||
details = {
|
||||
"inputs": texts,
|
||||
"serving_mode": serving_mode,
|
||||
"compartment_id": self._resolve_compartment_id(),
|
||||
"truncate": self.truncate,
|
||||
"input_type": input_type,
|
||||
}
|
||||
if self.output_dimensions is not None:
|
||||
details["output_dimensions"] = self.output_dimensions
|
||||
try:
|
||||
response = self._client.embed_text(models.EmbedTextDetails(**details))
|
||||
except oci.exceptions.ServiceError as e:
|
||||
raise OCIGenAIServiceError(
|
||||
f"OCI Generative AI embed_text failed with HTTP {e.status} "
|
||||
f"({e.code}): {e.message}\n{_SERVICE_ERROR_HELP}",
|
||||
status_code=e.status,
|
||||
) from e
|
||||
return response.data.embeddings
|
||||
|
||||
def _resolve_compartment_id(self) -> str:
|
||||
compartment_id = self.compartment_id or os.environ.get("OCI_COMPARTMENT_ID")
|
||||
if not compartment_id:
|
||||
raise ValueError(
|
||||
"compartment_id is required by the OCI Generative AI service. "
|
||||
"Pass `compartment_id=` to OCIGenAIEmbeddings or set the "
|
||||
"OCI_COMPARTMENT_ID environment variable."
|
||||
)
|
||||
return compartment_id
|
||||
|
||||
def _resolve_service_endpoint(self) -> str:
|
||||
if self.service_endpoint:
|
||||
return self.service_endpoint
|
||||
return f"https://inference.generativeai.{self.region}.oci.oraclecloud.com"
|
||||
|
||||
def _build_auth(self, oci) -> tuple[dict, Any]:
|
||||
"""Return the ``(config, signer)`` pair for the configured ``auth_type``."""
|
||||
if self.auth_type in ("API_KEY", "SECURITY_TOKEN"):
|
||||
config = oci.config.from_file(
|
||||
file_location=self.auth_file_location, profile_name=self.auth_profile
|
||||
)
|
||||
token_file = config.get("security_token_file")
|
||||
if self.auth_type == "API_KEY":
|
||||
if token_file:
|
||||
raise ValueError(
|
||||
f"Profile '{self.auth_profile}' in {self.auth_file_location} "
|
||||
"is a session-token profile; use auth_type='SECURITY_TOKEN'."
|
||||
)
|
||||
return config, None
|
||||
if not token_file:
|
||||
raise ValueError(
|
||||
f"Profile '{self.auth_profile}' in {self.auth_file_location} "
|
||||
"has no security_token_file; run `oci session authenticate` "
|
||||
"or use auth_type='API_KEY'."
|
||||
)
|
||||
with open(os.path.expanduser(token_file)) as f:
|
||||
token = f.read().strip()
|
||||
private_key = oci.signer.load_private_key_from_file(
|
||||
os.path.expanduser(config["key_file"]), config.get("pass_phrase")
|
||||
)
|
||||
return config, oci.auth.signers.SecurityTokenSigner(token, private_key)
|
||||
if self.auth_type == "INSTANCE_PRINCIPAL":
|
||||
return {}, oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
|
||||
if self.auth_type == "RESOURCE_PRINCIPAL":
|
||||
return {}, oci.auth.signers.get_resource_principals_signer()
|
||||
raise ValueError(f"Unsupported auth_type '{self.auth_type}'")
|
||||
|
||||
@cached_property
|
||||
def _client(self):
|
||||
oci = attempt_import_or_raise("oci")
|
||||
config, signer = self._build_auth(oci)
|
||||
kwargs = {
|
||||
"config": config,
|
||||
"service_endpoint": self._resolve_service_endpoint(),
|
||||
# LanceDB already retries with exponential backoff (`max_retries`),
|
||||
# so the SDK's own retry loop is disabled to avoid compounding it.
|
||||
"retry_strategy": oci.retry.NoneRetryStrategy(),
|
||||
"timeout": (10, 240),
|
||||
}
|
||||
if signer is not None:
|
||||
kwargs["signer"] = signer
|
||||
return oci.generative_ai_inference.GenerativeAiInferenceClient(**kwargs)
|
||||
|
||||
def __getstate__(self) -> dict[str, Any]:
|
||||
# The SDK client holds an HTTP session and cannot be pickled.
|
||||
state = super().__getstate__()
|
||||
state["__dict__"] = {
|
||||
k: v for k, v in state["__dict__"].items() if k != "_client"
|
||||
}
|
||||
return state
|
||||
@@ -36,6 +36,7 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
||||
embedding_function = openai.create(
|
||||
name="<ollama-embedding-model-name>",
|
||||
base_url="http://localhost:11434",
|
||||
dim=768, # the model's embedding dimension; required for unlisted names
|
||||
)
|
||||
```
|
||||
|
||||
@@ -77,8 +78,15 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
|
||||
return self.dim or 3072
|
||||
elif self.name == "text-embedding-3-small":
|
||||
return self.dim or 1536
|
||||
elif self.dim:
|
||||
# A name not listed above, e.g. a model served behind an
|
||||
# OpenAI-compatible `base_url`: `dim` is its embedding size
|
||||
return self.dim
|
||||
else:
|
||||
raise ValueError(f"Unknown model name {self.name}")
|
||||
raise ValueError(
|
||||
f"Unknown model name {self.name}: set `dim` to the model's "
|
||||
"embedding dimension"
|
||||
)
|
||||
|
||||
def generate_embeddings(
|
||||
self, texts: Union[List[str], "np.ndarray"]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from typing import Dict, Optional, Set, Tuple, Type
|
||||
from typing import Dict, Mapping, Optional, Set, Tuple, Type, Union
|
||||
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
@@ -13,6 +13,51 @@ from .base import (
|
||||
)
|
||||
|
||||
|
||||
def _embedding_column_pairs(
|
||||
metadata: Optional[Mapping[Union[bytes, str], Union[bytes, str]]],
|
||||
) -> list[Tuple[str, str]]:
|
||||
"""Return source/vector pairs without restoring embedding functions."""
|
||||
pairs = []
|
||||
seen = set()
|
||||
|
||||
def add_pair(source_column: str, vector_column: str) -> None:
|
||||
pair = (source_column, vector_column)
|
||||
if pair not in seen:
|
||||
seen.add(pair)
|
||||
pairs.append(pair)
|
||||
|
||||
if metadata is None:
|
||||
return pairs
|
||||
|
||||
serialized = metadata.get(
|
||||
b"embedding_functions", metadata.get("embedding_functions")
|
||||
)
|
||||
if serialized is not None:
|
||||
if isinstance(serialized, bytes):
|
||||
serialized = serialized.decode("utf-8")
|
||||
for config in json.loads(serialized):
|
||||
add_pair(config["source_column"], config["vector_column"])
|
||||
|
||||
serialized = metadata.get(
|
||||
b"lancedb::column_definitions", metadata.get("lancedb::column_definitions")
|
||||
)
|
||||
if serialized is not None:
|
||||
if isinstance(serialized, bytes):
|
||||
serialized = serialized.decode("utf-8")
|
||||
for column in json.loads(serialized):
|
||||
kind = column.get("kind")
|
||||
if not isinstance(kind, dict) or "Embedding" not in kind:
|
||||
continue
|
||||
embedding = kind["Embedding"]
|
||||
source_column = embedding["source_column"]
|
||||
vector_column = embedding.get("dest_column")
|
||||
if vector_column is None:
|
||||
vector_column = f"{source_column}_embedding"
|
||||
add_pair(source_column, vector_column)
|
||||
|
||||
return pairs
|
||||
|
||||
|
||||
class EmbeddingFunctionRegistry:
|
||||
"""
|
||||
This is a singleton class used to register embedding functions
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
"""Custom exception handling"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class MissingValueError(ValueError):
|
||||
"""Exception raised when a required value is missing."""
|
||||
@@ -25,10 +27,59 @@ class MissingColumnError(KeyError):
|
||||
)
|
||||
|
||||
|
||||
class JobFailedError(RuntimeError):
|
||||
"""Exception raised when an asynchronous job reaches the failed state."""
|
||||
class ColumnNotFoundError(ValueError):
|
||||
"""A requested table column does not exist.
|
||||
|
||||
pass
|
||||
Remote HTTP and SQL errors inherit this type and carry request metadata.
|
||||
Locally rejected queries have no request or job identifiers.
|
||||
"""
|
||||
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
self.request_id: Optional[str] = None
|
||||
self.job_id: Optional[str] = None
|
||||
self.job_request_id: Optional[str] = None
|
||||
|
||||
|
||||
class ReferenceNotFoundError(ValueError):
|
||||
"""A requested branch or table reference does not exist."""
|
||||
|
||||
request_id: Optional[str] = None
|
||||
job_id: Optional[str] = None
|
||||
job_request_id: Optional[str] = None
|
||||
|
||||
|
||||
class SchemaMismatchError(ValueError):
|
||||
"""Input data does not match the table's schema."""
|
||||
|
||||
request_id: Optional[str] = None
|
||||
job_id: Optional[str] = None
|
||||
job_request_id: Optional[str] = None
|
||||
|
||||
|
||||
class JobFailedError(RuntimeError):
|
||||
"""Exception raised when an asynchronous job reaches the failed state.
|
||||
|
||||
``job_id`` identifies the failed job when available. ``sql_job_id`` preserves
|
||||
the SQL execution identity reported by the server, which may differ from
|
||||
the outer job's identity. ``request_id`` and ``job_request_id`` identify the
|
||||
current request and isolated worker request. A typed SQL cause is available
|
||||
through ``__cause__`` when the server reports one.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
job_id: Optional[str] = None,
|
||||
sql_job_id: Optional[str] = None,
|
||||
request_id: Optional[str] = None,
|
||||
job_request_id: Optional[str] = None,
|
||||
):
|
||||
super().__init__(message)
|
||||
self.job_id = job_id
|
||||
self.sql_job_id = sql_job_id
|
||||
self.request_id = request_id
|
||||
self.job_request_id = job_request_id
|
||||
|
||||
|
||||
class JobCancelledError(RuntimeError):
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,256 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Property graphs: graphs defined over tables a database already holds.
|
||||
|
||||
A property graph stores no rows. Its definition says which tables of its
|
||||
namespace hold nodes and which hold edges: each node table's key and label
|
||||
(:class:`NodeTable`), and each edge table's label and the node keys its source
|
||||
and destination columns reference (:class:`EdgeTable`) -- the shape of
|
||||
SQL/PGQ's ``CREATE PROPERTY GRAPH``. A query reads the tables through SQL
|
||||
``GRAPH_TABLE``, as they are when it runs.
|
||||
|
||||
See ``DBConnection.create_property_graph``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
from .background_loop import LOOP
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ._lancedb import Connection as LanceDbConnection
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NodeTable:
|
||||
"""A table whose rows are the nodes of one label."""
|
||||
|
||||
table: str
|
||||
"""The table, in the graph's namespace."""
|
||||
key: str
|
||||
"""The column that identifies a node."""
|
||||
label: str
|
||||
"""The label its nodes carry."""
|
||||
properties: Optional[List[str]] = None
|
||||
"""The columns exposed as node properties; every column when ``None``. A
|
||||
created graph reports the list it resolved to, the key among them."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Endpoint:
|
||||
"""One end of an edge: a column of the edge table and the node key it holds."""
|
||||
|
||||
column: str
|
||||
"""The edge table's column."""
|
||||
references: Tuple[str, str]
|
||||
"""The node table and its key column, as ``(table, column)``."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EdgeTable:
|
||||
"""A table whose rows are the edges of one label."""
|
||||
|
||||
table: str
|
||||
"""The table, in the graph's namespace."""
|
||||
label: str
|
||||
"""The label its edges carry."""
|
||||
source: Endpoint
|
||||
"""The column naming each edge's source node."""
|
||||
destination: Endpoint
|
||||
"""The column naming each edge's destination node."""
|
||||
properties: Optional[List[str]] = None
|
||||
"""The columns exposed as edge properties; every column when ``None``. A
|
||||
created graph reports the list it resolved to, both endpoint columns among
|
||||
them."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PropertyGraphDescription:
|
||||
"""What a database records about one property graph."""
|
||||
|
||||
name: str
|
||||
"""The graph's name within its namespace."""
|
||||
namespace_path: List[str]
|
||||
"""The namespace holding the graph; empty is the root namespace."""
|
||||
nodes: List[NodeTable]
|
||||
"""The node tables, each with the properties create resolved."""
|
||||
edges: List[EdgeTable]
|
||||
"""The edge tables, each with the properties create resolved."""
|
||||
|
||||
|
||||
def _definition_json(nodes: Sequence[NodeTable], edges: Sequence[EdgeTable]) -> str:
|
||||
"""The definition a create request carries, refusing elements of the wrong
|
||||
type before any request is made."""
|
||||
nodes, edges = list(nodes), list(edges)
|
||||
for element, expected in [
|
||||
*((node, NodeTable) for node in nodes),
|
||||
*((edge, EdgeTable) for edge in edges),
|
||||
]:
|
||||
if not isinstance(element, expected):
|
||||
raise TypeError(
|
||||
"A property graph's nodes are NodeTable and its edges EdgeTable, "
|
||||
f"not {type(element).__name__}"
|
||||
)
|
||||
return json.dumps(
|
||||
{
|
||||
"nodes": [_node_table_to_json(node) for node in nodes],
|
||||
"edges": [_edge_table_to_json(edge) for edge in edges],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _description_from_json(text: str) -> PropertyGraphDescription:
|
||||
described = json.loads(text)
|
||||
return PropertyGraphDescription(
|
||||
name=described["name"],
|
||||
namespace_path=list(described.get("namespace", [])),
|
||||
nodes=[_node_table_from_json(node) for node in described["nodes"]],
|
||||
edges=[_edge_table_from_json(edge) for edge in described.get("edges", [])],
|
||||
)
|
||||
|
||||
|
||||
def _properties_to_json(
|
||||
encoded: Dict[str, Any], properties: Optional[List[str]]
|
||||
) -> None:
|
||||
# Absent means every column, which an empty list would not.
|
||||
if properties is None:
|
||||
return
|
||||
if isinstance(properties, str):
|
||||
raise TypeError("properties is a list of column names, not a string")
|
||||
encoded["properties"] = list(properties)
|
||||
|
||||
|
||||
def _node_table_to_json(node: NodeTable) -> Dict[str, Any]:
|
||||
encoded: Dict[str, Any] = {
|
||||
"table": node.table,
|
||||
"key": node.key,
|
||||
"label": node.label,
|
||||
}
|
||||
_properties_to_json(encoded, node.properties)
|
||||
return encoded
|
||||
|
||||
|
||||
def _edge_table_to_json(edge: EdgeTable) -> Dict[str, Any]:
|
||||
encoded: Dict[str, Any] = {
|
||||
"table": edge.table,
|
||||
"label": edge.label,
|
||||
"source": _endpoint_to_json(edge.source),
|
||||
"destination": _endpoint_to_json(edge.destination),
|
||||
}
|
||||
_properties_to_json(encoded, edge.properties)
|
||||
return encoded
|
||||
|
||||
|
||||
def _endpoint_to_json(endpoint: Endpoint) -> Dict[str, Any]:
|
||||
if not isinstance(endpoint, Endpoint):
|
||||
raise TypeError(
|
||||
"An edge's source and destination are Endpoint, "
|
||||
f"not {type(endpoint).__name__}"
|
||||
)
|
||||
table, column = endpoint.references
|
||||
return {
|
||||
"column": endpoint.column,
|
||||
"references": {"table": table, "column": column},
|
||||
}
|
||||
|
||||
|
||||
def _node_table_from_json(node: Dict[str, Any]) -> NodeTable:
|
||||
return NodeTable(
|
||||
table=node["table"],
|
||||
key=node["key"],
|
||||
label=node["label"],
|
||||
properties=node.get("properties"),
|
||||
)
|
||||
|
||||
|
||||
def _edge_table_from_json(edge: Dict[str, Any]) -> EdgeTable:
|
||||
return EdgeTable(
|
||||
table=edge["table"],
|
||||
label=edge["label"],
|
||||
source=_endpoint_from_json(edge["source"]),
|
||||
destination=_endpoint_from_json(edge["destination"]),
|
||||
properties=edge.get("properties"),
|
||||
)
|
||||
|
||||
|
||||
def _endpoint_from_json(endpoint: Dict[str, Any]) -> Endpoint:
|
||||
references = endpoint["references"]
|
||||
return Endpoint(
|
||||
column=endpoint["column"],
|
||||
references=(references["table"], references["column"]),
|
||||
)
|
||||
|
||||
|
||||
class AsyncPropertyGraph:
|
||||
"""A handle on one property graph: its name and namespace, and the
|
||||
connection it is described through.
|
||||
|
||||
Obtained from ``AsyncConnection.create_property_graph`` or
|
||||
``AsyncConnection.open_property_graph``. The graph is queried through SQL
|
||||
``GRAPH_TABLE``, not through this handle.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
inner: "LanceDbConnection",
|
||||
name: str,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
):
|
||||
self._inner = inner
|
||||
self._name = name
|
||||
self._namespace_path = list(namespace_path or [])
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"AsyncPropertyGraph(name={self._name!r}, "
|
||||
f"namespace_path={self._namespace_path!r})"
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""The graph's name within its namespace."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def namespace_path(self) -> List[str]:
|
||||
"""The namespace holding the graph; empty is the root namespace."""
|
||||
return list(self._namespace_path)
|
||||
|
||||
async def describe(self) -> PropertyGraphDescription:
|
||||
"""The graph's node and edge tables, each with the properties create
|
||||
resolved."""
|
||||
return _description_from_json(
|
||||
await self._inner.describe_property_graph(self._name, self._namespace_path)
|
||||
)
|
||||
|
||||
|
||||
class PropertyGraph:
|
||||
"""Synchronous variant of
|
||||
[AsyncPropertyGraph][lancedb.graph.AsyncPropertyGraph]."""
|
||||
|
||||
def __init__(self, graph: AsyncPropertyGraph):
|
||||
self._async = graph
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"PropertyGraph(name={self.name!r}, namespace_path={self.namespace_path!r})"
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""The graph's name within its namespace."""
|
||||
return self._async.name
|
||||
|
||||
@property
|
||||
def namespace_path(self) -> List[str]:
|
||||
"""The namespace holding the graph; empty is the root namespace."""
|
||||
return self._async.namespace_path
|
||||
|
||||
def describe(self) -> PropertyGraphDescription:
|
||||
"""The graph's node and edge tables, each with the properties create
|
||||
resolved."""
|
||||
return LOOP.run(self._async.describe())
|
||||
@@ -85,7 +85,7 @@ class LabelList:
|
||||
"""Describe a LabelList index configuration.
|
||||
|
||||
`LabelList` is a scalar index that can be used on `List<T>` columns to
|
||||
support queries with `array_contains_all` and `array_contains_any`
|
||||
support queries with `array_has_all` and `array_has_any`
|
||||
using an underlying bitmap index.
|
||||
|
||||
For example, it works with `tags`, `categories`, `keywords`, etc.
|
||||
@@ -108,6 +108,28 @@ class Fm:
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class NGram:
|
||||
"""Describe an NGram index configuration.
|
||||
|
||||
An `NGram` index is a scalar index on a UTF-8 string column that
|
||||
accelerates substring filters such as `contains(col, 'needle')`, along
|
||||
with some `LIKE` and regular-expression predicates. It tokenizes values
|
||||
into overlapping character n-grams (using Lance's default trigram
|
||||
parameters) and narrows a scan to the rows that share the query's n-grams;
|
||||
the exact predicate is then evaluated on those candidates, so the results
|
||||
are the same with or without the index.
|
||||
|
||||
Unlike the `Fm` index, which matches arbitrary substrings of the raw
|
||||
bytes, `NGram` is trigram based, so a query shorter than the n-gram length
|
||||
cannot be served by the index.
|
||||
|
||||
For example, it works with `text`, `description`, `comment`, etc.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class FTS:
|
||||
"""Describe a FTS index configuration.
|
||||
@@ -145,7 +167,7 @@ class FTS:
|
||||
Lance tokenizer can panic on malformed triples; see
|
||||
https://github.com/lance-format/lance/issues/8812.
|
||||
|
||||
LanceDB Distributed uses the same ``FTS()`` configuration and requires a
|
||||
LanceDB Enterprise uses the same ``FTS()`` configuration and requires a
|
||||
server that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])``
|
||||
before searching a newly created index there with its default name.
|
||||
|
||||
@@ -160,6 +182,10 @@ class FTS:
|
||||
>>> from lancedb.query import DocumentGranularity
|
||||
>>> config = FTS(document_granularity=DocumentGranularity.LIST_ELEMENT)
|
||||
|
||||
Create an index that splits code identifiers into searchable subwords:
|
||||
|
||||
>>> config = FTS(analyzer="code", split_identifiers=True)
|
||||
|
||||
Attributes
|
||||
----------
|
||||
with_position : bool, default False
|
||||
@@ -210,17 +236,39 @@ class FTS:
|
||||
memory_limit : int, optional
|
||||
The total memory limit in MiB for the local FTS build stage. The limit
|
||||
is divided evenly among indexing workers. This build-only setting is
|
||||
not persisted with the index and does not apply to LanceDB Distributed.
|
||||
not persisted with the index and does not apply to LanceDB Enterprise.
|
||||
num_workers : int, optional
|
||||
The number of workers for a local FTS build. By default Lance uses
|
||||
roughly half of the available CPU cores. The effective value is
|
||||
limited by the available compute capacity. This build-only setting is
|
||||
not persisted with the index and does not apply to LanceDB Distributed.
|
||||
not persisted with the index and does not apply to LanceDB Enterprise.
|
||||
document_granularity : DocumentGranularity, default ROW
|
||||
``ROW`` treats the selected text in one table row as one document.
|
||||
``LIST_ELEMENT`` treats each element of the deepest list on the indexed
|
||||
field path as one document and returns its physical coordinates in
|
||||
``_doc_index`` for matching queries.
|
||||
analyzer : {"text", "code"}, optional
|
||||
``"code"`` selects the code analyzer. ``"text"`` selects a text-family
|
||||
analyzer with the selected ``base_tokenizer``; it does not reset an
|
||||
explicit compatible tokenizer to ``"simple"``. ``None`` infers the
|
||||
analyzer from ``base_tokenizer``. ``"code"`` cannot be combined with a
|
||||
``base_tokenizer`` other than ``"simple"`` (the default) or ``"code"``.
|
||||
``"text"`` cannot be combined with ``"code"``.
|
||||
split_identifiers : bool, optional
|
||||
Split code identifiers such as ``camelCase`` and ``snake_case`` into
|
||||
subwords. Setting this to True requires the code analyzer. The default
|
||||
is False, so ``analyzer="code"`` alone keeps identifiers whole.
|
||||
split_on_numerics : bool, optional
|
||||
Split identifier subwords at letter and number boundaries, for example
|
||||
``utf8`` into ``utf`` and ``8``. The code analyzer default is True, but
|
||||
this only takes effect when ``split_identifiers=True``.
|
||||
preserve_original : bool, optional
|
||||
Also index the complete identifier next to its subwords. The code
|
||||
analyzer default is True, but this only takes effect when
|
||||
``split_identifiers=True``.
|
||||
index_operators : bool, optional
|
||||
Index code operators such as ``::``, ``->`` and ``!=``. The code
|
||||
analyzer default is False.
|
||||
|
||||
Notes
|
||||
-----
|
||||
@@ -246,6 +294,11 @@ class FTS:
|
||||
memory_limit: Optional[int] = None
|
||||
num_workers: Optional[int] = None
|
||||
document_granularity: DocumentGranularity = DocumentGranularity.ROW
|
||||
analyzer: Optional[Literal["text", "code"]] = None
|
||||
split_identifiers: Optional[bool] = None
|
||||
split_on_numerics: Optional[bool] = None
|
||||
preserve_original: Optional[bool] = None
|
||||
index_operators: Optional[bool] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -930,4 +983,5 @@ __all__ = [
|
||||
"Bitmap",
|
||||
"LabelList",
|
||||
"Fm",
|
||||
"NGram",
|
||||
]
|
||||
|
||||
+297
-10
@@ -5,6 +5,7 @@
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from typing import Any, Callable, Generic, Optional, TypeVar, cast
|
||||
|
||||
@@ -13,7 +14,8 @@ import pyarrow as pa
|
||||
from lancedb.background_loop import LOOP
|
||||
|
||||
from . import _lancedb
|
||||
from ._lancedb import JobDescription, JobFailureInfo, JobInfo
|
||||
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
|
||||
from .remote.errors import HttpError, RetryError
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
@@ -26,6 +28,162 @@ __all__ = [
|
||||
]
|
||||
|
||||
|
||||
def _timeout_message(
|
||||
job_id: Optional[str], timeout: timedelta, job_type: Optional[str]
|
||||
) -> str:
|
||||
seconds = f"{timeout.total_seconds():g}"
|
||||
unit = "second" if seconds == "1" else "seconds"
|
||||
if job_id is None:
|
||||
return (
|
||||
f"operation still running after {seconds} {unit}; "
|
||||
"it continues on the server"
|
||||
)
|
||||
if job_type == "query":
|
||||
return (
|
||||
f"query {job_id!r} still running after {seconds} {unit}; "
|
||||
"it continues on the server; keep this handle to continue waiting"
|
||||
)
|
||||
return (
|
||||
f"job {job_id!r} still running after {seconds} {unit}; "
|
||||
"it continues on the server; "
|
||||
f"reattach with db.open_job({job_id!r}).wait()"
|
||||
)
|
||||
|
||||
|
||||
def _normalize_job_progress(progress):
|
||||
"""Normalize ``wait(progress=...)`` using the same convention as writes."""
|
||||
if progress is True:
|
||||
from tqdm.auto import tqdm
|
||||
|
||||
return tqdm(unit=" rows"), True
|
||||
if progress is False or progress is None:
|
||||
return None, False
|
||||
return progress, False
|
||||
|
||||
|
||||
_ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000
|
||||
|
||||
|
||||
def _progress_eta(previous, current):
|
||||
"""Best-effort remaining time from two same-execution observations."""
|
||||
if not previous or current.get("state") not in ("running", "finished"):
|
||||
return None
|
||||
remaining = current.get("rows_remaining")
|
||||
if current.get("state") == "finished":
|
||||
return 0 if remaining == 0 else None
|
||||
if current.get("paused") or current.get("phase") in (
|
||||
"queued",
|
||||
"starting",
|
||||
"paused",
|
||||
):
|
||||
return None
|
||||
epoch = current.get("execution_epoch")
|
||||
if epoch is None or previous.get("execution_epoch") != epoch:
|
||||
return None
|
||||
sample_at = current.get("sample_at_millis")
|
||||
previous_at = previous.get("sample_at_millis")
|
||||
if not isinstance(sample_at, int) or not isinstance(previous_at, int):
|
||||
return None
|
||||
elapsed = sample_at - previous_at
|
||||
if not 0 < elapsed <= _ETA_MAX_SAMPLE_INTERVAL_MILLIS:
|
||||
return None
|
||||
if time.time() * 1_000 - sample_at > _ETA_MAX_SAMPLE_INTERVAL_MILLIS:
|
||||
return None
|
||||
planned = current.get("rows_planned")
|
||||
if not isinstance(planned, int) or not isinstance(remaining, int):
|
||||
return None
|
||||
if remaining == 0:
|
||||
return 0
|
||||
if planned != previous.get("rows_planned"):
|
||||
return None
|
||||
if current.get("fragments_planned") != previous.get("fragments_planned"):
|
||||
return None
|
||||
accounted = current.get("rows_computed", 0) + current.get("rows_skipped", 0)
|
||||
previous_accounted = previous.get("rows_computed", 0) + previous.get(
|
||||
"rows_skipped", 0
|
||||
)
|
||||
advanced = accounted - previous_accounted
|
||||
previous_remaining = previous.get("rows_remaining")
|
||||
if advanced <= 0 or not isinstance(previous_remaining, int):
|
||||
return None
|
||||
if remaining > previous_remaining:
|
||||
return None
|
||||
return remaining * elapsed // advanced
|
||||
|
||||
|
||||
def _with_progress_eta(previous, current):
|
||||
snapshot = dict(current)
|
||||
estimate = _progress_eta(previous, snapshot)
|
||||
if estimate is not None:
|
||||
snapshot["estimated_remaining_time_millis"] = estimate
|
||||
return snapshot
|
||||
|
||||
|
||||
def _job_progress_callback(progress, enrich):
|
||||
"""Adapt a callback or tqdm-like object to structured job snapshots."""
|
||||
if progress is None:
|
||||
return None
|
||||
if callable(progress):
|
||||
return lambda snapshot: progress(enrich(snapshot))
|
||||
|
||||
# A caller-owned bar can outlive one wait call. Resume from its displayed
|
||||
# position instead of adding the same completed rows on the next call.
|
||||
last_rows = getattr(progress, "n", 0) or 0
|
||||
last_planned = getattr(progress, "total", None)
|
||||
last_epoch = None
|
||||
first_snapshot = True
|
||||
|
||||
def update(snapshot):
|
||||
nonlocal first_snapshot, last_epoch, last_planned, last_rows
|
||||
snapshot = enrich(snapshot)
|
||||
planned = snapshot.get("rows_planned")
|
||||
remaining = snapshot.get("rows_remaining")
|
||||
computed = snapshot.get("rows_computed")
|
||||
if isinstance(planned, int):
|
||||
epoch = snapshot.get("execution_epoch")
|
||||
reset = (isinstance(last_planned, int) and planned < last_planned) or (
|
||||
isinstance(last_epoch, int)
|
||||
and isinstance(epoch, int)
|
||||
and epoch != last_epoch
|
||||
)
|
||||
if reset:
|
||||
last_rows = 0
|
||||
if hasattr(progress, "reset"):
|
||||
progress.reset(total=planned)
|
||||
elif hasattr(progress, "n"):
|
||||
progress.n = 0
|
||||
progress.total = planned
|
||||
last_planned = planned
|
||||
if isinstance(epoch, int):
|
||||
last_epoch = epoch
|
||||
completed = None
|
||||
if isinstance(planned, int) and isinstance(remaining, int):
|
||||
completed = max(planned - remaining, 0)
|
||||
elif computed is not None:
|
||||
completed = computed
|
||||
if completed is not None:
|
||||
if isinstance(planned, int):
|
||||
completed = min(completed, planned)
|
||||
if first_snapshot and completed < last_rows:
|
||||
# The server may have started a new execution while a
|
||||
# caller-owned bar retained its old position.
|
||||
last_rows = completed
|
||||
if hasattr(progress, "n"):
|
||||
progress.n = completed
|
||||
if hasattr(progress, "refresh"):
|
||||
progress.refresh()
|
||||
if completed > last_rows:
|
||||
delta = completed - last_rows
|
||||
last_rows = completed
|
||||
progress.update(delta)
|
||||
first_snapshot = False
|
||||
phase = snapshot.get("phase") or snapshot.get("state")
|
||||
if phase is not None and hasattr(progress, "set_postfix_str"):
|
||||
progress.set_postfix_str(phase)
|
||||
|
||||
return update
|
||||
|
||||
|
||||
class AsyncJob(Generic[T]):
|
||||
"""A handle to an operation that may still be running.
|
||||
|
||||
@@ -41,6 +199,12 @@ class AsyncJob(Generic[T]):
|
||||
):
|
||||
self._inner = inner
|
||||
self._result_decoder = result_decoder
|
||||
self._last_progress_snapshot = None
|
||||
|
||||
def _enrich_progress(self, snapshot):
|
||||
enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
|
||||
self._last_progress_snapshot = enriched
|
||||
return enriched
|
||||
|
||||
@property
|
||||
def id(self) -> Optional[str]:
|
||||
@@ -65,21 +229,118 @@ class AsyncJob(Generic[T]):
|
||||
return "finished"
|
||||
return await self._inner.status()
|
||||
|
||||
async def wait(self, timeout: Optional[timedelta] = None) -> T:
|
||||
async def progress(self) -> Optional[dict[str, Any]]:
|
||||
"""Fetch a structured progress snapshot.
|
||||
|
||||
Registry jobs always report lifecycle fields. Queue metadata and
|
||||
counters are included when supplied by the server. Older servers may
|
||||
omit counters, and in-process operations return ``None``. A missing
|
||||
counter is unknown rather than zero. This is additive to :meth:`status`,
|
||||
whose string contract is unchanged.
|
||||
"""
|
||||
if self._inner is None:
|
||||
return None
|
||||
await self._inner.status()
|
||||
description = getattr(self._inner, "_description", None)
|
||||
if description is None or description.progress is None:
|
||||
return None
|
||||
return self._enrich_progress(description.progress)
|
||||
|
||||
async def wait(
|
||||
self,
|
||||
timeout: Optional[timedelta] = None,
|
||||
progress: Any = False,
|
||||
) -> T:
|
||||
"""Wait until the operation reaches a terminal state.
|
||||
|
||||
Returns the endpoint's typed result, or ``None`` for a unit-result
|
||||
job.
|
||||
|
||||
``progress=True`` renders a progress bar, ``progress=callable``
|
||||
receives each structured snapshot, and a tqdm-like object is updated in
|
||||
place. Observations use the backend's existing wait poller and never
|
||||
start a second job. The bar advances by remaining rows when available,
|
||||
because completed computation can include repeated work after a plan
|
||||
change. On each wait call, the first complete observation synchronizes
|
||||
a caller-owned bar with the server's current completed rows and total;
|
||||
later observations in a stable execution epoch use a high-water mark. A
|
||||
new execution epoch or smaller plan resets the bar to that plan.
|
||||
``False`` preserves the original wait behavior.
|
||||
|
||||
Raises `JobFailedError` if the operation failed, `JobCancelledError`
|
||||
if it was cancelled, and `TimeoutError` if `timeout` elapses first.
|
||||
Transient connection and read errors are retried with capped exponential
|
||||
backoff within the same timeout (indefinitely when no timeout is given).
|
||||
If the timeout expires while disconnected, raises `ConnectionError`
|
||||
instead, with the job ID and instructions to resume waiting. The job
|
||||
may still be running; timing out does not cancel it.
|
||||
|
||||
The timeout error identifies the job and explains that it continues on
|
||||
the server. Registry jobs include the ``db.open_job(id).wait()``
|
||||
reattach call; SQL query handles must be kept because their IDs cannot
|
||||
be reopened through the registry jobs API.
|
||||
"""
|
||||
if self._inner is None:
|
||||
return cast(T, None)
|
||||
if timeout is None:
|
||||
result = await self._inner.wait()
|
||||
else:
|
||||
result = await asyncio.wait_for(self._inner.wait(), timeout.total_seconds())
|
||||
progress_obj, owns = _normalize_job_progress(progress)
|
||||
progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
|
||||
last_error = None
|
||||
|
||||
async def wait_with_retries():
|
||||
nonlocal last_error
|
||||
delay = 0.25
|
||||
while True:
|
||||
try:
|
||||
if last_error is not None:
|
||||
# Confirm recovery before restarting the backend poller,
|
||||
# so a later timeout isn't blamed on an earlier outage.
|
||||
await self._inner.status()
|
||||
last_error = None
|
||||
delay = 0.25
|
||||
if progress_callback is None:
|
||||
return await self._inner.wait()
|
||||
return await self._inner.wait(progress=progress_callback)
|
||||
except (HttpError, RetryError) as error:
|
||||
cause = error.__cause__ if isinstance(error, RetryError) else error
|
||||
if not isinstance(cause, HttpError) or not cause.is_transport_error:
|
||||
raise
|
||||
last_error = error
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, 30.0)
|
||||
|
||||
try:
|
||||
try:
|
||||
if timeout is None:
|
||||
result = await wait_with_retries()
|
||||
else:
|
||||
result = await asyncio.wait_for(
|
||||
wait_with_retries(), timeout.total_seconds()
|
||||
)
|
||||
except asyncio.TimeoutError as error:
|
||||
if last_error is None:
|
||||
if timeout is None:
|
||||
raise
|
||||
raise TimeoutError(
|
||||
_timeout_message(self.id, timeout, self.job_type)
|
||||
) from error
|
||||
identity = (
|
||||
f"job {self.id!r}" if self.id is not None else "the operation"
|
||||
)
|
||||
if self.id is not None and self.job_type != "query":
|
||||
reconnect = (
|
||||
f"Use db.open_job({self.id!r}) to reconnect, then call wait() "
|
||||
"on the returned job."
|
||||
)
|
||||
else:
|
||||
reconnect = "Call wait() on this job handle to reconnect."
|
||||
raise ConnectionError(
|
||||
f"Lost connection while waiting and the timeout expired; "
|
||||
f"{identity} may still be running. "
|
||||
f"{reconnect}"
|
||||
) from last_error
|
||||
finally:
|
||||
if owns:
|
||||
progress_obj.close()
|
||||
if self._result_decoder is not None:
|
||||
return self._result_decoder(result)
|
||||
return cast(T, result)
|
||||
@@ -188,7 +449,10 @@ class AsyncJob(Generic[T]):
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"job event history is only available for server-side jobs"
|
||||
_append_doc_url(
|
||||
"job event history is only available for server-side jobs",
|
||||
"jobs",
|
||||
)
|
||||
)
|
||||
return await self._inner.events(limit=limit, filter=filter)
|
||||
|
||||
@@ -262,7 +526,11 @@ class Job(Generic[T]):
|
||||
return "finished"
|
||||
return LOOP.run(self._inner.status())
|
||||
|
||||
def wait(self, timeout: Optional[timedelta] = None) -> T:
|
||||
def wait(
|
||||
self,
|
||||
timeout: Optional[timedelta] = None,
|
||||
progress: Any = False,
|
||||
) -> T:
|
||||
"""Block until the operation reaches a terminal state.
|
||||
|
||||
Returns the endpoint's typed result, or ``None`` for a unit-result
|
||||
@@ -270,10 +538,26 @@ class Job(Generic[T]):
|
||||
|
||||
Raises `JobFailedError` if the operation failed, `JobCancelledError`
|
||||
if it was cancelled, and `TimeoutError` if `timeout` elapses first.
|
||||
Transient connection and read errors are retried within that timeout;
|
||||
if it expires while disconnected, raises `ConnectionError` with
|
||||
instructions to reconnect. Timing out does not cancel the job.
|
||||
|
||||
The timeout error identifies the job and explains that it continues on
|
||||
the server. Registry jobs include the ``db.open_job(id).wait()``
|
||||
reattach call; SQL query handles must be kept because their IDs cannot
|
||||
be reopened through the registry jobs API.
|
||||
|
||||
See :meth:`AsyncJob.wait`.
|
||||
"""
|
||||
if self._inner is None:
|
||||
return cast(T, None)
|
||||
return LOOP.run(self._inner.wait(timeout))
|
||||
return LOOP.run(self._inner.wait(timeout, progress=progress))
|
||||
|
||||
def progress(self) -> Optional[dict[str, Any]]:
|
||||
"""Fetch a structured progress snapshot. See :meth:`AsyncJob.progress`."""
|
||||
if self._inner is None:
|
||||
return None
|
||||
return LOOP.run(self._inner.progress())
|
||||
|
||||
def cancel(self):
|
||||
"""Request cancellation. Cancelling a finished operation is a no-op."""
|
||||
@@ -343,7 +627,10 @@ class Job(Generic[T]):
|
||||
"""
|
||||
if self._inner is None:
|
||||
raise NotImplementedError(
|
||||
"job event history is only available for server-side jobs"
|
||||
_append_doc_url(
|
||||
"job event history is only available for server-side jobs",
|
||||
"jobs",
|
||||
)
|
||||
)
|
||||
return LOOP.run(self._inner.events(limit=limit, filter=filter))
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ maintained by refresh. See ``DBConnection.create_materialized_view``.
|
||||
|
||||
LanceDB Embedded creation and refresh require the ``experimental-functions``
|
||||
Cargo feature in a source build. Published packages disable it. Opening, reading,
|
||||
listing and dropping existing views and LanceDB Distributed operations remain
|
||||
listing and dropping existing views and LanceDB Enterprise operations remain
|
||||
available.
|
||||
"""
|
||||
|
||||
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .functions import _validate_gpu_class_name
|
||||
from .background_loop import LOOP
|
||||
from .job import AsyncJob, Job, _typed_job
|
||||
|
||||
@@ -156,6 +157,34 @@ def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _refresh_execution_options(cpu_millis, memory_bytes, gpu_count, gpu_class):
|
||||
values = {
|
||||
"cpu_millis": cpu_millis,
|
||||
"memory_bytes": memory_bytes,
|
||||
"gpu_count": gpu_count,
|
||||
}
|
||||
for name, value in values.items():
|
||||
maximum = 2**32 - 1 if name == "gpu_count" else 2**64 - 1
|
||||
minimum = 0 if name == "gpu_count" else 1
|
||||
if value is not None and (
|
||||
type(value) is not int or not minimum <= value <= maximum
|
||||
):
|
||||
raise ValueError(
|
||||
f"{name} must be an integer between {minimum} and {maximum}"
|
||||
)
|
||||
if (cpu_millis is not None or memory_bytes is not None) and any(
|
||||
value is None for value in values.values()
|
||||
):
|
||||
raise ValueError(
|
||||
"cpu_millis, memory_bytes, and gpu_count must be specified together"
|
||||
)
|
||||
if gpu_class is not None:
|
||||
values["gpu_class"] = _validate_gpu_class_name(gpu_class)
|
||||
if gpu_count == 0:
|
||||
raise ValueError("gpu_class requires a positive GPU budget")
|
||||
return {name: value for name, value in values.items() if value is not None}
|
||||
|
||||
|
||||
class AsyncMaterializedView:
|
||||
"""A handle on a materialized view: its table plus its definition.
|
||||
|
||||
@@ -185,38 +214,73 @@ class AsyncMaterializedView:
|
||||
return _definition_from_json(raw)
|
||||
|
||||
async def refresh(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "RefreshMaterializedViewResult":
|
||||
"""Recompute the view from its source.
|
||||
|
||||
In LanceDB Distributed, ``full=True`` forces a rebuild; otherwise the
|
||||
In LanceDB Enterprise, ``full=True`` forces a rebuild; otherwise the
|
||||
server chooses the refresh mode. LanceDB Embedded views always rebuild,
|
||||
and ``source_version`` selects a source version instead of the latest.
|
||||
LanceDB Distributed SQL refreshes do not support source-version pinning.
|
||||
LanceDB Enterprise SQL refreshes do not support source-version pinning.
|
||||
|
||||
LanceDB Distributed results leave ``mode``, ``rows_written``, and
|
||||
``cpu_millis`` (1000 = one core), ``memory_bytes``, and ``gpu_count``
|
||||
cap aggregate resources for this execution, including its Function
|
||||
processes. CPU or memory requires all three budget fields; GPU count
|
||||
may be zero for CPU-only views. ``gpu_class`` selects an operator-defined
|
||||
GPU class for this execution only. Omitted options preserve defaults.
|
||||
These options require an Enterprise backend that enforces isolation;
|
||||
Embedded refreshes reject them. Other servers may reject the new options.
|
||||
|
||||
LanceDB Enterprise results leave ``mode``, ``rows_written``, and
|
||||
``source_version`` as ``None`` because the SQL job adapter does not expose
|
||||
these metrics.
|
||||
"""
|
||||
return await self._table._inner.refresh_materialized_view(
|
||||
source_version=source_version, full=full
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
)
|
||||
|
||||
async def refresh_async(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "AsyncJob[RefreshMaterializedViewResult]":
|
||||
"""Submit a refresh and return its job without waiting.
|
||||
|
||||
The job may already be complete in LanceDB Embedded. In LanceDB
|
||||
Distributed, refreshes are submitted through the SQL service. Options and
|
||||
Distributed, refreshes are submitted through the SQL service and the
|
||||
returned ``id`` is the registry job ID, usable with ``open_job`` for
|
||||
progress, events, and cancellation while the refresh runs. Options and
|
||||
result metrics follow
|
||||
[refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].
|
||||
|
||||
Servers without early registry-handle support return a connection-scoped
|
||||
query job instead. Its ID cannot be reopened with ``open_job``.
|
||||
"""
|
||||
from ._lancedb import RefreshMaterializedViewResult
|
||||
|
||||
return _typed_job(
|
||||
await self._table._inner.refresh_materialized_view_async(
|
||||
source_version=source_version, full=full
|
||||
source_version=source_version,
|
||||
full=full,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
),
|
||||
RefreshMaterializedViewResult.from_json,
|
||||
)
|
||||
@@ -248,14 +312,36 @@ class MaterializedView:
|
||||
return LOOP.run(self._async.definition())
|
||||
|
||||
def refresh(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "RefreshMaterializedViewResult":
|
||||
"""Recompute the view from its source. See
|
||||
[AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]."""
|
||||
return LOOP.run(self._async.refresh(full=full, source_version=source_version))
|
||||
return LOOP.run(
|
||||
self._async.refresh(
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
def refresh_async(
|
||||
self, *, full: bool = False, source_version: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
full: bool = False,
|
||||
source_version: Optional[int] = None,
|
||||
cpu_millis: Optional[int] = None,
|
||||
memory_bytes: Optional[int] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
) -> "Job[RefreshMaterializedViewResult]":
|
||||
"""Submit a refresh and return its job without waiting.
|
||||
|
||||
@@ -264,6 +350,12 @@ class MaterializedView:
|
||||
"""
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._async.refresh_async(full=full, source_version=source_version)
|
||||
self._async.refresh_async(
|
||||
full=full,
|
||||
source_version=source_version,
|
||||
**_refresh_execution_options(
|
||||
cpu_millis, memory_bytes, gpu_count, gpu_class
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -548,7 +548,7 @@ class Permutation:
|
||||
picklable classes implementing ``__call__``. Lambdas and closures over
|
||||
local variables don't pickle with the default protocol.
|
||||
|
||||
A factory is optional for normal LanceDB Embedded and Distributed connections:
|
||||
A factory is optional for normal LanceDB Embedded and Enterprise connections:
|
||||
if not set, ``__getstate__`` captures the table's own picklable reopen
|
||||
state. Use a factory when that default state is not enough, for example
|
||||
when credentials should be loaded from the worker environment instead
|
||||
|
||||
@@ -9,16 +9,19 @@ import inspect
|
||||
import sys
|
||||
import types
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from enum import Enum
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
List,
|
||||
Literal,
|
||||
Type,
|
||||
Union,
|
||||
_GenericAlias,
|
||||
GenericAlias,
|
||||
get_args,
|
||||
get_origin,
|
||||
)
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -247,6 +250,19 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType:
|
||||
elif py_type is datetime:
|
||||
tz = get_extras(field, "tz")
|
||||
return pa.timestamp("us", tz=tz)
|
||||
elif py_type is time:
|
||||
return pa.time64("us")
|
||||
elif py_type is timedelta:
|
||||
return pa.duration("us")
|
||||
elif get_origin(py_type) is Literal:
|
||||
# Store a Literal as the type of its values, e.g. Literal["a", "b"] as utf8.
|
||||
value_types = {type(value) for value in get_args(py_type)}
|
||||
if len(value_types) != 1:
|
||||
raise TypeError(
|
||||
"Converting Pydantic type to Arrow Type: unsupported type "
|
||||
f"{py_type}. All values of a Literal must have the same type."
|
||||
)
|
||||
return _pydantic_type_to_arrow_type(value_types.pop(), field)
|
||||
elif getattr(py_type, "__origin__", None) in (list, tuple):
|
||||
# A bare, unparameterised ``typing.List`` / ``typing.Tuple`` matches this
|
||||
# branch (its ``__origin__`` is ``list`` / ``tuple``) but has no
|
||||
@@ -304,8 +320,12 @@ def _pydantic_type_to_arrow_type(tp: Any, field: FieldInfo) -> pa.DataType:
|
||||
# Map Enum to the Arrow type of its value.
|
||||
# For string-valued enums, use dictionary encoding for efficiency.
|
||||
# For integer enums, use the native type.
|
||||
# Fall back to utf8 for mixed-type or empty enums.
|
||||
value_types = {type(m.value) for m in tp}
|
||||
if len(value_types) > 1:
|
||||
raise TypeError(
|
||||
f"Converting Pydantic Enum {tp.__name__} to Arrow Type: "
|
||||
"all enum values must have the same type."
|
||||
)
|
||||
if len(value_types) == 1:
|
||||
value_type = value_types.pop()
|
||||
if value_type is str:
|
||||
@@ -435,7 +455,8 @@ def pydantic_to_schema(model: Type[pydantic.BaseModel]) -> pa.Schema:
|
||||
an Arrow list, so all its elements must have the same type, as in
|
||||
``Tuple[int, int]`` or ``Tuple[float, ...]``; for a fixed set of fields
|
||||
with different types, such as ``Tuple[int, str]``, use a nested
|
||||
``LanceModel`` (an Arrow struct) instead.
|
||||
``LanceModel`` (an Arrow struct) instead. Enum values must also all
|
||||
have the same type.
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -556,21 +577,36 @@ def get_extras(field_info: FieldInfo, key: str) -> Any:
|
||||
|
||||
|
||||
def model_to_dict(model: pydantic.BaseModel) -> dict[str, Any]:
|
||||
"""Convert a Pydantic model to a dictionary."""
|
||||
return _enum_members_to_values(model.model_dump())
|
||||
"""Convert a Pydantic model to a dictionary.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If a ``datetime.time`` value has a non-null ``tzinfo``. LanceDB stores
|
||||
times as timezone-naive wall-clock values and cannot preserve the offset.
|
||||
"""
|
||||
return _model_value_to_arrow_compatible(model.model_dump())
|
||||
|
||||
|
||||
def _enum_members_to_values(value: Any) -> Any:
|
||||
def _model_value_to_arrow_compatible(value: Any) -> Any:
|
||||
# model_dump() keeps Enum members, and Arrow cannot convert a member of a
|
||||
# plain Enum (one without a str or int mixin). Write its value instead,
|
||||
# which is what the Arrow type of the field is derived from.
|
||||
if isinstance(value, Enum):
|
||||
return value.value
|
||||
value = value.value
|
||||
if isinstance(value, time):
|
||||
if value.tzinfo is not None:
|
||||
raise ValueError(
|
||||
"LanceDB supports timezone-naive wall-clock datetime.time values "
|
||||
"only; time values with tzinfo cannot be written losslessly. Remove "
|
||||
"the timezone offset or store it in a separate field."
|
||||
)
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {k: _enum_members_to_values(v) for k, v in value.items()}
|
||||
return {k: _model_value_to_arrow_compatible(v) for k, v in value.items()}
|
||||
if isinstance(value, (list, tuple)) and value:
|
||||
# Skip lists of plain scalars, such as vectors, without walking them.
|
||||
if isinstance(value[0], (int, float, str, bytes)):
|
||||
return value
|
||||
return [_enum_members_to_values(v) for v in value]
|
||||
return [_model_value_to_arrow_compatible(v) for v in value]
|
||||
return value
|
||||
|
||||
+240
-10
@@ -81,6 +81,85 @@ if TYPE_CHECKING:
|
||||
from typing_extensions import Self
|
||||
|
||||
T = TypeVar("T", bound="LanceModel")
|
||||
|
||||
|
||||
def _top_level_alias_key(alias: Any) -> str | None:
|
||||
if isinstance(alias, str):
|
||||
return alias
|
||||
if isinstance(alias, pydantic.AliasPath) and alias.path:
|
||||
key = alias.path[0]
|
||||
return key if isinstance(key, str) else None
|
||||
return None
|
||||
|
||||
|
||||
def _top_level_alias_keys(alias: Any) -> set[str]:
|
||||
options = alias.choices if isinstance(alias, pydantic.AliasChoices) else (alias,)
|
||||
return {
|
||||
key for option in options if (key := _top_level_alias_key(option)) is not None
|
||||
}
|
||||
|
||||
|
||||
def _single_component_alias(alias: Any) -> str | None:
|
||||
# AliasChoices validates against the first matching source, so only use
|
||||
# its first option as a field-name fallback.
|
||||
option = alias.choices[0] if isinstance(alias, pydantic.AliasChoices) else alias
|
||||
if isinstance(option, pydantic.AliasPath) and len(option.path) != 1:
|
||||
# A nested path needs a structured payload; do not infer one here.
|
||||
return None
|
||||
return _top_level_alias_key(option)
|
||||
|
||||
|
||||
def _rows_to_models(model: type[T], rows: List[dict]) -> List[T]:
|
||||
"""Build ``model`` instances from result rows.
|
||||
|
||||
A table created from a LanceModel stores each field under its name, while
|
||||
pydantic validates an aliased field by its alias. Pass a row's value under
|
||||
the alias when the row has the field name but none of the aliases, so a
|
||||
model with aliases can read the tables it wrote; rows keyed by any alias
|
||||
still work.
|
||||
"""
|
||||
if model.model_config.get("validate_by_alias", True) is False:
|
||||
# Name-only validation: pydantic reads field names and ignores aliases.
|
||||
return [model(**row) for row in rows]
|
||||
aliases = {
|
||||
name: field.validation_alias or field.alias
|
||||
for name, field in model.model_fields.items()
|
||||
}
|
||||
# populate_by_name is the pre-2.11 spelling; an explicit new flag wins.
|
||||
accepts_by_name = model.model_config.get(
|
||||
"validate_by_name",
|
||||
model.model_config.get("populate_by_name", False),
|
||||
)
|
||||
# Every top-level key some field reads, including the first step of an
|
||||
# AliasPath and each choice of an AliasChoices.
|
||||
alias_keys = {}
|
||||
for name, alias in aliases.items():
|
||||
keys = _top_level_alias_keys(alias)
|
||||
if not keys or accepts_by_name:
|
||||
keys.add(name)
|
||||
alias_keys[name] = keys
|
||||
readers = {}
|
||||
for name, keys in alias_keys.items():
|
||||
for key in keys:
|
||||
readers.setdefault(key, set()).add(name)
|
||||
renames = {
|
||||
name: target
|
||||
for name, alias in aliases.items()
|
||||
if (target := _single_component_alias(alias)) is not None
|
||||
# Do not move a source that another field reads.
|
||||
and target != name
|
||||
and not (readers.get(name, set()) - {name})
|
||||
# Do not add a source that another field accepts. Introducing a shared
|
||||
# alias key could change that field's Pydantic selection.
|
||||
and not (readers.get(target, set()) - {name})
|
||||
}
|
||||
for row in rows:
|
||||
for name, target in renames.items():
|
||||
if name in row and not any(key in row for key in alias_keys[name]):
|
||||
row[target] = row.pop(name)
|
||||
return [model(**row) for row in rows]
|
||||
|
||||
|
||||
AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"]
|
||||
_SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray)
|
||||
|
||||
@@ -125,7 +204,7 @@ def _supports_local_blob_fetch(
|
||||
def _blob_bytes_without_snapshot_error() -> NotImplementedError:
|
||||
return NotImplementedError(
|
||||
"blob_mode='bytes' cannot safely materialize blob columns without a "
|
||||
"stable table snapshot. LanceDB Distributed and namespace QueryTable pushdown "
|
||||
"stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown "
|
||||
"run the query on a server, so the blob fetch could read another table "
|
||||
"version. Use blob_mode='descriptions'."
|
||||
)
|
||||
@@ -157,6 +236,7 @@ def _query_is_plain_scan(query: Query) -> bool:
|
||||
query.vector is None
|
||||
and query.full_text_query is None
|
||||
and query.take_offsets is None
|
||||
and query.take_row_ids is None
|
||||
and not query.postfilter
|
||||
and not query.order_by
|
||||
)
|
||||
@@ -833,6 +913,12 @@ class Query(pydantic.BaseModel):
|
||||
ef : Optional[int]
|
||||
The size of the nearest neighbor list maintained during HNSW search
|
||||
|
||||
This will only be set on vector search.
|
||||
approx_mode : Optional[str]
|
||||
The speed / accuracy tradeoff to use for approximate vector search
|
||||
|
||||
One of "fast", "normal" or "accurate".
|
||||
|
||||
This will only be set on vector search.
|
||||
full_text_query : Optional[Union[str, dict]]
|
||||
The full text search query
|
||||
@@ -924,6 +1010,9 @@ class Query(pydantic.BaseModel):
|
||||
# This is populated when a take query is converted to this serializable form.
|
||||
take_offsets: Optional[List[int]] = None
|
||||
|
||||
# Row IDs whose requested order and duplicate occurrences must be restored.
|
||||
take_row_ids: Optional[List[int]] = None
|
||||
|
||||
# if true, will only search the indexed data
|
||||
fast_search: Optional[bool] = None
|
||||
|
||||
@@ -935,6 +1024,9 @@ class Query(pydantic.BaseModel):
|
||||
# size of the nearest neighbor list maintained during HNSW search
|
||||
ef: Optional[int] = None
|
||||
|
||||
# speed / accuracy tradeoff for approximate vector search
|
||||
approx_mode: Optional[str] = None
|
||||
|
||||
# Bypass the vector index and use a brute force search
|
||||
bypass_vector_index: Optional[bool] = None
|
||||
|
||||
@@ -946,6 +1038,7 @@ class Query(pydantic.BaseModel):
|
||||
query.limit = req.limit
|
||||
query.offset = req.offset
|
||||
query.take_offsets = req.take_offsets
|
||||
query.take_row_ids = req.take_row_ids
|
||||
query.filter = req.filter
|
||||
query.full_text_query = req.full_text_search
|
||||
query.columns = req.select
|
||||
@@ -965,6 +1058,7 @@ class Query(pydantic.BaseModel):
|
||||
query.lower_bound = req.lower_bound
|
||||
query.upper_bound = req.upper_bound
|
||||
query.ef = req.ef
|
||||
query.approx_mode = req.approx_mode
|
||||
query.refine_factor = req.refine_factor
|
||||
query.bypass_vector_index = req.bypass_vector_index
|
||||
query.postfilter = req.postfilter
|
||||
@@ -1133,6 +1227,7 @@ class LanceQueryBuilder(ABC):
|
||||
self._vector = None
|
||||
self._text = None
|
||||
self._ef = None
|
||||
self._approx_mode = None
|
||||
self._bypass_vector_index = None
|
||||
self._order_by = None
|
||||
|
||||
@@ -1184,7 +1279,7 @@ class LanceQueryBuilder(ABC):
|
||||
mode and for legacy blob columns. Other local blob v2
|
||||
queries return descriptors in ``"lazy"`` and ``"descriptions"``
|
||||
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
|
||||
LanceDB Distributed blob queries support only ``"descriptions"`` until a
|
||||
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
|
||||
stable
|
||||
table snapshot can bind the query and blob fetches.
|
||||
**kwargs
|
||||
@@ -1240,6 +1335,9 @@ class LanceQueryBuilder(ABC):
|
||||
and also the "_distance" column which is the distance between the query
|
||||
vector and the returned vectors.
|
||||
|
||||
This collects all results in memory. To process a large result a batch
|
||||
at a time, use [to_batches][lancedb.query.LanceQueryBuilder.to_batches].
|
||||
|
||||
Parameters
|
||||
----------
|
||||
timeout: Optional[timedelta]
|
||||
@@ -1271,6 +1369,11 @@ class LanceQueryBuilder(ABC):
|
||||
``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide
|
||||
automatic row ids.
|
||||
|
||||
A remote table decodes batches as they arrive when the server streams
|
||||
query results. If the response stops partway, reading raises
|
||||
[ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError]
|
||||
after the batches already returned, which are valid but incomplete.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch_size: int
|
||||
@@ -1278,6 +1381,8 @@ class LanceQueryBuilder(ABC):
|
||||
timeout: Optional[timedelta]
|
||||
The maximum time to wait for the query to complete.
|
||||
If None, wait indefinitely.
|
||||
The timeout also covers reading the batches, so consuming them
|
||||
slowly can exceed it.
|
||||
blob_mode: str, default "lazy"
|
||||
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
|
||||
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
|
||||
@@ -1340,7 +1445,7 @@ class LanceQueryBuilder(ABC):
|
||||
-------
|
||||
List[LanceModel]
|
||||
"""
|
||||
return [model(**row) for row in self.to_arrow(timeout=timeout).to_pylist()]
|
||||
return _rows_to_models(model, self.to_arrow(timeout=timeout).to_pylist())
|
||||
|
||||
def to_polars(self, *, timeout: Optional[timedelta] = None) -> "pl.DataFrame":
|
||||
"""
|
||||
@@ -1965,6 +2070,11 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
def search_effort(self, search_effort: Optional[float]) -> LanceVectorQueryBuilder:
|
||||
"""Set the initial IVF search effort to a finite value in [0, 1].
|
||||
|
||||
Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
|
||||
80% and 90% for L2, cosine and dot through k=100000. The probe budget
|
||||
adapts to the metric and k. Hamming and larger k remain uncalibrated;
|
||||
100000 is not an API limit. Remote queries also require server support.
|
||||
|
||||
None (the default) uses Auto, internally 0.5. Zero starts at the caller
|
||||
minimum; one searches all partitions within the caller maximum. Later
|
||||
probing may continue when too few candidates are found. Any explicit
|
||||
@@ -2057,6 +2167,35 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
self._ef = ef
|
||||
return self
|
||||
|
||||
def approx_mode(
|
||||
self, approx_mode: Literal["fast", "normal", "accurate"]
|
||||
) -> LanceVectorQueryBuilder:
|
||||
"""Set the speed / accuracy tradeoff to use for approximate search.
|
||||
|
||||
This currently affects RQ-quantized indexes, such as IVF_RQ, and
|
||||
prefiltered search on HNSW indexes, where "fast" enables the ACORN
|
||||
traversal. Other index types ignore this setting.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory://")
|
||||
>>> table = db.create_table("approx_vectors", [{"vector": [0.1, 0.2]}])
|
||||
>>> query = table.search([0.1, 0.2]).approx_mode("fast")
|
||||
|
||||
Parameters
|
||||
----------
|
||||
approx_mode: "fast" or "normal" or "accurate"
|
||||
The tradeoff to use. By default "normal" is used.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceVectorQueryBuilder
|
||||
The LanceQueryBuilder object.
|
||||
"""
|
||||
self._approx_mode = approx_mode
|
||||
return self
|
||||
|
||||
def refine_factor(self, refine_factor: int) -> LanceVectorQueryBuilder:
|
||||
"""Set the refine factor to use, increasing the number of vectors sampled.
|
||||
|
||||
@@ -2151,6 +2290,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
offset=self._offset,
|
||||
fast_search=self._fast_search,
|
||||
ef=self._ef,
|
||||
approx_mode=self._approx_mode,
|
||||
bypass_vector_index=self._bypass_vector_index,
|
||||
order_by=self._order_by,
|
||||
)
|
||||
@@ -2173,6 +2313,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
timeout: timedelta, default None
|
||||
The maximum time to wait for the query to complete.
|
||||
If None, wait indefinitely.
|
||||
The timeout also covers reading the batches, so consuming them
|
||||
slowly can exceed it.
|
||||
blob_mode: str, default "lazy"
|
||||
Controls blob conversion as described in
|
||||
:meth:`LanceQueryBuilder.to_batches`.
|
||||
@@ -2709,7 +2851,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
)
|
||||
if not with_row_ids and "_rowid" in empty.column_names:
|
||||
empty = empty.drop(["_rowid"])
|
||||
return empty
|
||||
# Match the columns a non-empty result has for this reranker. Call the
|
||||
# base method so an override that assumes rows never sees the empty
|
||||
# table (#3030).
|
||||
return Reranker._keep_relevance_score(reranker, empty)
|
||||
|
||||
original_distances = None
|
||||
original_scores = None
|
||||
@@ -2891,6 +3036,11 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
def search_effort(self, search_effort: Optional[float]) -> LanceHybridQueryBuilder:
|
||||
"""Set the initial IVF search effort to a finite value in [0, 1].
|
||||
|
||||
Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
|
||||
80% and 90% for L2, cosine and dot through k=100000. The probe budget
|
||||
adapts to the metric and k. Hamming and larger k remain uncalibrated;
|
||||
100000 is not an API limit. Remote queries also require server support.
|
||||
|
||||
None (the default) uses Auto, internally 0.5. Zero starts at the caller
|
||||
minimum; one searches all partitions within the caller maximum. Later
|
||||
probing may continue when too few candidates are found. Any explicit
|
||||
@@ -2978,6 +3128,43 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
self._ef = ef
|
||||
return self
|
||||
|
||||
def approx_mode(
|
||||
self, approx_mode: Literal["fast", "normal", "accurate"]
|
||||
) -> LanceHybridQueryBuilder:
|
||||
"""
|
||||
Set the speed / accuracy tradeoff to use for approximate search.
|
||||
|
||||
This currently affects RQ-quantized indexes, such as IVF_RQ, and
|
||||
prefiltered search on HNSW indexes, where "fast" enables the ACORN
|
||||
traversal. Other index types ignore this setting.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("memory://")
|
||||
>>> table = db.create_table(
|
||||
... "approx_hybrid", [{"vector": [0.1, 0.2], "text": "dog"}]
|
||||
... )
|
||||
>>> query = (
|
||||
... table.search(query_type="hybrid")
|
||||
... .vector([0.1, 0.2])
|
||||
... .text("dog")
|
||||
... .approx_mode("accurate")
|
||||
... )
|
||||
|
||||
Parameters
|
||||
----------
|
||||
approx_mode: "fast" or "normal" or "accurate"
|
||||
The tradeoff to use. By default "normal" is used.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceHybridQueryBuilder
|
||||
The LanceHybridQueryBuilder object.
|
||||
"""
|
||||
self._approx_mode = approx_mode
|
||||
return self
|
||||
|
||||
def metric(self, metric: Literal["l2", "cosine", "dot"]) -> LanceHybridQueryBuilder:
|
||||
"""Set the distance metric to use.
|
||||
|
||||
@@ -3222,6 +3409,8 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
self._vector_query.refine_factor(self._refine_factor)
|
||||
if self._ef:
|
||||
self._vector_query.ef(self._ef)
|
||||
if self._approx_mode:
|
||||
self._vector_query.approx_mode(self._approx_mode)
|
||||
if self._bypass_vector_index:
|
||||
self._vector_query.bypass_vector_index()
|
||||
if self._lower_bound is not None or self._upper_bound is not None:
|
||||
@@ -3393,6 +3582,11 @@ class AsyncQueryBase(object):
|
||||
"""
|
||||
Execute the query and return the results as an Apache Arrow RecordBatchReader.
|
||||
|
||||
A remote table decodes batches as they arrive when the server streams
|
||||
query results. If the response stops partway, reading raises
|
||||
[ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError]
|
||||
after the batches already returned, which are valid but incomplete.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
|
||||
@@ -3405,6 +3599,8 @@ class AsyncQueryBase(object):
|
||||
The maximum time to wait for the query to complete.
|
||||
If not specified, no timeout is applied. If the query does not
|
||||
complete within the specified time, an error will be raised.
|
||||
The timeout also covers reading the batches, so consuming them
|
||||
slowly can exceed it.
|
||||
blob_mode: str, default "lazy"
|
||||
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
|
||||
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
|
||||
@@ -3521,7 +3717,7 @@ class AsyncQueryBase(object):
|
||||
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
|
||||
``"bytes"`` returns payload bytes and raises for legacy blob columns
|
||||
and blobs inside lists.
|
||||
LanceDB Distributed and namespace query pushdown refuse ``"bytes"``.
|
||||
LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``.
|
||||
"""
|
||||
blob_sources = await self._validated_blob_sources(blob_mode)
|
||||
batch_iter = await self.to_batches(timeout=timeout)
|
||||
@@ -3600,7 +3796,7 @@ class AsyncQueryBase(object):
|
||||
mode and for legacy blob columns. Other local blob v2
|
||||
queries return descriptors in ``"lazy"`` and ``"descriptions"``
|
||||
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
|
||||
LanceDB Distributed blob queries support only ``"descriptions"`` until a
|
||||
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
|
||||
stable
|
||||
table snapshot can bind the query and blob fetches.
|
||||
**kwargs
|
||||
@@ -3770,9 +3966,9 @@ class AsyncQueryBase(object):
|
||||
-------
|
||||
list[LanceModel]
|
||||
"""
|
||||
return [
|
||||
model(**row) for row in (await self.to_arrow(timeout=timeout)).to_pylist()
|
||||
]
|
||||
return _rows_to_models(
|
||||
model, (await self.to_arrow(timeout=timeout)).to_pylist()
|
||||
)
|
||||
|
||||
async def explain_plan(self, verbose: Optional[bool] = False):
|
||||
"""Return the execution plan for this query.
|
||||
@@ -4249,7 +4445,7 @@ class AsyncVectorQueryBase:
|
||||
you the desired recall.
|
||||
|
||||
LanceDB retains this as `nprobes` through LanceDB Embedded and LanceDB
|
||||
Distributed request construction. Lance sets both probe bounds to this
|
||||
Enterprise request construction. Lance sets both probe bounds to this
|
||||
value. Explicit minimum or maximum settings can override their respective
|
||||
bounds.
|
||||
"""
|
||||
@@ -4259,6 +4455,11 @@ class AsyncVectorQueryBase:
|
||||
def search_effort(self, search_effort: Optional[float]) -> Self:
|
||||
"""Set the initial IVF search effort to a finite value in [0, 1].
|
||||
|
||||
Efforts 0.1 and 0.25 target empirical mean partition-routing recall of
|
||||
80% and 90% for L2, cosine and dot through k=100000. The probe budget
|
||||
adapts to the metric and k. Hamming and larger k remain uncalibrated;
|
||||
100000 is not an API limit. Remote queries also require server support.
|
||||
|
||||
None preserves Auto (internally 0.5) and fixed nprobes. Any explicit
|
||||
effort, including 0.5, overrides nprobes in either call order; explicit
|
||||
minimum and maximum bounds remain effective. Zero starts at the caller
|
||||
@@ -4348,6 +4549,33 @@ class AsyncVectorQueryBase:
|
||||
self._inner.ef(ef)
|
||||
return self
|
||||
|
||||
def approx_mode(self, approx_mode: Literal["fast", "normal", "accurate"]) -> Self:
|
||||
"""
|
||||
Set the speed / accuracy tradeoff to use for approximate search
|
||||
|
||||
This currently affects RQ-quantized indexes, such as IVF_RQ, and prefiltered
|
||||
search on HNSW indexes, where "fast" enables the ACORN traversal. Other index
|
||||
types ignore this setting.
|
||||
|
||||
"fast" favors lower latency and may reduce recall, "normal" (the default) uses
|
||||
the index's default balance, and "accurate" favors higher recall and may
|
||||
increase latency.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import asyncio
|
||||
>>> import lancedb
|
||||
>>> async def build_query():
|
||||
... db = await lancedb.connect_async("memory://")
|
||||
... table = await db.create_table(
|
||||
... "approx_async", [{"vector": [0.1, 0.2]}]
|
||||
... )
|
||||
... return table.vector_search([0.1, 0.2]).approx_mode("accurate")
|
||||
>>> query = asyncio.run(build_query())
|
||||
"""
|
||||
self._inner.approx_mode(approx_mode)
|
||||
return self
|
||||
|
||||
def refine_factor(self, refine_factor: int) -> Self:
|
||||
"""
|
||||
A multiplier to control how many additional rows are taken during the refine
|
||||
@@ -4905,6 +5133,8 @@ class BaseQueryBuilder(object):
|
||||
The maximum time to wait for the query to complete.
|
||||
If not specified, no timeout is applied. If the query does not
|
||||
complete within the specified time, an error will be raised.
|
||||
The timeout also covers reading the batches, so consuming them
|
||||
slowly can exceed it.
|
||||
blob_mode: str, default "lazy"
|
||||
Controls blob conversion as described in
|
||||
:meth:`AsyncQueryBase.to_batches`.
|
||||
|
||||
@@ -15,6 +15,7 @@ from typing import (
|
||||
Dict,
|
||||
Iterable,
|
||||
List,
|
||||
Literal,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
@@ -37,16 +38,18 @@ 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 ..functions import FunctionVersion, FunctionDefinition
|
||||
from ..graph import EdgeTable, NodeTable, PropertyGraph
|
||||
from ..job import AsyncJob, Job
|
||||
from ..sql import Query as SqlQuery
|
||||
from ..sql import QueryDescription, QueryParameters
|
||||
from ..materialized_view import MaterializedView, MaterializedViewSource, SelectArg
|
||||
from ..secrets import EnvVarSecret, SecretInfo
|
||||
from ..storage_integration import SecretReference, StorageIntegrationInfo
|
||||
from ..view import ViewDescription
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .._lancedb import JobInfo, Session
|
||||
from .._lancedb import GpuClass, JobInfo, Session
|
||||
from ..embeddings import EmbeddingFunctionConfig
|
||||
from lance_namespace import (
|
||||
LanceNamespace,
|
||||
@@ -101,7 +104,7 @@ def _tls_config_to_dict(config: Optional[TlsConfig]) -> Optional[dict[str, Any]]
|
||||
def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]:
|
||||
if config.header_provider is not None:
|
||||
raise ValueError(
|
||||
"Cannot serialize a LanceDB Distributed connection with a header_provider. "
|
||||
"Cannot serialize a LanceDB Enterprise connection with a header_provider. "
|
||||
"Use static api_key/extra_headers or provide a worker-side "
|
||||
"connection factory instead."
|
||||
)
|
||||
@@ -246,16 +249,16 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@property
|
||||
def session(self) -> Optional["Session"]:
|
||||
"""LanceDB Distributed connections do not expose a local cache session."""
|
||||
"""LanceDB Enterprise connections do not expose a local cache session."""
|
||||
raise NotImplementedError(
|
||||
"session is not supported by LanceDB Distributed connections"
|
||||
"session is not supported by LanceDB Enterprise connections"
|
||||
)
|
||||
|
||||
@property
|
||||
def read_consistency_interval(self) -> Optional[timedelta]:
|
||||
"""LanceDB Distributed connections do not expose a read consistency interval."""
|
||||
"""LanceDB Enterprise connections do not expose a read consistency interval."""
|
||||
raise NotImplementedError(
|
||||
"read_consistency_interval is not supported by LanceDB Distributed "
|
||||
"read_consistency_interval is not supported by LanceDB Enterprise "
|
||||
"connections"
|
||||
)
|
||||
|
||||
@@ -664,11 +667,11 @@ class RemoteDBConnection(DBConnection):
|
||||
The embedding functions to store in the table schema and use to
|
||||
generate vectors when creating the table or adding data.
|
||||
storage_options: dict, optional
|
||||
Not supported in LanceDB Distributed. Raises NotImplementedError.
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
data_storage_version: str, optional
|
||||
Not supported in LanceDB Distributed. Raises NotImplementedError.
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
enable_v2_manifest_paths: bool, optional
|
||||
Not supported in LanceDB Distributed. Raises NotImplementedError.
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -742,7 +745,7 @@ class RemoteDBConnection(DBConnection):
|
||||
if value is not None:
|
||||
raise NotImplementedError(
|
||||
f"{option} is not supported for table creation in "
|
||||
"LanceDB Distributed"
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if exist_ok:
|
||||
if mode == "create":
|
||||
@@ -909,8 +912,7 @@ class RemoteDBConnection(DBConnection):
|
||||
def drop_all_tables(self, namespace_path: Optional[List[str]] = None):
|
||||
"""Drop all tables from the database.
|
||||
|
||||
The remote API does not currently support this operation. Use
|
||||
``list_tables()`` and ``drop_table()`` to drop tables individually.
|
||||
Lists the tables in the selected namespace and drops them one at a time.
|
||||
"""
|
||||
LOOP.run(self._conn.drop_all_tables(namespace_path=namespace_path))
|
||||
|
||||
@@ -956,10 +958,17 @@ class RemoteDBConnection(DBConnection):
|
||||
"""
|
||||
return Job(LOOP.run(self._conn.open_job(job_id)))
|
||||
|
||||
@override
|
||||
def list_gpu_classes(self) -> List[GpuClass]:
|
||||
"""List configured Function GPU classes. See
|
||||
[DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes].
|
||||
"""
|
||||
return LOOP.run(self._conn.list_gpu_classes())
|
||||
|
||||
@override
|
||||
def create_function_async(
|
||||
self,
|
||||
definition: UdfDefinition,
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
@@ -1015,11 +1024,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(
|
||||
@@ -1036,6 +1048,76 @@ class RemoteDBConnection(DBConnection):
|
||||
)
|
||||
return dropped, Job(job)
|
||||
|
||||
@override
|
||||
def create_storage_integration(
|
||||
self,
|
||||
name: str,
|
||||
storage_prefix: str,
|
||||
*,
|
||||
aws_role_arn: Optional[str] = None,
|
||||
aws_access_key_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
aws_secret_access_key_secret: Optional[Union[str, SecretReference]] = None,
|
||||
aws_region: Optional[str] = None,
|
||||
storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"] = "S3",
|
||||
azure_storage_account: Optional[str] = None,
|
||||
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,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> StorageIntegrationInfo:
|
||||
return LOOP.run(
|
||||
self._conn.create_storage_integration(
|
||||
name,
|
||||
storage_prefix,
|
||||
aws_role_arn=aws_role_arn,
|
||||
aws_access_key_id_secret=aws_access_key_id_secret,
|
||||
aws_secret_access_key_secret=aws_secret_access_key_secret,
|
||||
aws_region=aws_region,
|
||||
storage_provider=storage_provider,
|
||||
azure_storage_account=azure_storage_account,
|
||||
azure_tenant_id_secret=azure_tenant_id_secret,
|
||||
azure_client_id_secret=azure_client_id_secret,
|
||||
azure_client_secret_secret=azure_client_secret_secret,
|
||||
gcp_credentials_json_secret=gcp_credentials_json_secret,
|
||||
huggingface_token_secret=huggingface_token_secret,
|
||||
namespace_path=namespace_path,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def describe_storage_integration(
|
||||
self, name: str, *, namespace_path: Optional[List[str]] = None
|
||||
) -> StorageIntegrationInfo:
|
||||
return LOOP.run(
|
||||
self._conn.describe_storage_integration(name, namespace_path=namespace_path)
|
||||
)
|
||||
|
||||
@override
|
||||
def list_storage_integrations(
|
||||
self,
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
) -> Listing[str]:
|
||||
return Listing(
|
||||
self._conn.list_storage_integrations(
|
||||
namespace_path=namespace_path,
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def drop_storage_integration(
|
||||
self, name: str, *, namespace_path: Optional[List[str]] = None
|
||||
) -> None:
|
||||
LOOP.run(
|
||||
self._conn.drop_storage_integration(name, namespace_path=namespace_path)
|
||||
)
|
||||
|
||||
@override
|
||||
def create_secret(
|
||||
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
|
||||
@@ -1131,6 +1213,61 @@ class RemoteDBConnection(DBConnection):
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def create_property_graph(
|
||||
self,
|
||||
name: str,
|
||||
nodes: Sequence[NodeTable],
|
||||
edges: Sequence[EdgeTable] = (),
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> PropertyGraph:
|
||||
return PropertyGraph(
|
||||
LOOP.run(
|
||||
self._conn.create_property_graph(
|
||||
name, nodes, edges, namespace_path=namespace_path
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def open_property_graph(
|
||||
self, name: str, *, namespace_path: Optional[List[str]] = None
|
||||
) -> PropertyGraph:
|
||||
return PropertyGraph(
|
||||
LOOP.run(
|
||||
self._conn.open_property_graph(name, namespace_path=namespace_path)
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def drop_property_graph(
|
||||
self, name: str, *, namespace_path: Optional[List[str]] = None
|
||||
) -> None:
|
||||
LOOP.run(self._conn.drop_property_graph(name, namespace_path=namespace_path))
|
||||
|
||||
@override
|
||||
def list_property_graphs(
|
||||
self,
|
||||
*,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
) -> Listing[str]:
|
||||
"""List property graphs.
|
||||
|
||||
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].
|
||||
"""
|
||||
return Listing(
|
||||
self._conn.list_property_graphs(
|
||||
namespace_path=namespace_path,
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
@@ -1179,7 +1316,7 @@ class RemoteDBConnection(DBConnection):
|
||||
default_namespace_path: Optional[List[str]] = None,
|
||||
parameters: Optional[QueryParameters] = None,
|
||||
) -> SqlQuery:
|
||||
"""Start executing SQL through this LanceDB Distributed connection.
|
||||
"""Start executing SQL through this LanceDB Enterprise connection.
|
||||
|
||||
Unqualified tables use this connection's database and the
|
||||
``["public"]`` namespace by default. Fully qualified table names may
|
||||
|
||||
@@ -4,6 +4,14 @@
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from lance_namespace.errors import TableNotFoundError as _NamespaceTableNotFoundError
|
||||
|
||||
from lancedb.exceptions import (
|
||||
ColumnNotFoundError as _ColumnNotFoundError,
|
||||
ReferenceNotFoundError as _ReferenceNotFoundError,
|
||||
SchemaMismatchError as _SchemaMismatchError,
|
||||
)
|
||||
|
||||
|
||||
class LanceDBClientError(RuntimeError):
|
||||
"""An error that occurred in the LanceDB client.
|
||||
@@ -44,6 +52,313 @@ class HttpError(LanceDBClientError):
|
||||
status_code: int
|
||||
The HTTP status code of the response. May be None if the request
|
||||
failed before the response was received.
|
||||
error_code: str
|
||||
A machine-readable error code reported by the server, if available.
|
||||
resource_kind: str
|
||||
The kind of resource reported by the server, if available.
|
||||
resource_name: str
|
||||
The name of the resource reported by the server, if available.
|
||||
namespace_path: tuple[str, ...]
|
||||
The parent namespace path of the resource, if available.
|
||||
is_transport_error: bool
|
||||
Whether the request failed while connecting, sending, or reading, rather
|
||||
than because of an HTTP status or an invalid response payload.
|
||||
job_id: str or None
|
||||
SQL job reported by the server, when available.
|
||||
job_request_id: str or None
|
||||
Original request executed by the isolated SQL worker, when available.
|
||||
"""
|
||||
|
||||
def __new__(
|
||||
cls,
|
||||
message: str,
|
||||
request_id: str,
|
||||
status_code: Optional[int] = None,
|
||||
error_code: Optional[str] = None,
|
||||
resource_kind: Optional[str] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
namespace_path: Optional[tuple[str, ...]] = None,
|
||||
is_transport_error: bool = False,
|
||||
job_id: Optional[str] = None,
|
||||
job_request_id: Optional[str] = None,
|
||||
):
|
||||
if cls is HttpError:
|
||||
mapped_cls = _http_error_class(error_code, resource_kind, status_code)
|
||||
if mapped_cls is not None:
|
||||
cls = mapped_cls
|
||||
return RuntimeError.__new__(cls)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
request_id: str,
|
||||
status_code: Optional[int] = None,
|
||||
error_code: Optional[str] = None,
|
||||
resource_kind: Optional[str] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
namespace_path: Optional[tuple[str, ...]] = None,
|
||||
is_transport_error: bool = False,
|
||||
job_id: Optional[str] = None,
|
||||
job_request_id: Optional[str] = None,
|
||||
):
|
||||
super().__init__(message, request_id, status_code)
|
||||
self.is_transport_error = is_transport_error
|
||||
self.job_id = job_id
|
||||
self.job_request_id = job_request_id
|
||||
self.error_code = error_code
|
||||
self.resource_kind = resource_kind
|
||||
self.resource_name = resource_name
|
||||
self.namespace_path = (
|
||||
tuple(namespace_path) if namespace_path is not None else None
|
||||
)
|
||||
|
||||
def __reduce__(self) -> tuple[type, tuple]:
|
||||
return (
|
||||
self.__class__,
|
||||
(
|
||||
str(self),
|
||||
self.request_id,
|
||||
self.status_code,
|
||||
self.error_code,
|
||||
self.resource_kind,
|
||||
self.resource_name,
|
||||
self.namespace_path,
|
||||
self.is_transport_error,
|
||||
self.job_id,
|
||||
self.job_request_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _http_error_class(
|
||||
error_code: Optional[str], resource_kind: Optional[str], status_code: Optional[int]
|
||||
) -> Optional[type[HttpError]]:
|
||||
if status_code == 400 and error_code is not None:
|
||||
input_class = {
|
||||
"column_not_found": ColumnNotFoundError,
|
||||
"schema_mismatch": SchemaMismatchError,
|
||||
}.get(error_code)
|
||||
if input_class is not None:
|
||||
return input_class
|
||||
if status_code == 404 and error_code is not None:
|
||||
input_class = {
|
||||
"table_not_found": TableNotFoundError,
|
||||
"reference_not_found": ReferenceNotFoundError,
|
||||
}.get(error_code)
|
||||
if input_class is not None:
|
||||
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 {
|
||||
"secret": SecretNotFoundError,
|
||||
"function": FunctionNotFoundError,
|
||||
"namespace": NamespaceNotFoundError,
|
||||
}.get(resource_kind)
|
||||
|
||||
|
||||
class ColumnNotFoundError(HttpError, _ColumnNotFoundError):
|
||||
"""A remote HTTP request named a missing table column."""
|
||||
|
||||
|
||||
class ReferenceNotFoundError(HttpError, _ReferenceNotFoundError):
|
||||
"""A remote HTTP request named a missing branch or table reference."""
|
||||
|
||||
|
||||
class SchemaMismatchError(HttpError, _SchemaMismatchError):
|
||||
"""Input to a remote HTTP request does not match the table schema."""
|
||||
|
||||
|
||||
class SqlError(LanceDBClientError):
|
||||
"""A SQL response with its gRPC status and correlation fields.
|
||||
|
||||
``grpc_code`` is the numeric gRPC code. ``error_code`` is an optional
|
||||
machine-readable classification supplied by the server; message text is
|
||||
never used to choose a subclass. ``job_id`` and ``job_request_id`` are absent
|
||||
unless the server reports an isolated SQL job. ``request_id`` identifies the
|
||||
current request. Older servers still produce SqlError without a category.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> error = SqlError("Column 'missing' was not found", "req-1", 3,
|
||||
... "column_not_found", "job-1", "worker-1")
|
||||
>>> isinstance(error, SqlColumnNotFoundError)
|
||||
True
|
||||
>>> error.job_request_id
|
||||
'worker-1'
|
||||
"""
|
||||
|
||||
def __new__(
|
||||
cls,
|
||||
message: str,
|
||||
request_id: str,
|
||||
grpc_code: int,
|
||||
error_code: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
job_request_id: Optional[str] = None,
|
||||
):
|
||||
if cls is SqlError and error_code is not None:
|
||||
cls = {
|
||||
(3, "column_not_found"): SqlColumnNotFoundError,
|
||||
(3, "schema_mismatch"): SqlSchemaMismatchError,
|
||||
(5, "table_not_found"): SqlTableNotFoundError,
|
||||
(5, "reference_not_found"): SqlReferenceNotFoundError,
|
||||
}.get((grpc_code, error_code), cls)
|
||||
return RuntimeError.__new__(cls)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
request_id: str,
|
||||
grpc_code: int,
|
||||
error_code: Optional[str] = None,
|
||||
job_id: Optional[str] = None,
|
||||
job_request_id: Optional[str] = None,
|
||||
):
|
||||
super().__init__(message, request_id)
|
||||
self.grpc_code = grpc_code
|
||||
self.error_code = error_code
|
||||
self.job_id = job_id
|
||||
self.job_request_id = job_request_id
|
||||
|
||||
def __reduce__(self):
|
||||
return (
|
||||
self.__class__,
|
||||
(
|
||||
str(self),
|
||||
self.request_id,
|
||||
self.grpc_code,
|
||||
self.error_code,
|
||||
self.job_id,
|
||||
self.job_request_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class SqlColumnNotFoundError(SqlError, _ColumnNotFoundError):
|
||||
"""A SQL request named a missing column."""
|
||||
|
||||
|
||||
class SqlReferenceNotFoundError(SqlError, _ReferenceNotFoundError):
|
||||
"""A SQL request named a missing branch or table reference."""
|
||||
|
||||
|
||||
class SqlSchemaMismatchError(SqlError, _SchemaMismatchError):
|
||||
"""SQL input does not match the table schema."""
|
||||
|
||||
|
||||
class SqlTableNotFoundError(SqlError, ValueError, _NamespaceTableNotFoundError):
|
||||
"""A SQL request named a missing table."""
|
||||
|
||||
|
||||
class SecretNotFoundError(HttpError):
|
||||
"""A remote secret was not found."""
|
||||
|
||||
|
||||
class FunctionNotFoundError(HttpError):
|
||||
"""A remote function was not found."""
|
||||
|
||||
|
||||
class NamespaceNotFoundError(HttpError):
|
||||
"""A remote namespace was not found."""
|
||||
|
||||
|
||||
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.
|
||||
|
||||
This is also a ``lance_namespace.errors.TableNotFoundError`` and a
|
||||
``ValueError``, so existing missing-table handlers continue to work.
|
||||
Like [HttpError][lancedb.remote.errors.HttpError], it carries the
|
||||
``request_id`` and ``status_code`` of the failed request.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> error = TableNotFoundError("Table 'missing' was not found", "req-123", 404)
|
||||
>>> isinstance(error, ValueError)
|
||||
True
|
||||
>>> error.request_id
|
||||
'req-123'
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
import deprecation
|
||||
import logging
|
||||
@@ -45,7 +48,11 @@ from lancedb.index import (
|
||||
LabelList,
|
||||
)
|
||||
from lancedb.job import Job
|
||||
from lancedb.functions import FunctionApplication, RefreshColumnResult
|
||||
from lancedb.functions import (
|
||||
FunctionApplication,
|
||||
FunctionRetryPolicy,
|
||||
RefreshColumnResult,
|
||||
)
|
||||
from lancedb.remote.db import LOOP
|
||||
from lancedb.table import IndexConfigType, _maybe_add_fts_error_note
|
||||
import pyarrow as pa
|
||||
@@ -126,7 +133,7 @@ class RemoteTable(Table):
|
||||
def _serialized_connection_state(self) -> str:
|
||||
if self._connection_state is None:
|
||||
raise RuntimeError(
|
||||
"Cannot reopen this LanceDB Distributed table because it does not "
|
||||
"Cannot reopen this LanceDB Enterprise table because it does not "
|
||||
"carry serialized connection state"
|
||||
)
|
||||
if callable(self._connection_state):
|
||||
@@ -206,7 +213,8 @@ class RemoteTable(Table):
|
||||
LOOP.run(self._table.replace_field_metadata(field_name, new_metadata))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"RemoteTable({self.db_name}.{self.name})"
|
||||
identifier = "$".join([*self._namespace_path, self.name])
|
||||
return f"RemoteTable({self.db_name}.{identifier})"
|
||||
|
||||
@property
|
||||
def schema(self) -> pa.Schema:
|
||||
@@ -273,23 +281,23 @@ class RemoteTable(Table):
|
||||
return LOOP.run(self._table.list_versions())
|
||||
|
||||
def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table:
|
||||
"""to_arrow() is not supported in LanceDB Distributed."""
|
||||
"""to_arrow() is not supported in LanceDB Enterprise."""
|
||||
validate_blob_mode(blob_mode)
|
||||
raise NotImplementedError(
|
||||
"to_arrow() is not supported in LanceDB Distributed. "
|
||||
"to_arrow() is not supported in LanceDB Enterprise. "
|
||||
"Use table.search().to_arrow() instead."
|
||||
)
|
||||
|
||||
def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs):
|
||||
"""to_pandas() is not supported in LanceDB Distributed."""
|
||||
"""to_pandas() is not supported in LanceDB Enterprise."""
|
||||
validate_blob_mode(blob_mode)
|
||||
raise NotImplementedError(
|
||||
"to_pandas() is not supported in LanceDB Distributed. "
|
||||
"to_pandas() is not supported in LanceDB Enterprise. "
|
||||
"Use table.search().to_pandas() instead."
|
||||
)
|
||||
|
||||
def to_lance(self, **kwargs) -> "lance.LanceDataset":
|
||||
"""Direct Lance dataset access is not supported in LanceDB Distributed.
|
||||
"""Direct Lance dataset access is not supported in LanceDB Enterprise.
|
||||
|
||||
Use ``table.search().to_arrow()`` to read query results through the server.
|
||||
"""
|
||||
@@ -298,7 +306,7 @@ class RemoteTable(Table):
|
||||
def to_polars(self, batch_size=None) -> "pl.LazyFrame":
|
||||
"""Use ``table.search().to_polars()`` to read query results."""
|
||||
raise NotImplementedError(
|
||||
"to_polars() is not supported in LanceDB Distributed. "
|
||||
"to_polars() is not supported in LanceDB Enterprise. "
|
||||
"Use table.search().to_polars() instead."
|
||||
)
|
||||
|
||||
@@ -331,7 +339,7 @@ class RemoteTable(Table):
|
||||
"""Tokenize a query using the tokenizer configured on an FTS index.
|
||||
|
||||
Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are
|
||||
rebuilt in the client process from index metadata. In LanceDB Distributed,
|
||||
rebuilt in the client process from index metadata. In LanceDB Enterprise,
|
||||
this means the same tokenizer model files must also exist locally
|
||||
(under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the
|
||||
server uses. A mismatch cannot be detected: the returned tokens may
|
||||
@@ -638,7 +646,7 @@ class RemoteTable(Table):
|
||||
|
||||
if accelerator is not None:
|
||||
logging.warning(
|
||||
"GPU accelerator is not supported in LanceDB Distributed "
|
||||
"GPU accelerator is not supported in LanceDB Enterprise "
|
||||
"and will be ignored."
|
||||
)
|
||||
|
||||
@@ -743,7 +751,7 @@ class RemoteTable(Table):
|
||||
capped at the number of CPU cores. Lower this if bulk ingestion is
|
||||
using too much memory.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Not supported in LanceDB Distributed. Setting this raises.
|
||||
Not supported in LanceDB Enterprise. Setting this raises.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -992,6 +1000,11 @@ class RemoteTable(Table):
|
||||
This can be used to update zero to all rows depending on how many
|
||||
rows match the where clause.
|
||||
|
||||
Embeddings are not computed by this method. Updating an embedding source
|
||||
column requires providing all associated vector columns in the same call;
|
||||
otherwise a ValueError is raised. Use `merge_insert` to recompute embeddings
|
||||
automatically.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
where: str or [Expr][lancedb.expr.Expr], optional
|
||||
@@ -1048,20 +1061,20 @@ class RemoteTable(Table):
|
||||
delete_unverified: bool = False,
|
||||
):
|
||||
"""
|
||||
cleanup_old_versions() is a no-op in LanceDB Distributed.
|
||||
cleanup_old_versions() is a no-op in LanceDB Enterprise.
|
||||
"""
|
||||
warnings.warn(
|
||||
"cleanup_old_versions() is a no-op in LanceDB Distributed.",
|
||||
"cleanup_old_versions() is a no-op in LanceDB Enterprise.",
|
||||
stacklevel=2,
|
||||
)
|
||||
pass
|
||||
|
||||
def compact_files(self, *args, **kwargs):
|
||||
"""
|
||||
compact_files() is a no-op in LanceDB Distributed.
|
||||
compact_files() is a no-op in LanceDB Enterprise.
|
||||
"""
|
||||
warnings.warn(
|
||||
"compact_files() is a no-op in LanceDB Distributed.",
|
||||
"compact_files() is a no-op in LanceDB Enterprise.",
|
||||
stacklevel=2,
|
||||
)
|
||||
pass
|
||||
@@ -1074,12 +1087,24 @@ class RemoteTable(Table):
|
||||
retrain: bool = False,
|
||||
compaction_options: Optional[CompactionOptions] = None,
|
||||
):
|
||||
"""optimize() is not supported in LanceDB Distributed."""
|
||||
"""Compact the table's data files via a durable, asynchronous
|
||||
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. 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(
|
||||
cleanup_older_than=cleanup_older_than,
|
||||
delete_unverified=delete_unverified,
|
||||
retrain=retrain,
|
||||
compaction_options=compaction_options,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1088,11 +1113,15 @@ class RemoteTable(Table):
|
||||
|
||||
def add_columns(
|
||||
self,
|
||||
transforms: Dict[str, str | FunctionApplication]
|
||||
transforms: Mapping[str, str | FunctionApplication]
|
||||
| FunctionApplication
|
||||
| pa.Field
|
||||
| List[pa.Field]
|
||||
| pa.Schema
|
||||
| DATA
|
||||
| pa.RecordBatch
|
||||
| pa.RecordBatchReader
|
||||
| pl.DataFrame
|
||||
| None = None,
|
||||
*,
|
||||
computed: Dict[str, str] | None = None,
|
||||
@@ -1108,11 +1137,77 @@ class RemoteTable(Table):
|
||||
)
|
||||
)
|
||||
|
||||
def refresh_column(self, column: str):
|
||||
return LOOP.run(self._table.refresh_column(column))
|
||||
def refresh_column(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
error_policy: Optional[Literal["fail", "skip"]] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
):
|
||||
return LOOP.run(
|
||||
self._table.refresh_column(
|
||||
column,
|
||||
where=where,
|
||||
batch_size=batch_size,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
retry_policy=retry_policy,
|
||||
error_policy=error_policy,
|
||||
max_failed_fraction=max_failed_fraction,
|
||||
max_failed_rows=max_failed_rows,
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
init_timeout_seconds=init_timeout_seconds,
|
||||
num_workers=num_workers,
|
||||
max_executor_processes_per_worker=max_executor_processes_per_worker,
|
||||
)
|
||||
)
|
||||
|
||||
def refresh_column_async(self, column: str) -> Job[RefreshColumnResult]:
|
||||
return Job(LOOP.run(self._table.refresh_column_async(column)))
|
||||
def refresh_column_async(
|
||||
self,
|
||||
column: str,
|
||||
*,
|
||||
where: Optional[str] = None,
|
||||
batch_size: Optional[int] = None,
|
||||
gpu_class: Optional[str] = None,
|
||||
gpu_count: Optional[int] = None,
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None,
|
||||
error_policy: Optional[Literal["fail", "skip"]] = None,
|
||||
max_failed_fraction: Optional[float] = None,
|
||||
max_failed_rows: Optional[int] = None,
|
||||
row_timeout_seconds: Optional[float] = None,
|
||||
init_timeout_seconds: Optional[float] = None,
|
||||
num_workers: Optional[int] = None,
|
||||
max_executor_processes_per_worker: Optional[int] = None,
|
||||
) -> Job[RefreshColumnResult]:
|
||||
return Job(
|
||||
LOOP.run(
|
||||
self._table.refresh_column_async(
|
||||
column,
|
||||
where=where,
|
||||
batch_size=batch_size,
|
||||
gpu_class=gpu_class,
|
||||
gpu_count=gpu_count,
|
||||
retry_policy=retry_policy,
|
||||
error_policy=error_policy,
|
||||
max_failed_fraction=max_failed_fraction,
|
||||
max_failed_rows=max_failed_rows,
|
||||
row_timeout_seconds=row_timeout_seconds,
|
||||
init_timeout_seconds=init_timeout_seconds,
|
||||
num_workers=num_workers,
|
||||
max_executor_processes_per_worker=max_executor_processes_per_worker,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def function_errors(
|
||||
self,
|
||||
@@ -1153,6 +1248,18 @@ class RemoteTable(Table):
|
||||
"""Read the installed RTEWriteSpec, or ``None``."""
|
||||
return LOOP.run(self._table.get_rte_spec())
|
||||
|
||||
def get_table_overrides(self) -> dict[str, Any]:
|
||||
"""Read Enterprise table overrides for this 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."""
|
||||
return LOOP.run(self._table.update_table_overrides(**overrides))
|
||||
|
||||
def reset_table_overrides(self) -> dict[str, Any]:
|
||||
"""Clear Enterprise table overrides for this table."""
|
||||
return LOOP.run(self._table.reset_table_overrides())
|
||||
|
||||
# WAL-PK-FUSION: delete both hooks.
|
||||
def _hybrid_pk_fusion_learned(self) -> bool:
|
||||
# `self._table` is the async table, which owns the Rust handle.
|
||||
@@ -1184,7 +1291,7 @@ class RemoteTable(Table):
|
||||
)
|
||||
|
||||
def close_rte_writers(self) -> None:
|
||||
"""No-op in LanceDB Distributed (no local shard writers)."""
|
||||
"""No-op in LanceDB Enterprise (no local shard writers)."""
|
||||
return LOOP.run(self._table.close_rte_writers())
|
||||
|
||||
@_deprecated_keyword("index_name", "name")
|
||||
@@ -1213,7 +1320,7 @@ class RemoteTable(Table):
|
||||
|
||||
This is a hint to the database that the given columns will be accessed
|
||||
in the future and the database should prefetch the data if possible.
|
||||
Currently only supported in LanceDB Distributed.
|
||||
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.
|
||||
@@ -1242,7 +1349,7 @@ class RemoteTable(Table):
|
||||
def uri(self) -> str:
|
||||
"""The table URI (storage location).
|
||||
|
||||
In LanceDB Distributed, this fetches the location from the server via describe.
|
||||
In LanceDB Enterprise, this fetches the location from the server via describe.
|
||||
"""
|
||||
return LOOP.run(self._table.uri())
|
||||
|
||||
|
||||
@@ -189,6 +189,8 @@ class Reranker(ABC):
|
||||
vector_results = (
|
||||
[vector_results] if not isinstance(vector_results, list) else vector_results
|
||||
)
|
||||
if not vector_results:
|
||||
raise ValueError("vector_results must not be empty")
|
||||
|
||||
# Make sure all elements are of the same type
|
||||
if not all(isinstance(v, type(vector_results[0])) for v in vector_results):
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
|
||||
from collections import defaultdict
|
||||
from numpy import nan
|
||||
import pyarrow as pa
|
||||
|
||||
from .base import Reranker
|
||||
@@ -66,7 +65,7 @@ class LinearCombinationReranker(Reranker):
|
||||
elif self.score == "all":
|
||||
results = results.append_column(
|
||||
"_distance",
|
||||
pa.array([nan] * len(fts_results), type=pa.float32()),
|
||||
pa.nulls(len(fts_results), type=pa.float32()),
|
||||
)
|
||||
return results
|
||||
|
||||
@@ -87,7 +86,7 @@ class LinearCombinationReranker(Reranker):
|
||||
elif self.score == "all":
|
||||
results = results.append_column(
|
||||
"_score",
|
||||
pa.array([nan] * len(vector_results), type=pa.float32()),
|
||||
pa.nulls(len(vector_results), type=pa.float32()),
|
||||
)
|
||||
return results
|
||||
results = defaultdict()
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Handles to SQL queries running on a LanceDB Distributed database."""
|
||||
"""Handles to SQL queries running on a LanceDB Enterprise database."""
|
||||
|
||||
from typing import Any, Mapping, Optional, Sequence, Union
|
||||
from uuid import UUID
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Database-owned storage integrations and references to credential Secrets."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, Literal, Optional
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SecretReference:
|
||||
"""A credential Secret, optionally qualified by database and namespace."""
|
||||
|
||||
name: str
|
||||
database: Optional[str] = None
|
||||
namespace_path: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StorageIntegrationInfo:
|
||||
"""Registered cloud configuration and setup instructions.
|
||||
|
||||
``configuration_instructions`` is a single sentence of setup guidance for
|
||||
display; its wording may change. Use the structured identity and policy fields
|
||||
instead of parsing that text. Creating this object does not verify AWS access
|
||||
or configure a storage operation to use it. Static-key authentication stores
|
||||
only Secret references. No field contains AWS credentials.
|
||||
"""
|
||||
|
||||
name: str
|
||||
database: str
|
||||
namespace_path: list[str]
|
||||
storage_provider: Literal["S3", "AZURE", "GCP", "HUGGINGFACE"]
|
||||
storage_prefix: str
|
||||
aws_region: Optional[str]
|
||||
aws_account_id: str
|
||||
aws_iam_principal_arn: str
|
||||
aws_external_id: str
|
||||
created_at_millis: int
|
||||
access_verified: bool
|
||||
trust_policy: Optional[Dict[str, Any]]
|
||||
permissions_policy: Optional[Dict[str, Any]]
|
||||
configuration_instructions: str
|
||||
aws_role_arn: Optional[str] = None
|
||||
aws_access_key_id_secret: Optional[SecretReference] = None
|
||||
aws_secret_access_key_secret: Optional[SecretReference] = None
|
||||
azure_storage_account: Optional[str] = None
|
||||
azure_tenant_id_secret: Optional[SecretReference] = None
|
||||
azure_client_id_secret: Optional[SecretReference] = None
|
||||
azure_client_secret_secret: Optional[SecretReference] = None
|
||||
gcp_credentials_json_secret: Optional[SecretReference] = None
|
||||
huggingface_token_secret: Optional[SecretReference] = None
|
||||
|
||||
def __post_init__(self):
|
||||
for field in (
|
||||
"aws_access_key_id_secret",
|
||||
"aws_secret_access_key_secret",
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
"gcp_credentials_json_secret",
|
||||
"huggingface_token_secret",
|
||||
):
|
||||
value = getattr(self, field)
|
||||
if isinstance(value, dict):
|
||||
object.__setattr__(self, field, SecretReference(**value))
|
||||
@@ -13,7 +13,7 @@ Provides StreamingDataset, a PyTorch IterableDataset that guarantees:
|
||||
distributed topology changes between runs.
|
||||
|
||||
Transform failures on bad rows (e.g. nulls or NaNs from incomplete data) can
|
||||
be tolerated with ``on_transform_error="skip"``; see the parameter
|
||||
be tolerated with ``on_transform_error="skip"`` or ``"fill"``; see the parameter
|
||||
documentation on StreamingDataset for how this interacts with the guarantees
|
||||
above.
|
||||
"""
|
||||
@@ -30,7 +30,7 @@ import warnings
|
||||
from collections import deque
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from copy import deepcopy
|
||||
from multiprocessing import RawArray
|
||||
from multiprocessing import RawArray, get_context
|
||||
from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -57,6 +57,7 @@ _EPOCH_PRIME = 100003
|
||||
|
||||
DEFAULT_READ_BATCH_SIZE = 64
|
||||
DEFAULT_PREFETCH_BATCHES = 4
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
class _WorkerSample(NamedTuple):
|
||||
@@ -350,6 +351,10 @@ class StreamingDataset(IterableDataset):
|
||||
- ``"skip"``: the failing rows are dropped and iteration continues.
|
||||
- ``"warn"``: like ``"skip"``, but a warning is logged for each
|
||||
failing batch.
|
||||
- ``"fill"``: replace each failing row with ``fill_value`` or the
|
||||
result of ``repair(exc, row_batch)``. Exactly one of these must be
|
||||
provided. Filled rows retain their original positions, so split
|
||||
lengths, elastic determinism, and checkpoint offsets are preserved.
|
||||
- a callable ``handler(exc) -> bool``: called with the exception;
|
||||
return ``True`` to skip the failing rows or ``False`` to re-raise.
|
||||
Useful to skip only expected error types (compatible with
|
||||
@@ -357,9 +362,9 @@ class StreamingDataset(IterableDataset):
|
||||
|
||||
When a batch fails, the transform is re-invoked on each single-row
|
||||
slice of the batch so that only the rows that actually fail are
|
||||
dropped. Transforms should therefore be deterministic and accept
|
||||
batches of any size (including one row). Skipped rows are counted in
|
||||
``rows_skipped``.
|
||||
skipped or filled. Transforms should therefore be deterministic and
|
||||
accept batches of any size (including one row). Skipped and filled
|
||||
rows are counted in ``rows_skipped`` and ``rows_filled`` respectively.
|
||||
|
||||
Skipping weakens the elastic-determinism guarantee at the end of the
|
||||
epoch: splits that lose more rows than others run dry earlier, and
|
||||
@@ -372,8 +377,9 @@ class StreamingDataset(IterableDataset):
|
||||
but synchronous distributed training (e.g. ranks that call
|
||||
``all_reduce`` every step) can hang or deadlock if one rank's
|
||||
iterator is exhausted while others are still stepping; callers doing
|
||||
synchronous multi-rank training with ``on_transform_error != "raise"``
|
||||
are responsible for their own cross-rank stopping mechanism (e.g.
|
||||
synchronous multi-rank training with ``on_transform_error="skip"`` or
|
||||
``"warn"`` (or a skipping callable) are responsible for their own
|
||||
cross-rank stopping mechanism (e.g.
|
||||
broadcasting a stop signal on ``StopIteration``). The final few
|
||||
global steps can also differ across topologies (bounded by the skew
|
||||
in bad-row counts across splits). The sequence of samples yielded
|
||||
@@ -385,6 +391,18 @@ class StreamingDataset(IterableDataset):
|
||||
Prefer the ``filter`` parameter when bad rows can be expressed as a
|
||||
SQL predicate (e.g. ``"col IS NOT NULL"``) — filtering happens before
|
||||
splits are built, so every guarantee is fully preserved.
|
||||
fill_value:
|
||||
Constant output row used with ``on_transform_error="fill"``. A copy
|
||||
is made for each failed row so mutable placeholders are independent.
|
||||
For example, ``fill_value={"vector": [0.0, 0.0]}``. Pass exactly one
|
||||
of ``fill_value`` or ``repair`` in fill mode.
|
||||
repair:
|
||||
Optional function ``repair(exc, row_batch) -> row`` used with
|
||||
``on_transform_error="fill"``. ``row_batch`` is a one-row
|
||||
``pyarrow.RecordBatch``. The returned value replaces that row's
|
||||
transformed output. Replacements should have the same structure as
|
||||
successful transform outputs. The repair must be deterministic for
|
||||
reproducible checkpoints and elastic steps.
|
||||
transform_queue_depth:
|
||||
Number of transform-result batches to buffer per split in the
|
||||
post-transform queue before backpressure is applied to the transform
|
||||
@@ -438,6 +456,8 @@ class StreamingDataset(IterableDataset):
|
||||
pad_id: Optional[int] = None,
|
||||
blocks_per_epoch: Optional[Union[int, Literal["auto"]]] = None,
|
||||
on_transform_error: Union[str, Callable[[Exception], bool]] = "raise",
|
||||
fill_value: Any = _UNSET,
|
||||
repair: Optional[Callable[[Exception, pa.RecordBatch], Any]] = None,
|
||||
transform_queue_depth: Optional[int] = None,
|
||||
connection_factory: Optional[Callable[[str], Any]] = None,
|
||||
worker_info_override=None,
|
||||
@@ -513,13 +533,20 @@ class StreamingDataset(IterableDataset):
|
||||
)
|
||||
elif blocks_per_epoch is not None:
|
||||
raise ValueError("blocks_per_epoch requires pack_sequences")
|
||||
if on_transform_error not in ("raise", "skip", "warn") and not callable(
|
||||
if on_transform_error not in ("raise", "skip", "warn", "fill") and not callable(
|
||||
on_transform_error
|
||||
):
|
||||
raise ValueError(
|
||||
"on_transform_error must be 'raise', 'skip', 'warn', or a "
|
||||
"on_transform_error must be 'raise', 'skip', 'warn', 'fill', or a "
|
||||
f"callable, got {on_transform_error!r}"
|
||||
)
|
||||
if on_transform_error == "fill":
|
||||
if (fill_value is _UNSET) == (repair is None):
|
||||
raise ValueError(
|
||||
"fill mode requires exactly one of fill_value or repair"
|
||||
)
|
||||
elif fill_value is not _UNSET or repair is not None:
|
||||
raise ValueError("fill_value and repair require on_transform_error='fill'")
|
||||
if transform_queue_depth is not None and transform_queue_depth <= 0:
|
||||
raise ValueError("transform_queue_depth must be greater than 0")
|
||||
|
||||
@@ -542,6 +569,8 @@ class StreamingDataset(IterableDataset):
|
||||
self._pad_id = pad_id
|
||||
self._blocks_per_epoch = blocks_per_epoch
|
||||
self._on_transform_error = on_transform_error
|
||||
self._fill_value = None if fill_value is _UNSET else fill_value
|
||||
self._repair = repair
|
||||
self._transform_queue_depth = transform_queue_depth
|
||||
self._connection_factory = connection_factory
|
||||
self._worker_info_override = worker_info_override
|
||||
@@ -568,6 +597,9 @@ class StreamingDataset(IterableDataset):
|
||||
# bytes_loaded, fetch_time_us, transform_time_us,
|
||||
# rows_skipped]
|
||||
self._worker_stats: RawArray = RawArray(ctypes.c_int64, 8)
|
||||
# A locked shared counter keeps fills from separate DataLoader workers
|
||||
# from overwriting one another's totals.
|
||||
self._filled_count = get_context("spawn").Value(ctypes.c_int64, 0)
|
||||
|
||||
# A standard multi-process DataLoader cannot report which prefetched
|
||||
# batches were actually returned to its consumer. Workers set this
|
||||
@@ -951,12 +983,12 @@ class StreamingDataset(IterableDataset):
|
||||
|
||||
on_error = self._on_transform_error
|
||||
|
||||
def _should_skip(exc: Exception) -> bool:
|
||||
def _should_continue(exc: Exception) -> bool:
|
||||
if on_error == "raise":
|
||||
return False
|
||||
if callable(on_error):
|
||||
return bool(on_error(exc))
|
||||
return True # "skip" or "warn"
|
||||
return True # "skip", "warn", or "fill"
|
||||
|
||||
def _check_row_count(rows: list, num_rows: int) -> None:
|
||||
if len(rows) != num_rows:
|
||||
@@ -968,16 +1000,27 @@ class StreamingDataset(IterableDataset):
|
||||
)
|
||||
|
||||
def _transform_isolated(abs_start, batch, batch_exc):
|
||||
"""Re-run the transform on single-row slices, dropping failures."""
|
||||
"""Re-run the transform on single-row slices to isolate failures."""
|
||||
out = []
|
||||
skipped = 0
|
||||
filled = 0
|
||||
first_exc = None
|
||||
for j in range(batch.num_rows):
|
||||
row_batch = batch.slice(j, 1)
|
||||
try:
|
||||
rows = list(final_transform(batch.slice(j, 1)))
|
||||
rows = list(final_transform(row_batch))
|
||||
except Exception as exc:
|
||||
if not _should_skip(exc):
|
||||
if not _should_continue(exc):
|
||||
raise
|
||||
if on_error == "fill":
|
||||
row = (
|
||||
self._repair(exc, row_batch)
|
||||
if self._repair is not None
|
||||
else deepcopy(self._fill_value)
|
||||
)
|
||||
out.append((abs_start + j, row))
|
||||
filled += 1
|
||||
continue
|
||||
skipped += 1
|
||||
if first_exc is None:
|
||||
first_exc = exc
|
||||
@@ -985,6 +1028,9 @@ class StreamingDataset(IterableDataset):
|
||||
_check_row_count(rows, 1)
|
||||
out.append((abs_start + j, rows[0]))
|
||||
self._rows_skipped += skipped
|
||||
if filled:
|
||||
with self._filled_count.get_lock():
|
||||
self._filled_count.value += filled
|
||||
if skipped and on_error == "warn":
|
||||
logger.warning(
|
||||
"Skipped %d of %d rows whose transform failed (first error: %r)",
|
||||
@@ -999,7 +1045,7 @@ class StreamingDataset(IterableDataset):
|
||||
try:
|
||||
rows = list(final_transform(batch))
|
||||
except Exception as exc:
|
||||
if not _should_skip(exc):
|
||||
if not _should_continue(exc):
|
||||
raise
|
||||
return _transform_isolated(abs_start, batch, exc)
|
||||
_check_row_count(rows, batch.num_rows)
|
||||
@@ -1370,6 +1416,15 @@ class StreamingDataset(IterableDataset):
|
||||
return self._rows_skipped
|
||||
return int(self._worker_stats[7])
|
||||
|
||||
@property
|
||||
def rows_filled(self) -> int:
|
||||
"""Number of failed transform rows replaced by fill mode.
|
||||
|
||||
Accumulates across iterations of the same dataset instance and is
|
||||
never reset automatically.
|
||||
"""
|
||||
return int(self._filled_count.value)
|
||||
|
||||
@property
|
||||
def consumed_rows(self) -> int:
|
||||
"""Number of rows already yielded to the caller across all splits.
|
||||
|
||||
+820
-78
File diff suppressed because it is too large
Load Diff
@@ -51,6 +51,7 @@ IndexType = Literal[
|
||||
"BTREE",
|
||||
"BITMAP",
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
"IVF_RQ",
|
||||
]
|
||||
|
||||
|
||||
@@ -7,12 +7,9 @@ import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
|
||||
import lance
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.compute as pc
|
||||
import pytest
|
||||
from lance.blob import Blob, BlobType as LanceBlobType
|
||||
|
||||
import lancedb
|
||||
from lancedb import schema as schema_module
|
||||
@@ -114,6 +111,7 @@ def _assert_fetch_apis_reject_missing_row_ids(table, row_ids):
|
||||
|
||||
|
||||
def test_blob_factory_declares_v2_field():
|
||||
LanceBlobType = pytest.importorskip("lance.blob").BlobType
|
||||
field = lancedb.blob("image")
|
||||
assert isinstance(field.type, pa.ExtensionType)
|
||||
assert field.type.extension_name == "lance.blob.v2"
|
||||
@@ -163,6 +161,8 @@ def test_blob_without_thresholds_has_no_threshold_metadata():
|
||||
],
|
||||
)
|
||||
def test_blob_thresholds_match_pylance(monkeypatch, nullable, thresholds):
|
||||
lance = pytest.importorskip("lance")
|
||||
LanceBlobType = pytest.importorskip("lance.blob").BlobType
|
||||
expected = lance.blob_field("payload", nullable=nullable, **thresholds)
|
||||
actual = lancedb.blob("payload", nullable=nullable, **thresholds)
|
||||
assert type(actual.type) is LanceBlobType
|
||||
@@ -304,6 +304,7 @@ def test_local_schema_restores_blob_extensions(tmp_path, use_async, with_pylance
|
||||
|
||||
|
||||
def test_blob_resolves_pylance_type_without_eager_import():
|
||||
pytest.importorskip("lance.blob")
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
import sys
|
||||
@@ -375,6 +376,7 @@ def test_blob_fallback_fails_if_name_already_registered():
|
||||
|
||||
|
||||
def test_blob_type_rejects_competing_registration_with_pylance():
|
||||
pytest.importorskip("lance.blob")
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
import pyarrow as pa
|
||||
@@ -515,6 +517,7 @@ def _nested_blob_table(db, name):
|
||||
|
||||
|
||||
def test_nested_blob_to_pandas_bytes(tmp_path):
|
||||
pytest.importorskip("pandas")
|
||||
table = _nested_blob_table(lancedb.connect(tmp_path), "nested_pandas_bytes")
|
||||
expected = [
|
||||
{"name": "first", "blob": b"hello"},
|
||||
@@ -538,6 +541,9 @@ def test_nested_blob_to_pandas_bytes(tmp_path):
|
||||
assert table.search().select({"b": "info.blob"}).to_pandas(blob_mode="bytes")[
|
||||
"b"
|
||||
].tolist() == [b"hello", None, None]
|
||||
assert table.search().select([]).to_pandas(blob_mode="bytes")["info"].tolist() == (
|
||||
table.search().select([]).to_arrow(blob_mode="bytes")["info"].to_pylist()
|
||||
)
|
||||
|
||||
|
||||
def test_to_arrow_and_to_list_blob_mode(tmp_path):
|
||||
@@ -573,9 +579,6 @@ def test_to_arrow_and_to_list_blob_mode(tmp_path):
|
||||
assert [
|
||||
row["info"] for row in table.search().select([]).to_list(blob_mode="bytes")
|
||||
] == expected
|
||||
assert table.search().select([]).to_pandas(blob_mode="bytes")["info"].tolist() == (
|
||||
table.search().select([]).to_arrow(blob_mode="bytes")["info"].to_pylist()
|
||||
)
|
||||
assert "_rowid" not in table.search().select([]).to_arrow().column_names
|
||||
# A flat non-blob column named like the nested blob path keeps its values.
|
||||
shadowed = table.search().select({"info": "info", "info.blob": "id"})
|
||||
@@ -694,6 +697,7 @@ def test_vector_query_to_arrow_blob_mode_bytes(tmp_path):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nested_blob_to_pandas_bytes_async(tmp_path):
|
||||
pytest.importorskip("pandas")
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
schema = pa.schema(
|
||||
[
|
||||
@@ -809,6 +813,7 @@ def test_blob_query_explicit_row_id_opt_in():
|
||||
|
||||
|
||||
def test_table_to_pandas_descriptions_mode_omits_row_id():
|
||||
pytest.importorskip("pandas")
|
||||
table = _blob_table("descriptions_no_leak", [{"id": 1, "image": b"x"}])
|
||||
df = table.to_pandas(blob_mode="descriptions")
|
||||
descriptor = df["image"].iloc[0]
|
||||
@@ -818,6 +823,7 @@ def test_table_to_pandas_descriptions_mode_omits_row_id():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_table_to_pandas_descriptions_mode_omits_row_id():
|
||||
pytest.importorskip("pandas")
|
||||
db = await lancedb.connect_async("memory:///")
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
table = await db.create_table("descriptions_no_leak_async", schema=schema)
|
||||
@@ -983,6 +989,7 @@ def test_to_batches_validates_blob_mode():
|
||||
|
||||
|
||||
def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode():
|
||||
pytest.importorskip("pandas")
|
||||
from lancedb.query import LanceEmptyQueryBuilder
|
||||
|
||||
class ToArrowWithoutBlobMode(LanceEmptyQueryBuilder):
|
||||
@@ -1000,6 +1007,7 @@ def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode():
|
||||
|
||||
|
||||
def test_take_queries_honor_blob_mode():
|
||||
pytest.importorskip("pandas")
|
||||
table = _blob_table(
|
||||
"take_blob_mode", [{"id": 1, "image": b"one"}, {"id": 2, "image": b"two"}]
|
||||
)
|
||||
@@ -1449,6 +1457,7 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path):
|
||||
|
||||
|
||||
def test_merge_insert_blob_array_into_reopened_table(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
table = db.create_table("images", schema=schema)
|
||||
@@ -1624,6 +1633,8 @@ def test_row_addressable_paths_exclude_list_children():
|
||||
|
||||
|
||||
def test_merge_insert_writes_pylance_blob_array():
|
||||
lance = pytest.importorskip("lance")
|
||||
LanceBlobType = pytest.importorskip("lance.blob").BlobType
|
||||
table = _blob_table("merge_pylance", [{"id": 1, "image": b"before"}])
|
||||
image = lance.blob_array([b"updated", b"inserted"])
|
||||
assert type(image.type) is LanceBlobType
|
||||
@@ -2085,6 +2096,7 @@ def test_fetch_legacy_v1_blobs():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_fetch_legacy_v1_blobs(tmp_path):
|
||||
lance = pytest.importorskip("lance")
|
||||
table = _legacy_v1_table("legacy_async_source")
|
||||
# Open a dataset written by Lance independently of the LanceDB connection.
|
||||
lance.write_dataset(
|
||||
@@ -2193,6 +2205,7 @@ def _blob_query_shape(table, shape):
|
||||
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
|
||||
@pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"])
|
||||
def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id):
|
||||
pytest.importorskip("pandas")
|
||||
table = _hybrid_blob_table(lancedb.connect("memory:///"))
|
||||
query = _blob_query_shape(table, shape).select(["id", "image"]).limit(2)
|
||||
if with_row_id is not None:
|
||||
@@ -2218,6 +2231,7 @@ def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id):
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"])
|
||||
async def test_async_blob_bytes_for_every_query_shape(shape):
|
||||
pytest.importorskip("pandas")
|
||||
db = await lancedb.connect_async("memory:///")
|
||||
table = await _hybrid_blob_table_async(db)
|
||||
query = table.query()
|
||||
@@ -2750,13 +2764,15 @@ def test_add_external_blob_range_matches_storage_schema(
|
||||
table = db.create_table(
|
||||
"ranges", schema=pa.schema([pa.field("id", pa.int64()), field])
|
||||
)
|
||||
value = (
|
||||
Blob.from_uri(blob_path.as_uri(), position=position, size=6)
|
||||
if as_blob
|
||||
else {"uri": blob_path.as_uri(), "position": position, "size": 6}
|
||||
)
|
||||
if as_blob:
|
||||
Blob = pytest.importorskip("lance.blob").Blob
|
||||
value = Blob.from_uri(blob_path.as_uri(), position=position, size=6)
|
||||
else:
|
||||
value = {"uri": blob_path.as_uri(), "position": position, "size": 6}
|
||||
rows = [{"id": 1, "image": b"inline"}, {"id": 2, "image": value}]
|
||||
data = pd.DataFrame(rows) if as_pandas else rows
|
||||
data = rows
|
||||
if as_pandas:
|
||||
data = pytest.importorskip("pandas").DataFrame(rows)
|
||||
|
||||
if minimal_schema:
|
||||
with pytest.raises(ValueError, match="Blob column 'image'.*storage schema"):
|
||||
@@ -2775,6 +2791,7 @@ def test_add_external_blob_range_matches_storage_schema(
|
||||
def test_add_minimal_blob_schema_preserves_whole_file_and_inline_values(
|
||||
tmp_path, as_pandas
|
||||
):
|
||||
Blob = pytest.importorskip("lance.blob").Blob
|
||||
payload = b"whole-file"
|
||||
blob_path = tmp_path / "payload.bin"
|
||||
blob_path.write_bytes(payload)
|
||||
@@ -2797,10 +2814,10 @@ def test_add_minimal_blob_schema_preserves_whole_file_and_inline_values(
|
||||
{"uri": uri, "position": None, "size": None},
|
||||
]
|
||||
rows = [{"id": i, "image": value} for i, value in enumerate(values)]
|
||||
table.add(
|
||||
pd.DataFrame(rows) if as_pandas else rows,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
data = rows
|
||||
if as_pandas:
|
||||
data = pytest.importorskip("pandas").DataFrame(rows)
|
||||
table.add(data, allow_external_blob_outside_bases=True)
|
||||
|
||||
by_id = _row_ids_by_id(table)
|
||||
assert table.fetch_blobs(
|
||||
@@ -2828,10 +2845,10 @@ def test_add_bytes_and_uri_in_one_batch_preserves_external_uri(tmp_path, as_pand
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
table = db.create_table("mixed", schema=schema)
|
||||
|
||||
table.add(
|
||||
pd.DataFrame(rows) if as_pandas else rows,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
data = rows
|
||||
if as_pandas:
|
||||
data = pytest.importorskip("pandas").DataFrame(rows)
|
||||
table.add(data, allow_external_blob_outside_bases=True)
|
||||
|
||||
by_id = _row_ids_by_id(table)
|
||||
assert table.fetch_blobs("image", [by_id[1], by_id[2]]).to_pylist() == [
|
||||
@@ -2842,6 +2859,7 @@ def test_add_bytes_and_uri_in_one_batch_preserves_external_uri(tmp_path, as_pand
|
||||
|
||||
@pytest.mark.parametrize("as_pandas", [False, True])
|
||||
def test_add_mixed_python_blob_values_preserves_external_uris(tmp_path, as_pandas):
|
||||
Blob = pytest.importorskip("lance.blob").Blob
|
||||
payload = b"external-payload"
|
||||
blob_path = tmp_path / "payload.bin"
|
||||
blob_path.write_bytes(payload)
|
||||
@@ -2859,10 +2877,10 @@ def test_add_mixed_python_blob_values_preserves_external_uris(tmp_path, as_panda
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
table = db.create_table("mixed", schema=schema)
|
||||
|
||||
table.add(
|
||||
pd.DataFrame(rows) if as_pandas else rows,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
data = rows
|
||||
if as_pandas:
|
||||
data = pytest.importorskip("pandas").DataFrame(rows)
|
||||
table.add(data, allow_external_blob_outside_bases=True)
|
||||
|
||||
by_id = _row_ids_by_id(table)
|
||||
assert table.fetch_blobs("image", [by_id[i] for i in range(1, 8)]).to_pylist() == [
|
||||
@@ -2886,18 +2904,22 @@ def test_merge_insert_mixed_python_blobs_validates_external_uri(tmp_path, as_pan
|
||||
{"id": 2, "image": blob_path.as_uri()},
|
||||
]
|
||||
|
||||
data = rows
|
||||
if as_pandas:
|
||||
data = pytest.importorskip("pandas").DataFrame(rows)
|
||||
with pytest.raises(ValueError, match="outside registered external bases"):
|
||||
(
|
||||
table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(pd.DataFrame(rows) if as_pandas else rows)
|
||||
.execute(data)
|
||||
)
|
||||
assert table.count_rows() == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("as_pandas", [False, True])
|
||||
def test_merge_insert_python_blob_dicts_and_objects(as_pandas):
|
||||
Blob = pytest.importorskip("lance.blob").Blob
|
||||
table = _blob_table("merge_python_blobs", [{"id": 1, "image": b"before"}])
|
||||
rows = [
|
||||
{"id": 1, "image": b"updated"},
|
||||
@@ -2905,11 +2927,14 @@ def test_merge_insert_python_blob_dicts_and_objects(as_pandas):
|
||||
{"id": 3, "image": Blob.from_bytes(b"from-blob")},
|
||||
]
|
||||
|
||||
data = rows
|
||||
if as_pandas:
|
||||
data = pytest.importorskip("pandas").DataFrame(rows)
|
||||
result = (
|
||||
table.merge_insert("id")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(pd.DataFrame(rows) if as_pandas else rows)
|
||||
.execute(data)
|
||||
)
|
||||
|
||||
assert result.num_updated_rows == 1
|
||||
@@ -2923,6 +2948,7 @@ def test_merge_insert_python_blob_dicts_and_objects(as_pandas):
|
||||
|
||||
|
||||
def test_create_table_with_python_blob_dict_and_object():
|
||||
Blob = pytest.importorskip("lance.blob").Blob
|
||||
db = lancedb.connect("memory:///")
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
table = db.create_table(
|
||||
@@ -2979,6 +3005,7 @@ def _openable_descriptors(table, *, by_address):
|
||||
def test_open_blob_files_preserve_snapshot_order_nulls_and_empty_values(
|
||||
tmp_path, by_address
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
db = lancedb.connect(str(tmp_path))
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
|
||||
table = db.create_table("videos", schema=schema)
|
||||
@@ -3049,6 +3076,7 @@ def test_open_blob_files_does_not_open_ahead(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
db = lancedb.connect(str(tmp_path))
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
|
||||
@@ -10,6 +10,8 @@ import pytest
|
||||
|
||||
@pytest.mark.parametrize("with_pylance", [False, True])
|
||||
def test_blob_array(with_pylance):
|
||||
if with_pylance:
|
||||
pytest.importorskip("lance")
|
||||
# Use fresh processes so each extension class can own Arrow's registry.
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
|
||||
@@ -11,6 +11,8 @@ 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 = """\
|
||||
import importlib.abc
|
||||
import sys
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import lancedb
|
||||
from lancedb._lancedb import __version__ as _core_version, _append_doc_url, _doc_url
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.job import AsyncJob, Job
|
||||
import pytest
|
||||
|
||||
|
||||
def test_python_sdk_utm_content_and_doc_links(tmp_path):
|
||||
compaction_url = _doc_url("compaction")
|
||||
expected_content = f"utm_content=python-{_core_version}"
|
||||
assert (
|
||||
compaction_url
|
||||
== f"https://docs.lancedb.com/performance?utm_source=lancedb_sdk&utm_medium=warning&utm_campaign=compaction&{expected_content}#compaction-and-cleanup"
|
||||
)
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
with pytest.raises(NotImplementedError) as sql_exc:
|
||||
db.execute_query("SELECT 1")
|
||||
assert _doc_url("sql") in str(sql_exc.value)
|
||||
|
||||
with pytest.raises(NotImplementedError) as gpu_exc:
|
||||
db.list_gpu_classes()
|
||||
assert _doc_url("gpu_classes") in str(gpu_exc.value)
|
||||
|
||||
with pytest.raises(NotImplementedError) as job_exc:
|
||||
db.open_job("job-1")
|
||||
assert _doc_url("jobs") in str(job_exc.value)
|
||||
|
||||
with pytest.raises(NotImplementedError) as secret_exc:
|
||||
db.create_secret("s", "v")
|
||||
assert _doc_url("secrets") in str(secret_exc.value)
|
||||
|
||||
with pytest.raises(NotImplementedError) as view_exc:
|
||||
db.create_view("v", "SELECT 1")
|
||||
assert _doc_url("views") in str(view_exc.value)
|
||||
|
||||
with pytest.raises(NotImplementedError) as mv_exc:
|
||||
DBConnection.open_materialized_view(db, "mv")
|
||||
assert _doc_url("materialized_views") in str(mv_exc.value)
|
||||
|
||||
with pytest.raises(NotImplementedError) as create_mv_exc:
|
||||
DBConnection.create_materialized_view(db, "mv", "SELECT 1")
|
||||
assert _doc_url("materialized_views") in str(create_mv_exc.value)
|
||||
|
||||
local_job = Job(AsyncJob(None))
|
||||
with pytest.raises(NotImplementedError) as events_exc:
|
||||
local_job.events()
|
||||
assert _doc_url("jobs") in str(events_exc.value)
|
||||
|
||||
appended = _append_doc_url("Something failed.", "sql")
|
||||
assert appended.endswith(f"See {_doc_url('sql')}")
|
||||
@@ -10,7 +10,7 @@ import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb import LanceDBConnection
|
||||
from lancedb import LanceDBConnection, function
|
||||
from lancedb.index import FTS
|
||||
|
||||
# TODO: setup integ test mark and script
|
||||
@@ -74,6 +74,106 @@ def test_json_fts_against_server():
|
||||
conn.drop_table(name)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not os.environ.get("LANCEDB_URI"),
|
||||
reason="Set LANCEDB_URI to a server with Python Functions enabled",
|
||||
)
|
||||
def test_function_execution_controls_through_sql_and_materialized_view():
|
||||
"""Exercise registered batch controls through the real remote runtime.
|
||||
|
||||
The Function returns the input batch length for every row. A cap of two must
|
||||
therefore produce only one- or two-element observations in both a direct
|
||||
SELECT and a materialized view refreshed after an append.
|
||||
"""
|
||||
suffix = uuid4().hex[:12]
|
||||
conn = lancedb.connect(
|
||||
uri=os.environ["LANCEDB_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"),
|
||||
)
|
||||
function_name = f"batch_probe_{suffix}"
|
||||
source_name = f"batch_probe_source_{suffix}"
|
||||
view_name = f"batch_probe_view_{suffix}"
|
||||
registered_version = None
|
||||
|
||||
@function(
|
||||
name=function_name,
|
||||
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
output_schema=pa.int64(),
|
||||
batch_size=2,
|
||||
row_timeout_seconds=15,
|
||||
)
|
||||
def observed_batch(value: pa.Array) -> pa.Array:
|
||||
size = len(value)
|
||||
return pa.array([size] * size, type=pa.int64())
|
||||
|
||||
def row_batch_sizes(table_name):
|
||||
rows = (
|
||||
conn.execute_query(
|
||||
f"SELECT {function_name}(value) AS observed FROM {table_name}"
|
||||
)
|
||||
.read_all()
|
||||
.to_pylist()
|
||||
)
|
||||
return [row["observed"] for row in rows]
|
||||
|
||||
def drop_table_if_present(table_name):
|
||||
try:
|
||||
conn.drop_table(table_name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
table = conn.create_table(
|
||||
source_name,
|
||||
pa.table(
|
||||
{"value": pa.array(range(8), type=pa.int64())},
|
||||
schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
),
|
||||
)
|
||||
registered_version = conn.create_function(observed_batch, namespace_path=None)
|
||||
|
||||
direct = row_batch_sizes(source_name)
|
||||
assert len(direct) == 8
|
||||
assert all(1 <= size <= 2 for size in direct)
|
||||
|
||||
view = conn.create_materialized_view(
|
||||
view_name,
|
||||
source=source_name,
|
||||
select=[("observed", f"{function_name}(value)")],
|
||||
)
|
||||
initial_view = [
|
||||
row["observed"]
|
||||
for row in view.table.search().select(["observed"]).to_list()
|
||||
]
|
||||
assert len(initial_view) == 8
|
||||
assert all(1 <= size <= 2 for size in initial_view)
|
||||
|
||||
table.add(
|
||||
pa.table(
|
||||
{"value": pa.array(range(8, 12), type=pa.int64())},
|
||||
schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
)
|
||||
)
|
||||
view.refresh()
|
||||
refreshed = [
|
||||
row["observed"]
|
||||
for row in view.table.search().select(["observed"]).to_list()
|
||||
]
|
||||
assert len(refreshed) == 12
|
||||
assert all(1 <= size <= 2 for size in refreshed)
|
||||
finally:
|
||||
drop_table_if_present(view_name)
|
||||
drop_table_if_present(source_name)
|
||||
if registered_version is not None:
|
||||
try:
|
||||
conn.drop_function(function_name, version=registered_version.version)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="Need to set up a local server")
|
||||
def test_against_local_server():
|
||||
conn = LanceDBConnection("lancedb+http://localhost:10024")
|
||||
|
||||
@@ -2337,6 +2337,13 @@ def _failing_transform(bad_ids: set):
|
||||
return transform
|
||||
|
||||
|
||||
def _fill_workers_transform(batch: pa.RecordBatch) -> list[dict]:
|
||||
ids = batch.column("id").to_pylist()
|
||||
if 0 in ids or 60 in ids:
|
||||
raise BadRowError("bad row")
|
||||
return [{"id": row_id} for row_id in ids]
|
||||
|
||||
|
||||
def _sequential_split_members(table) -> list[list[int]]:
|
||||
"""Return each split's ids in yield order for shuffle=False.
|
||||
|
||||
@@ -2367,6 +2374,115 @@ def test_on_transform_error_invalid_value(lance_table):
|
||||
StreamingDataset(lance_table, num_splits=NUM_SPLITS, on_transform_error="bogus")
|
||||
|
||||
|
||||
def test_on_transform_error_fill_requires_one_replacement(lance_table):
|
||||
kwargs = dict(num_splits=NUM_SPLITS, on_transform_error="fill")
|
||||
with pytest.raises(ValueError, match="exactly one"):
|
||||
StreamingDataset(lance_table, **kwargs)
|
||||
with pytest.raises(ValueError, match="exactly one"):
|
||||
StreamingDataset(
|
||||
lance_table, **kwargs, fill_value={"id": -1}, repair=lambda exc, row: row
|
||||
)
|
||||
with pytest.raises(ValueError, match="require on_transform_error='fill'"):
|
||||
StreamingDataset(lance_table, num_splits=NUM_SPLITS, fill_value=None)
|
||||
StreamingDataset(lance_table, **kwargs, fill_value=None)
|
||||
|
||||
|
||||
def test_on_transform_error_fill_preserves_rows_and_positions(lance_table):
|
||||
"""Uneven failures are replaced in place, including an entirely bad split."""
|
||||
members = _sequential_split_members(lance_table)
|
||||
bad_ids = set(members[0]) | {members[5][7]}
|
||||
clean = [
|
||||
row["id"]
|
||||
for row in StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
|
||||
]
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle=False,
|
||||
transform=_failing_transform(bad_ids),
|
||||
on_transform_error="fill",
|
||||
fill_value={"id": -1, "vector": [0.0, 0.0]},
|
||||
)
|
||||
assert ds.rows_filled == 0
|
||||
rows = list(ds)
|
||||
assert [row["id"] for row in rows] == [
|
||||
-1 if row_id in bad_ids else row_id for row_id in clean
|
||||
]
|
||||
assert len(rows) == NUM_ROWS
|
||||
assert ds.rows_filled == len(bad_ids)
|
||||
assert ds.rows_skipped == 0
|
||||
|
||||
placeholders = [row for row in rows if row["id"] == -1]
|
||||
placeholders[0]["vector"][0] = 1.0
|
||||
assert all(row["vector"] == [0.0, 0.0] for row in placeholders[1:])
|
||||
|
||||
|
||||
def test_on_transform_error_fill_repair_receives_failed_row(lance_table):
|
||||
bad_ids = {5, 17, 46}
|
||||
repaired = []
|
||||
|
||||
def repair(exc: Exception, row_batch: pa.RecordBatch) -> dict:
|
||||
assert isinstance(exc, BadRowError)
|
||||
assert row_batch.num_rows == 1
|
||||
row_id = row_batch.column("id")[0].as_py()
|
||||
repaired.append(row_id)
|
||||
return {"id": row_id, "repaired": True}
|
||||
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle=False,
|
||||
transform=_failing_transform(bad_ids),
|
||||
on_transform_error="fill",
|
||||
repair=repair,
|
||||
)
|
||||
rows = list(ds)
|
||||
assert sorted(row["id"] for row in rows) == list(range(NUM_ROWS))
|
||||
assert set(repaired) == bad_ids
|
||||
assert {row["id"] for row in rows if row.get("repaired")} == bad_ids
|
||||
assert ds.rows_filled == len(bad_ids)
|
||||
|
||||
|
||||
def test_on_transform_error_fill_repair_error_propagates(lance_table):
|
||||
def broken_repair(exc: Exception, row_batch: pa.RecordBatch):
|
||||
raise RuntimeError("repair failed")
|
||||
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
transform=_failing_transform({5}),
|
||||
on_transform_error="fill",
|
||||
repair=broken_repair,
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="repair failed"):
|
||||
list(ds)
|
||||
|
||||
|
||||
def test_on_transform_error_fill_counts_across_workers(lance_table):
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle=False,
|
||||
transform=_fill_workers_transform,
|
||||
on_transform_error="fill",
|
||||
fill_value={"id": -1},
|
||||
)
|
||||
loader = StreamingDataLoader(
|
||||
ds,
|
||||
batch_size=6,
|
||||
num_workers=2,
|
||||
multiprocessing_context="spawn",
|
||||
)
|
||||
iterator = iter(loader)
|
||||
try:
|
||||
ids = [row_id for batch in iterator for row_id in batch["id"].tolist()]
|
||||
finally:
|
||||
iterator._shutdown_workers()
|
||||
assert len(ids) == NUM_ROWS
|
||||
assert ids.count(-1) == 2
|
||||
assert ds.rows_filled == 2
|
||||
|
||||
|
||||
def test_on_transform_error_skip_drops_bad_rows(lance_table):
|
||||
"""With one bad row per split, 'skip' yields every good row exactly once
|
||||
and counts the dropped rows in rows_skipped."""
|
||||
@@ -2471,9 +2587,10 @@ def test_on_transform_error_callable_selective(lance_table):
|
||||
list(ds2)
|
||||
|
||||
|
||||
def test_transform_wrong_row_count_raises(lance_table):
|
||||
@pytest.mark.parametrize("on_error", ["skip", "fill"])
|
||||
def test_transform_wrong_row_count_raises(lance_table, on_error):
|
||||
"""A transform that returns the wrong number of rows is an error even with
|
||||
on_transform_error='skip' — silent shrinkage would corrupt accounting."""
|
||||
error recovery enabled — silent shrinkage would corrupt accounting."""
|
||||
|
||||
def drops_rows(batch: pa.RecordBatch) -> list:
|
||||
return batch.column("id").to_pylist()[:-1]
|
||||
@@ -2483,7 +2600,8 @@ def test_transform_wrong_row_count_raises(lance_table):
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
transform=drops_rows,
|
||||
on_transform_error="skip",
|
||||
on_transform_error=on_error,
|
||||
**({"fill_value": {"id": -1}} if on_error == "fill" else {}),
|
||||
)
|
||||
with pytest.raises(ValueError, match="one output row per input row"):
|
||||
list(ds)
|
||||
@@ -2561,6 +2679,61 @@ def test_skip_elastic_det_across_world_sizes(lance_table):
|
||||
assert collect(ws) == reference, f"world_size={ws} diverged"
|
||||
|
||||
|
||||
def test_fill_elastic_determinism_and_checkpoint(lance_table):
|
||||
"""Uneven fills keep every global step and resume across world sizes."""
|
||||
members = _sequential_split_members(lance_table)
|
||||
bad_ids = {members[0][0], members[0][2], members[6][1]}
|
||||
kwargs = dict(
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle=False,
|
||||
transform=_failing_transform(bad_ids),
|
||||
on_transform_error="fill",
|
||||
fill_value={"id": -1},
|
||||
)
|
||||
reference = [row["id"] for row in StreamingDataset(lance_table, **kwargs)]
|
||||
ref_steps = [
|
||||
sorted(reference[start : start + GLOBAL_BATCH_SIZE])
|
||||
for start in range(0, len(reference), GLOBAL_BATCH_SIZE)
|
||||
]
|
||||
assert len(ref_steps) == STEPS_PER_EPOCH
|
||||
|
||||
for world_size in (1, 2, 3, 4):
|
||||
micro = GLOBAL_BATCH_SIZE // world_size
|
||||
datasets = [
|
||||
StreamingDataset(lance_table, rank=rank, world_size=world_size, **kwargs)
|
||||
for rank in range(world_size)
|
||||
]
|
||||
iters = [iter(ds) for ds in datasets]
|
||||
steps = [
|
||||
sorted(next(it)["id"] for it in iters for _ in range(micro))
|
||||
for _ in range(STEPS_PER_EPOCH)
|
||||
]
|
||||
assert steps == ref_steps
|
||||
assert all(next(it, None) is None for it in iters)
|
||||
|
||||
world_size = 2
|
||||
micro = GLOBAL_BATCH_SIZE // world_size
|
||||
datasets = [
|
||||
StreamingDataset(lance_table, rank=rank, world_size=world_size, **kwargs)
|
||||
for rank in range(world_size)
|
||||
]
|
||||
iters = [iter(ds) for ds in datasets]
|
||||
for _ in range(3):
|
||||
for it in iters:
|
||||
for _ in range(micro):
|
||||
next(it)
|
||||
states = [ds.state_dict() for ds in datasets]
|
||||
for it in iters:
|
||||
it.close()
|
||||
merged = StreamingDataset.merge_state_dicts(states)
|
||||
assert merged["positions_consumed_per_split"] == [3] * NUM_SPLITS
|
||||
assert merged["samples_consumed_per_split"] == [3] * NUM_SPLITS
|
||||
|
||||
resumed = StreamingDataset(lance_table, **kwargs)
|
||||
resumed.load_state_dict(merged)
|
||||
assert [row["id"] for row in resumed] == reference[3 * NUM_SPLITS :]
|
||||
|
||||
|
||||
def test_resumability_with_skips_same_topology(lance_table):
|
||||
"""Checkpointing mid-epoch with skipped rows resumes exactly: no sample
|
||||
repeated, no sample lost, skipped rows stay skipped."""
|
||||
@@ -3495,6 +3668,7 @@ def test_default_checkpoint_resumes_after_compaction(lance_table):
|
||||
on this path -- instead of relying on shuffle_seed/num_splits alone, as it
|
||||
does -- would reject this resume even though the seeded permutation itself
|
||||
is unchanged."""
|
||||
pytest.importorskip("lance")
|
||||
lance_table.add(pa.table({"id": [NUM_ROWS]})) # a second fragment to compact
|
||||
|
||||
ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED)
|
||||
|
||||
@@ -33,6 +33,78 @@ def mock_embed_func(input_data):
|
||||
return [np.random.randn(128).tolist() for _ in range(len(input_data))]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def embedding_schema():
|
||||
func = MockTextEmbeddingFunction.create()
|
||||
|
||||
class Doc(LanceModel):
|
||||
id: int
|
||||
text: str = func.SourceField()
|
||||
vector: Vector(func.ndims()) = func.VectorField()
|
||||
|
||||
return Doc
|
||||
|
||||
|
||||
@pytest.mark.parametrize("column", ["text", "vector", "`text`", "`vector`"])
|
||||
@pytest.mark.parametrize("operation", ["rename", "drop"])
|
||||
def test_embedding_columns_schema_evolution(
|
||||
tmp_path, embedding_schema, column, operation
|
||||
):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", schema=embedding_schema)
|
||||
table.add([{"id": 1, "text": "hello"}])
|
||||
schema, version = table.schema, table.version
|
||||
|
||||
with pytest.raises(ValueError, match="used by an embedding function"):
|
||||
if operation == "rename":
|
||||
table.alter_columns(
|
||||
{"path": "id", "rename": "doc_id"},
|
||||
{"path": column, "rename": "renamed"},
|
||||
)
|
||||
else:
|
||||
table.drop_columns(["id", column])
|
||||
|
||||
assert table.schema == schema
|
||||
assert table.version == version
|
||||
assert table.embedding_functions["vector"].source_column == "text"
|
||||
reopened = db.open_table("docs")
|
||||
reopened.add([{"id": 2, "text": "world"}])
|
||||
assert reopened.count_rows() == 2
|
||||
assert reopened.to_arrow()["vector"].null_count == 0
|
||||
|
||||
# Columns outside the embedding binding can still evolve.
|
||||
reopened.alter_columns({"path": "id", "rename": "doc_id"})
|
||||
reopened.drop_columns(["doc_id"])
|
||||
reopened.add([{"text": "again"}])
|
||||
assert reopened.count_rows() == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("column", ["text", "vector"])
|
||||
@pytest.mark.parametrize("operation", ["rename", "drop"])
|
||||
async def test_async_embedding_columns_schema_evolution(
|
||||
tmp_path, embedding_schema, column, operation
|
||||
):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", schema=embedding_schema)
|
||||
await table.add([{"id": 1, "text": "hello"}])
|
||||
schema, version = await table.schema(), await table.version()
|
||||
|
||||
with pytest.raises(ValueError, match="used by an embedding function"):
|
||||
if operation == "rename":
|
||||
await table.alter_columns({"path": column, "rename": "renamed"})
|
||||
else:
|
||||
await table.drop_columns([column])
|
||||
|
||||
assert await table.schema() == schema
|
||||
assert await table.version() == version
|
||||
assert (await table.embedding_functions())["vector"].source_column == "text"
|
||||
reopened = await db.open_table("docs")
|
||||
await reopened.add([{"id": 2, "text": "world"}])
|
||||
assert await reopened.count_rows() == 2
|
||||
assert (await reopened.to_arrow())["vector"].null_count == 0
|
||||
|
||||
|
||||
def test_embedding_function(tmp_path):
|
||||
registry = EmbeddingFunctionRegistry.get_instance()
|
||||
|
||||
@@ -602,6 +674,51 @@ def test_openai_propagates_api_key(monkeypatch):
|
||||
assert len(actual.text) > 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_url", [None, "http://localhost:11434/v1"])
|
||||
def test_openai_compatible_model_uses_dim_for_ndims(base_url):
|
||||
# Unlisted model names use the explicit dimension independently of base_url.
|
||||
openai = get_registry().get("openai")
|
||||
func = openai.create(
|
||||
name="nomic-embed-text",
|
||||
base_url=base_url,
|
||||
dim=768,
|
||||
)
|
||||
assert func.ndims() == 768
|
||||
|
||||
class Schema(LanceModel):
|
||||
text: str = func.SourceField()
|
||||
vector: Vector(func.ndims()) = func.VectorField()
|
||||
|
||||
schema = Schema.to_arrow_schema()
|
||||
assert schema.field("vector").type == pa.list_(pa.float32(), 768)
|
||||
|
||||
|
||||
def test_openai_unknown_model_without_dim_raises_clear_error():
|
||||
openai = get_registry().get("openai")
|
||||
func = openai.create(
|
||||
name="nomic-embed-text",
|
||||
base_url="http://localhost:11434/v1",
|
||||
)
|
||||
with pytest.raises(ValueError, match="dim"):
|
||||
func.ndims()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "dim", "expected_dim"),
|
||||
[
|
||||
("text-embedding-ada-002", None, 1536),
|
||||
("text-embedding-ada-002", 512, 1536),
|
||||
("text-embedding-3-large", None, 3072),
|
||||
("text-embedding-3-large", 1024, 1024),
|
||||
("text-embedding-3-small", None, 1536),
|
||||
("text-embedding-3-small", 512, 512),
|
||||
],
|
||||
)
|
||||
def test_openai_known_model_ndims(name, dim, expected_dim):
|
||||
func = get_registry().get("openai").create(name=name, dim=dim)
|
||||
assert func.ndims() == expected_dim
|
||||
|
||||
|
||||
@patch("time.sleep")
|
||||
def test_openai_no_retry_on_401(mock_sleep):
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
"""Unit tests for the OCI Generative AI embedding function.
|
||||
|
||||
The ``oci`` SDK is replaced with a small fake so these run without the package
|
||||
or cloud credentials. Live coverage lives in ``test_embeddings_slow.py``.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pickle
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import lancedb
|
||||
import pytest
|
||||
from lancedb.embeddings import OCIGenAIEmbeddings, get_registry
|
||||
from lancedb.embeddings.oci_genai import EMBEDDING_BATCH_SIZE, OCIGenAIServiceError
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
from pydantic import ValidationError
|
||||
|
||||
DIMS = 8
|
||||
COMPARTMENT = "ocid1.compartment.oc1..test"
|
||||
|
||||
|
||||
class FakeServiceError(Exception):
|
||||
"""Mimics ``oci.exceptions.ServiceError``."""
|
||||
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def _fake_embed_text(details):
|
||||
# Deterministic embeddings: first component encodes len(text) so ordering
|
||||
# and nearest-neighbour behaviour can be asserted.
|
||||
embeddings = [[float(len(text))] + [0.0] * (DIMS - 1) for text in details.inputs]
|
||||
return SimpleNamespace(data=SimpleNamespace(embeddings=embeddings))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_oci():
|
||||
"""Stand-in for the ``oci`` package, injected via attempt_import_or_raise."""
|
||||
oci = MagicMock(name="oci")
|
||||
oci.exceptions.ServiceError = FakeServiceError
|
||||
models = oci.generative_ai_inference.models
|
||||
models.EmbedTextDetails.side_effect = lambda **kw: SimpleNamespace(**kw)
|
||||
models.OnDemandServingMode.side_effect = lambda **kw: SimpleNamespace(
|
||||
serving_type="ON_DEMAND", **kw
|
||||
)
|
||||
models.DedicatedServingMode.side_effect = lambda **kw: SimpleNamespace(
|
||||
serving_type="DEDICATED", **kw
|
||||
)
|
||||
oci.config.from_file.return_value = {"key_file": "~/.oci/key.pem"}
|
||||
client = oci.generative_ai_inference.GenerativeAiInferenceClient.return_value
|
||||
client.embed_text.side_effect = _fake_embed_text
|
||||
with patch(
|
||||
"lancedb.embeddings.oci_genai.attempt_import_or_raise", return_value=oci
|
||||
):
|
||||
yield oci
|
||||
|
||||
|
||||
def _create(**kwargs):
|
||||
kwargs.setdefault("compartment_id", COMPARTMENT)
|
||||
kwargs.setdefault("max_retries", 0)
|
||||
return get_registry().get("oci-genai").create(**kwargs)
|
||||
|
||||
|
||||
def _client(fake_oci):
|
||||
return fake_oci.generative_ai_inference.GenerativeAiInferenceClient.return_value
|
||||
|
||||
|
||||
def _client_kwargs(fake_oci):
|
||||
return fake_oci.generative_ai_inference.GenerativeAiInferenceClient.call_args.kwargs
|
||||
|
||||
|
||||
def _embed_requests(fake_oci):
|
||||
return [call.args[0] for call in _client(fake_oci).embed_text.call_args_list]
|
||||
|
||||
|
||||
def test_oci_genai_registered():
|
||||
assert get_registry().get("oci-genai") is OCIGenAIEmbeddings
|
||||
assert "cohere.embed-v4.0" in OCIGenAIEmbeddings.model_names()
|
||||
func = _create()
|
||||
assert func.name == "cohere.embed-v4.0"
|
||||
assert func.auth_type == "API_KEY"
|
||||
assert func.truncate == "END"
|
||||
assert func.sensitive_keys() == []
|
||||
|
||||
|
||||
def test_oci_genai_service_endpoint(fake_oci):
|
||||
default = _create()
|
||||
assert default.endpoints() == []
|
||||
default._client
|
||||
assert (
|
||||
_client_kwargs(fake_oci)["service_endpoint"]
|
||||
== "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com"
|
||||
)
|
||||
|
||||
regional = _create(region="eu-frankfurt-1")
|
||||
regional_endpoint = (
|
||||
"https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com"
|
||||
)
|
||||
assert regional.endpoints() == [regional_endpoint]
|
||||
regional._client
|
||||
assert _client_kwargs(fake_oci)["service_endpoint"] == regional_endpoint
|
||||
|
||||
custom = "https://inference.generativeai.us-langley-1.oci.oraclegovcloud.com"
|
||||
explicit = _create(region="us-chicago-1", service_endpoint=custom)
|
||||
assert explicit.endpoints() == [custom]
|
||||
explicit._client
|
||||
assert _client_kwargs(fake_oci)["service_endpoint"] == custom
|
||||
|
||||
|
||||
def test_oci_genai_client_disables_sdk_retries(fake_oci):
|
||||
_create()._client
|
||||
kwargs = _client_kwargs(fake_oci)
|
||||
assert kwargs["retry_strategy"] is fake_oci.retry.NoneRetryStrategy.return_value
|
||||
|
||||
|
||||
def test_oci_genai_api_key_auth(fake_oci, tmp_path):
|
||||
config_file = str(tmp_path / "config")
|
||||
func = _create(auth_profile="MYPROFILE", auth_file_location=config_file)
|
||||
func._client
|
||||
fake_oci.config.from_file.assert_called_once_with(
|
||||
file_location=config_file, profile_name="MYPROFILE"
|
||||
)
|
||||
kwargs = _client_kwargs(fake_oci)
|
||||
assert kwargs["config"] is fake_oci.config.from_file.return_value
|
||||
assert "signer" not in kwargs
|
||||
|
||||
|
||||
def test_oci_genai_api_key_rejects_session_profile(fake_oci):
|
||||
fake_oci.config.from_file.return_value = {
|
||||
"key_file": "~/.oci/sessions/x/key.pem",
|
||||
"security_token_file": "~/.oci/sessions/x/token",
|
||||
}
|
||||
with pytest.raises(ValueError, match="SECURITY_TOKEN"):
|
||||
_create(auth_type="API_KEY")._client
|
||||
|
||||
|
||||
def test_oci_genai_security_token_auth(fake_oci, tmp_path):
|
||||
token_file = tmp_path / "token"
|
||||
token_file.write_text("session-token\n")
|
||||
fake_oci.config.from_file.return_value = {
|
||||
"key_file": "~/.oci/sessions/x/key.pem",
|
||||
"security_token_file": str(token_file),
|
||||
}
|
||||
_create(auth_type="SECURITY_TOKEN", auth_profile="SESSION")._client
|
||||
|
||||
fake_oci.signer.load_private_key_from_file.assert_called_once_with(
|
||||
os.path.expanduser("~/.oci/sessions/x/key.pem"), None
|
||||
)
|
||||
fake_oci.auth.signers.SecurityTokenSigner.assert_called_once_with(
|
||||
"session-token", fake_oci.signer.load_private_key_from_file.return_value
|
||||
)
|
||||
kwargs = _client_kwargs(fake_oci)
|
||||
assert kwargs["signer"] is fake_oci.auth.signers.SecurityTokenSigner.return_value
|
||||
assert kwargs["config"] is fake_oci.config.from_file.return_value
|
||||
|
||||
|
||||
def test_oci_genai_security_token_requires_token_file(fake_oci):
|
||||
with pytest.raises(ValueError, match="security_token_file"):
|
||||
_create(auth_type="SECURITY_TOKEN")._client
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"auth_type,factory",
|
||||
[
|
||||
("INSTANCE_PRINCIPAL", "InstancePrincipalsSecurityTokenSigner"),
|
||||
("RESOURCE_PRINCIPAL", "get_resource_principals_signer"),
|
||||
],
|
||||
)
|
||||
def test_oci_genai_principal_auth(fake_oci, auth_type, factory):
|
||||
_create(auth_type=auth_type)._client
|
||||
signer_factory = getattr(fake_oci.auth.signers, factory)
|
||||
signer_factory.assert_called_once_with()
|
||||
kwargs = _client_kwargs(fake_oci)
|
||||
assert kwargs["config"] == {}
|
||||
assert kwargs["signer"] is signer_factory.return_value
|
||||
fake_oci.config.from_file.assert_not_called()
|
||||
|
||||
|
||||
def test_oci_genai_rejects_invalid_config():
|
||||
with pytest.raises(ValidationError, match="auth_type"):
|
||||
_create(auth_type="PASSWORD")
|
||||
with pytest.raises(ValidationError, match="truncate"):
|
||||
_create(truncate="MIDDLE")
|
||||
|
||||
|
||||
def test_oci_genai_compartment_id_required(fake_oci, monkeypatch):
|
||||
monkeypatch.delenv("OCI_COMPARTMENT_ID", raising=False)
|
||||
func = get_registry().get("oci-genai").create(max_retries=0)
|
||||
with pytest.raises(ValueError, match="OCI_COMPARTMENT_ID"):
|
||||
func.compute_source_embeddings(["hello"])
|
||||
assert _embed_requests(fake_oci) == []
|
||||
|
||||
monkeypatch.setenv("OCI_COMPARTMENT_ID", "ocid1.compartment.oc1..from-env")
|
||||
func.compute_source_embeddings(["hello"])
|
||||
assert _embed_requests(fake_oci)[0].compartment_id == (
|
||||
"ocid1.compartment.oc1..from-env"
|
||||
)
|
||||
|
||||
|
||||
def test_oci_genai_request_shape(fake_oci):
|
||||
func = _create(name="cohere.embed-multilingual-v3.0", truncate="START")
|
||||
func.compute_source_embeddings(["hello"])
|
||||
(details,) = _embed_requests(fake_oci)
|
||||
assert details.inputs == ["hello"]
|
||||
assert details.compartment_id == COMPARTMENT
|
||||
assert details.truncate == "START"
|
||||
assert details.input_type == "SEARCH_DOCUMENT"
|
||||
assert details.serving_mode.serving_type == "ON_DEMAND"
|
||||
assert details.serving_mode.model_id == "cohere.embed-multilingual-v3.0"
|
||||
# only sent when configured so older SDKs / models keep working
|
||||
assert not hasattr(details, "output_dimensions")
|
||||
|
||||
|
||||
def test_oci_genai_dedicated_endpoint(fake_oci):
|
||||
endpoint = "ocid1.generativeaiendpoint.oc1.us-chicago-1.test"
|
||||
_create(name=endpoint).compute_source_embeddings(["hello"])
|
||||
(details,) = _embed_requests(fake_oci)
|
||||
assert details.serving_mode.serving_type == "DEDICATED"
|
||||
assert details.serving_mode.endpoint_id == endpoint
|
||||
|
||||
|
||||
def test_oci_genai_query_and_source_input_types(fake_oci):
|
||||
func = _create()
|
||||
func.compute_source_embeddings(["a document"])
|
||||
func.compute_query_embeddings("a query")
|
||||
source, query = _embed_requests(fake_oci)
|
||||
assert source.input_type == "SEARCH_DOCUMENT"
|
||||
assert query.input_type == "SEARCH_QUERY"
|
||||
|
||||
custom = _create(source_input_type="CLUSTERING", query_input_type="CLASSIFICATION")
|
||||
custom.compute_source_embeddings(["a document"])
|
||||
custom.compute_query_embeddings("a query")
|
||||
source, query = _embed_requests(fake_oci)[2:]
|
||||
assert source.input_type == "CLUSTERING"
|
||||
assert query.input_type == "CLASSIFICATION"
|
||||
|
||||
|
||||
def test_oci_genai_batches_at_service_limit(fake_oci):
|
||||
assert EMBEDDING_BATCH_SIZE == 96
|
||||
texts = [f"text {i:03d}" for i in range(2 * EMBEDDING_BATCH_SIZE + 8)]
|
||||
embeddings = _create().compute_source_embeddings(texts)
|
||||
|
||||
requests = _embed_requests(fake_oci)
|
||||
assert [len(r.inputs) for r in requests] == [96, 96, 8]
|
||||
assert [t for r in requests for t in r.inputs] == texts
|
||||
assert all(r.input_type == "SEARCH_DOCUMENT" for r in requests)
|
||||
assert len(embeddings) == len(texts)
|
||||
assert [e[0] for e in embeddings] == [float(len(t)) for t in texts]
|
||||
|
||||
|
||||
def test_oci_genai_empty_inputs_are_skipped(fake_oci):
|
||||
func = _create()
|
||||
assert func.compute_source_embeddings([]) == []
|
||||
assert _embed_requests(fake_oci) == []
|
||||
|
||||
embeddings = func.compute_source_embeddings(["hello", "", None, "world"])
|
||||
(details,) = _embed_requests(fake_oci)
|
||||
assert details.inputs == ["hello", "world"]
|
||||
assert embeddings[1] is None
|
||||
assert embeddings[2] is None
|
||||
assert embeddings[0][0] == 5.0
|
||||
assert embeddings[3][0] == 5.0
|
||||
|
||||
|
||||
def test_oci_genai_ndims_probe_is_cached(fake_oci):
|
||||
func = _create()
|
||||
assert func.ndims() == DIMS
|
||||
assert func.ndims() == DIMS
|
||||
assert len(_embed_requests(fake_oci)) == 1
|
||||
|
||||
|
||||
def test_oci_genai_output_dimensions(fake_oci):
|
||||
func = _create(output_dimensions=512)
|
||||
assert func.ndims() == 512
|
||||
assert _embed_requests(fake_oci) == [] # no probe request needed
|
||||
|
||||
func.compute_source_embeddings(["hello"])
|
||||
(details,) = _embed_requests(fake_oci)
|
||||
assert details.output_dimensions == 512
|
||||
|
||||
|
||||
@patch("time.sleep")
|
||||
def test_oci_genai_auth_errors_are_not_retried(mock_sleep, fake_oci):
|
||||
_client(fake_oci).embed_text.side_effect = FakeServiceError(
|
||||
401, "NotAuthenticated", "The required information was not provided."
|
||||
)
|
||||
func = _create(max_retries=3)
|
||||
with pytest.raises(OCIGenAIServiceError, match="HTTP 401") as exc_info:
|
||||
func.compute_source_embeddings_with_retry(["hello"])
|
||||
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "oci session authenticate" in str(exc_info.value)
|
||||
assert isinstance(exc_info.value.__cause__, FakeServiceError)
|
||||
assert _client(fake_oci).embed_text.call_count == 1
|
||||
mock_sleep.assert_not_called()
|
||||
|
||||
|
||||
@patch("time.sleep")
|
||||
def test_oci_genai_server_errors_are_retried(mock_sleep, fake_oci):
|
||||
_client(fake_oci).embed_text.side_effect = FakeServiceError(
|
||||
500, "InternalError", "try again"
|
||||
)
|
||||
func = _create(max_retries=2)
|
||||
with pytest.raises(Exception, match="Maximum number of retries"):
|
||||
func.compute_source_embeddings_with_retry(["hello"])
|
||||
assert _client(fake_oci).embed_text.call_count == 3
|
||||
|
||||
|
||||
def test_oci_genai_pickle_after_client_created(fake_oci):
|
||||
func = _create(auth_profile="MYPROFILE")
|
||||
func.compute_source_embeddings(["hello"])
|
||||
assert "_client" in func.__dict__
|
||||
|
||||
restored = pickle.loads(pickle.dumps(func))
|
||||
assert "_client" not in restored.__dict__
|
||||
assert restored.compartment_id == COMPARTMENT
|
||||
assert restored.auth_profile == "MYPROFILE"
|
||||
|
||||
|
||||
def test_oci_genai_table_round_trip(fake_oci):
|
||||
func = _create(region="us-ashburn-1", auth_profile="MYPROFILE")
|
||||
|
||||
class Docs(LanceModel):
|
||||
text: str = func.SourceField()
|
||||
vector: Vector(func.ndims()) = func.VectorField()
|
||||
|
||||
db = lancedb.connect("memory://")
|
||||
tbl = db.create_table("docs", schema=Docs, mode="overwrite")
|
||||
tbl.add([{"text": "hello"}, {"text": "goodbye world"}])
|
||||
assert len(tbl.to_arrow()["vector"][0].as_py()) == DIMS
|
||||
|
||||
# the fake embeds len(text), so an equally long query lands on that row
|
||||
hits = tbl.search("goodbye world").limit(1).to_arrow()
|
||||
assert hits["text"][0].as_py() == "goodbye world"
|
||||
assert _embed_requests(fake_oci)[-1].input_type == "SEARCH_QUERY"
|
||||
|
||||
parsed = tbl.embedding_functions["vector"].function
|
||||
assert isinstance(parsed, OCIGenAIEmbeddings)
|
||||
assert parsed.safe_model_dump() == {
|
||||
"compartment_id": COMPARTMENT,
|
||||
"max_retries": 0,
|
||||
"region": "us-ashburn-1",
|
||||
"auth_profile": "MYPROFILE",
|
||||
}
|
||||
@@ -379,6 +379,58 @@ def test_bedrock_embedding(tmp_path):
|
||||
assert len(tbl.to_pandas()["vector"][0]) == model.ndims()
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("OCI_COMPARTMENT_ID") is None, reason="OCI_COMPARTMENT_ID not set"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"model_name,output_dimensions,expected_dims",
|
||||
[
|
||||
("cohere.embed-v4.0", None, 1536),
|
||||
("cohere.embed-v4.0", 512, 512),
|
||||
("cohere.embed-multilingual-v3.0", None, 1024),
|
||||
],
|
||||
)
|
||||
def test_oci_genai_embedding(model_name, output_dimensions, expected_dims, tmp_path):
|
||||
pytest.importorskip("oci")
|
||||
# compartment_id comes from OCI_COMPARTMENT_ID; the profile / auth follow the
|
||||
# OCI CLI's own OCI_CLI_PROFILE / OCI_CLI_AUTH / OCI_CLI_REGION variables so
|
||||
# both API keys and `oci session authenticate` sessions work.
|
||||
security_token = os.environ.get("OCI_CLI_AUTH") == "security_token"
|
||||
model = (
|
||||
get_registry()
|
||||
.get("oci-genai")
|
||||
.create(
|
||||
name=model_name,
|
||||
output_dimensions=output_dimensions,
|
||||
auth_type="SECURITY_TOKEN" if security_token else "API_KEY",
|
||||
auth_profile=os.environ.get("OCI_CLI_PROFILE", "DEFAULT"),
|
||||
region=os.environ.get("OCI_CLI_REGION", "us-chicago-1"),
|
||||
max_retries=0,
|
||||
)
|
||||
)
|
||||
assert model.ndims() == expected_dims
|
||||
|
||||
class TextModel(LanceModel):
|
||||
text: str = model.SourceField()
|
||||
vector: Vector(model.ndims()) = model.VectorField()
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
tbl = db.create_table("oci_genai_test", schema=TextModel, mode="overwrite")
|
||||
df = pd.DataFrame(
|
||||
{"text": ["hello world", "goodbye world", "a recipe for lasagna", ""]}
|
||||
)
|
||||
tbl.add(df, on_bad_vectors="null")
|
||||
|
||||
tb = tbl.to_arrow()
|
||||
assert tb.schema.field_by_name("vector").type == pa.list_(
|
||||
pa.float32(), expected_dims
|
||||
)
|
||||
# the empty input is not sent to the service and is stored as null
|
||||
assert tb["vector"].is_null().to_pylist() == [False, False, False, True]
|
||||
assert tbl.search("hello").limit(1).to_pandas()["text"][0] == "hello world"
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("OPENAI_API_KEY") is None, reason="OPENAI_API_KEY not set"
|
||||
|
||||
@@ -15,6 +15,7 @@ import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb.embeddings import (
|
||||
EmbeddingFunctionConfig,
|
||||
OCIGenAIEmbeddings,
|
||||
OllamaEmbeddings,
|
||||
OpenAIEmbeddings,
|
||||
SentenceTransformerEmbeddings,
|
||||
@@ -220,6 +221,9 @@ def test_trusting_one_model_does_not_trust_a_swapped_name():
|
||||
|
||||
|
||||
ATTACKER_URL = "https://attacker.example/v1"
|
||||
OCI_REGION_ENDPOINT = (
|
||||
"https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -247,6 +251,31 @@ def test_default_endpoints_need_no_allowlist():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model,endpoint",
|
||||
[
|
||||
({"service_endpoint": ATTACKER_URL}, ATTACKER_URL),
|
||||
({"region": "eu-frankfurt-1"}, OCI_REGION_ENDPOINT),
|
||||
],
|
||||
)
|
||||
def test_restored_oci_custom_endpoint_requires_allowlist(model, endpoint):
|
||||
func = restore("oci-genai", model)
|
||||
assert isinstance(func, UntrustedEmbeddingFunction)
|
||||
with pytest.raises(UntrustedEmbeddingConfigError, match="allow_endpoint"):
|
||||
func.compute_query_embeddings("hello")
|
||||
|
||||
get_registry().allow_endpoint(endpoint)
|
||||
restored = restore("oci-genai", model)
|
||||
assert isinstance(restored, OCIGenAIEmbeddings)
|
||||
assert restored.endpoints() == [endpoint]
|
||||
|
||||
|
||||
def test_restored_oci_default_endpoint_needs_no_allowlist():
|
||||
func = restore("oci-genai", {})
|
||||
assert isinstance(func, OCIGenAIEmbeddings)
|
||||
assert func.endpoints() == []
|
||||
|
||||
|
||||
def test_endpoint_allowlist_ignores_trailing_slash():
|
||||
get_registry().allow_endpoint("http://my-host:11434/")
|
||||
assert isinstance(
|
||||
|
||||
@@ -4,9 +4,22 @@
|
||||
import pickle
|
||||
|
||||
import pytest
|
||||
from lance_namespace.errors import ErrorCode
|
||||
from lance_namespace.errors import TableNotFoundError as NamespaceTableNotFoundError
|
||||
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.remote.errors import HttpError, LanceDBClientError, RetryError
|
||||
from lancedb.remote.errors import (
|
||||
AlreadyExistsError,
|
||||
ConflictError,
|
||||
FunctionNotFoundError,
|
||||
HttpError,
|
||||
LanceDBClientError,
|
||||
NamespaceNotFoundError,
|
||||
ResponseInterruptedError,
|
||||
RetryError,
|
||||
SecretNotFoundError,
|
||||
TableNotFoundError,
|
||||
)
|
||||
from lancedb.table import Table
|
||||
|
||||
|
||||
@@ -50,6 +63,150 @@ def test_pickle_http_error():
|
||||
assert str(restored) == "not found"
|
||||
assert restored.request_id == "req-789"
|
||||
assert restored.status_code == 404
|
||||
assert restored.is_transport_error is False
|
||||
|
||||
|
||||
def test_pickle_http_transport_error():
|
||||
err = HttpError("connection reset", "req-789", is_transport_error=True)
|
||||
restored = pickle.loads(pickle.dumps(err))
|
||||
assert isinstance(restored, HttpError)
|
||||
assert restored.is_transport_error is True
|
||||
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",
|
||||
[
|
||||
("not_found", "secret", 404, SecretNotFoundError),
|
||||
("not_found", "function", 404, FunctionNotFoundError),
|
||||
("not_found", "namespace", 404, NamespaceNotFoundError),
|
||||
("already_exists", "secret", 409, AlreadyExistsError),
|
||||
],
|
||||
)
|
||||
def test_http_error_structured_resource_error(
|
||||
error_code, resource_kind, status_code, expected_type
|
||||
):
|
||||
err = HttpError(
|
||||
"resource request failed",
|
||||
"req-structured",
|
||||
status_code,
|
||||
error_code,
|
||||
resource_kind,
|
||||
"resource-name",
|
||||
["parent", "child"],
|
||||
)
|
||||
|
||||
assert type(err) is expected_type
|
||||
assert isinstance(err, HttpError)
|
||||
assert err.error_code == error_code
|
||||
assert err.resource_kind == resource_kind
|
||||
assert err.resource_name == "resource-name"
|
||||
assert err.namespace_path == ("parent", "child")
|
||||
assert err.request_id == "req-structured"
|
||||
assert err.status_code == status_code
|
||||
assert err.is_transport_error is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error_code,resource_kind",
|
||||
[
|
||||
(None, None),
|
||||
("not_found", None),
|
||||
("not_found", "unknown"),
|
||||
("invalid", "secret"),
|
||||
],
|
||||
)
|
||||
def test_http_error_without_known_structured_fields_stays_generic(
|
||||
error_code, resource_kind
|
||||
):
|
||||
err = HttpError(
|
||||
"not found",
|
||||
"req-generic",
|
||||
404,
|
||||
error_code,
|
||||
resource_kind,
|
||||
"resource-name",
|
||||
[],
|
||||
)
|
||||
|
||||
assert type(err) is HttpError
|
||||
assert err.error_code == error_code
|
||||
assert err.resource_kind == resource_kind
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exception_type,error_code,resource_kind",
|
||||
[
|
||||
(SecretNotFoundError, "not_found", "secret"),
|
||||
(FunctionNotFoundError, "not_found", "function"),
|
||||
(NamespaceNotFoundError, "not_found", "namespace"),
|
||||
(AlreadyExistsError, "already_exists", "namespace"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("is_transport_error", [False, True])
|
||||
def test_pickle_structured_http_error(
|
||||
exception_type, error_code, resource_kind, is_transport_error
|
||||
):
|
||||
err = HttpError(
|
||||
"resource request failed",
|
||||
"req-pickle",
|
||||
409 if error_code == "already_exists" else 404,
|
||||
error_code,
|
||||
resource_kind,
|
||||
"resource-name",
|
||||
["parent"],
|
||||
is_transport_error=is_transport_error,
|
||||
)
|
||||
assert type(err) is exception_type
|
||||
|
||||
restored = pickle.loads(pickle.dumps(err))
|
||||
|
||||
assert type(restored) is exception_type
|
||||
assert restored.error_code == error_code
|
||||
assert restored.resource_kind == resource_kind
|
||||
assert restored.resource_name == "resource-name"
|
||||
assert restored.namespace_path == ("parent",)
|
||||
assert restored.request_id == "req-pickle"
|
||||
assert restored.status_code == err.status_code
|
||||
assert restored.is_transport_error is is_transport_error
|
||||
|
||||
|
||||
def test_pickle_table_not_found_error():
|
||||
err = TableNotFoundError("Table 'missing' was not found", "req-missing", 404)
|
||||
restored = pickle.loads(pickle.dumps(err))
|
||||
assert isinstance(restored, TableNotFoundError)
|
||||
assert isinstance(restored, NamespaceTableNotFoundError)
|
||||
assert isinstance(restored, ValueError)
|
||||
assert isinstance(restored, HttpError)
|
||||
assert restored.code == ErrorCode.TABLE_NOT_FOUND
|
||||
assert str(restored) == "Table 'missing' was not found"
|
||||
assert restored.request_id == "req-missing"
|
||||
assert restored.status_code == 404
|
||||
|
||||
|
||||
def test_pickle_retry_error():
|
||||
@@ -75,3 +232,87 @@ def test_pickle_retry_error():
|
||||
assert restored.max_connect_failures == 3
|
||||
assert restored.max_read_failures == 3
|
||||
assert restored.status_code == 503
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"code,category,type_name",
|
||||
[
|
||||
(3, "column_not_found", "SqlColumnNotFoundError"),
|
||||
(3, "schema_mismatch", "SqlSchemaMismatchError"),
|
||||
(5, "table_not_found", "SqlTableNotFoundError"),
|
||||
(5, "reference_not_found", "SqlReferenceNotFoundError"),
|
||||
(13, "column_not_found", "SqlError"),
|
||||
(14, "table_not_found", "SqlError"),
|
||||
(3, None, "SqlError"),
|
||||
(5, "future_code", "SqlError"),
|
||||
],
|
||||
)
|
||||
def test_sql_errors_use_only_server_codes(code, category, type_name):
|
||||
from lancedb.remote import errors
|
||||
|
||||
original = errors.SqlError(
|
||||
"column_not_found: user/file.rs:12",
|
||||
"current",
|
||||
code,
|
||||
category,
|
||||
"sql-job",
|
||||
"worker",
|
||||
)
|
||||
for error in [original, pickle.loads(pickle.dumps(original))]:
|
||||
assert type(error) is getattr(errors, type_name)
|
||||
assert str(error) == "column_not_found: user/file.rs:12"
|
||||
assert error.request_id == "current"
|
||||
assert error.grpc_code == code
|
||||
assert error.error_code == category
|
||||
assert error.job_id == "sql-job"
|
||||
assert error.job_request_id == "worker"
|
||||
assert error.status_code is None
|
||||
if type_name != "SqlError":
|
||||
assert isinstance(error, ValueError)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"status,category,type_name",
|
||||
[
|
||||
(400, "column_not_found", "ColumnNotFoundError"),
|
||||
(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"),
|
||||
],
|
||||
)
|
||||
def test_http_input_errors_keep_status_and_job_metadata(status, category, type_name):
|
||||
from lancedb.remote import errors
|
||||
|
||||
original = errors.HttpError(
|
||||
"original diagnostic",
|
||||
"current",
|
||||
status,
|
||||
error_code=category,
|
||||
job_id="sql-job",
|
||||
job_request_id="worker",
|
||||
)
|
||||
for error in [original, pickle.loads(pickle.dumps(original))]:
|
||||
assert type(error) is getattr(errors, type_name)
|
||||
assert error.status_code == status
|
||||
assert error.job_id == "sql-job"
|
||||
assert error.job_request_id == "worker"
|
||||
assert error.request_id == "current"
|
||||
|
||||
|
||||
def test_local_query_keeps_missing_column_type(tmp_path):
|
||||
import lancedb
|
||||
from lancedb.exceptions import ColumnNotFoundError
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("events", [{"id": 1}])
|
||||
with pytest.raises(ColumnNotFoundError) as exc_info:
|
||||
table.search().where("missing > 0").to_arrow()
|
||||
assert "missing" in str(exc_info.value)
|
||||
assert exc_info.value.request_id is None
|
||||
assert exc_info.value.job_id is None
|
||||
assert exc_info.value.job_request_id is None
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from collections import UserDict
|
||||
from pathlib import Path
|
||||
from types import MappingProxyType
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -167,6 +169,33 @@ def test_function_version_preserves_source_digest(source_digest):
|
||||
version.source_digest = "sha256:changed"
|
||||
|
||||
|
||||
def test_function_version_exposes_registered_gpu_class():
|
||||
value = job_result("remote_function_job.json")
|
||||
legacy = FunctionVersion.from_json(json.dumps(value))
|
||||
assert legacy.gpu_class is None
|
||||
|
||||
value["gpu_class"] = "a10g"
|
||||
version = FunctionVersion.from_json(json.dumps(value))
|
||||
assert version.gpu_class == "a10g"
|
||||
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,
|
||||
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["row_timeout_seconds"]) is float
|
||||
assert type(encoded["result_stability"]) is str
|
||||
|
||||
|
||||
def test_function_version_binds_named_columns_as_one_immutable_application():
|
||||
version = FunctionVersion.from_json(
|
||||
json.dumps(job_result("remote_function_job.json"))
|
||||
@@ -272,10 +301,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():
|
||||
@@ -444,13 +478,16 @@ def known_application() -> FunctionApplication:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomically():
|
||||
@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType])
|
||||
async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomically(
|
||||
mapping_type,
|
||||
):
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()
|
||||
|
||||
result = await table.add_columns(
|
||||
{"features": application._copy(update={"columns": {}})}
|
||||
mapping_type({"features": application._copy(update={"columns": {}})})
|
||||
)
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] == "features"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -39,7 +39,6 @@ from lancedb.query import (
|
||||
)
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pandas as pd
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from utils import exception_output
|
||||
@@ -154,7 +153,7 @@ def table(tmp_path) -> ldb.table.LanceTable:
|
||||
count = [local_random.randint(1, 10000) for _ in range(100)]
|
||||
table = db.create_table(
|
||||
"test",
|
||||
data=pd.DataFrame(
|
||||
data=pa.table(
|
||||
{
|
||||
"vector": vectors,
|
||||
"id": [i % 2 for i in range(100)],
|
||||
@@ -239,7 +238,7 @@ async def async_table(tmp_path) -> ldb.table.AsyncTable:
|
||||
count = [local_random.randint(1, 10000) for _ in range(100)]
|
||||
table = await db.create_table(
|
||||
"test",
|
||||
data=pd.DataFrame(
|
||||
data=pa.table(
|
||||
{
|
||||
"vector": vectors,
|
||||
"id": [i % 2 for i in range(100)],
|
||||
@@ -760,9 +759,9 @@ def test_search_order_by_ascending(table):
|
||||
|
||||
def test_create_index_from_table(tmp_path, table):
|
||||
table.create_fts_index("text")
|
||||
df = table.search("puppy").limit(5).select(["text"]).to_pandas()
|
||||
assert len(df) <= 5
|
||||
assert "text" in df.columns
|
||||
result = table.search("puppy").limit(5).select(["text"]).to_arrow()
|
||||
assert len(result) <= 5
|
||||
assert "text" in result.column_names
|
||||
|
||||
# Check whether it can be updated
|
||||
table.add(
|
||||
@@ -782,7 +781,7 @@ def test_create_index_from_table(tmp_path, table):
|
||||
table.create_fts_index("text")
|
||||
|
||||
table.create_fts_index("text", replace=True)
|
||||
assert len(table.search("gorilla").limit(1).to_pandas()) == 1
|
||||
assert len(table.search("gorilla").limit(1).to_arrow()) == 1
|
||||
|
||||
|
||||
def test_create_index_multiple_columns(tmp_path, table):
|
||||
@@ -1832,3 +1831,120 @@ async def test_fts_fast_search_async(async_table):
|
||||
.to_list()
|
||||
)
|
||||
assert len(results) > 0
|
||||
|
||||
|
||||
CODE_TEXT = "parseHTTPRequest user_id utf8"
|
||||
|
||||
|
||||
def _token_texts(tokens):
|
||||
return [token.text for token in tokens]
|
||||
|
||||
|
||||
def test_tokenize_code_analyzer_flags():
|
||||
default = _token_texts(ldb.tokenize(CODE_TEXT, analyzer="code"))
|
||||
assert default == _token_texts(ldb.tokenize(CODE_TEXT, base_tokenizer="code"))
|
||||
|
||||
no_split = _token_texts(
|
||||
ldb.tokenize(CODE_TEXT, analyzer="code", split_identifiers=False)
|
||||
)
|
||||
split = _token_texts(
|
||||
ldb.tokenize(CODE_TEXT, analyzer="code", split_identifiers=True)
|
||||
)
|
||||
assert "parsehttprequest" in no_split
|
||||
assert "parse" not in no_split
|
||||
assert {"parse", "http", "request", "user", "id"} <= set(split)
|
||||
|
||||
numerics = _token_texts(
|
||||
ldb.tokenize(
|
||||
CODE_TEXT,
|
||||
analyzer="code",
|
||||
split_identifiers=True,
|
||||
split_on_numerics=True,
|
||||
)
|
||||
)
|
||||
no_numerics = _token_texts(
|
||||
ldb.tokenize(
|
||||
CODE_TEXT,
|
||||
analyzer="code",
|
||||
split_identifiers=True,
|
||||
split_on_numerics=False,
|
||||
)
|
||||
)
|
||||
assert "utf" in numerics and "8" in numerics
|
||||
assert "utf8" in no_numerics
|
||||
|
||||
operators = _token_texts(
|
||||
ldb.tokenize("a::b -> c != d", analyzer="code", index_operators=True)
|
||||
)
|
||||
plain = _token_texts(
|
||||
ldb.tokenize("a::b -> c != d", analyzer="code", index_operators=False)
|
||||
)
|
||||
assert {"::", "->", "!="} <= set(operators)
|
||||
assert not {"::", "->", "!="} & set(plain)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kwargs", "message"),
|
||||
[
|
||||
({"analyzer": "code", "base_tokenizer": "ngram"}, "requires base_tokenizer"),
|
||||
({"analyzer": "text", "base_tokenizer": "code"}, "requires analyzer='code'"),
|
||||
({"analyzer": "java"}, "analyzer must be"),
|
||||
({"split_identifiers": True}, "require analyzer='code'"),
|
||||
({"base_tokenizer": "raw", "index_operators": True}, "require analyzer='code'"),
|
||||
],
|
||||
)
|
||||
def test_code_analyzer_options_are_validated(mem_db, kwargs, message):
|
||||
with pytest.raises(ValueError, match=message):
|
||||
ldb.tokenize(CODE_TEXT, **kwargs)
|
||||
|
||||
table = mem_db.create_table("t", data=[{"text": CODE_TEXT}])
|
||||
with pytest.raises(ValueError, match=message):
|
||||
table.create_index("text", config=FTS(**kwargs))
|
||||
|
||||
|
||||
def test_code_analyzer_flags_false_are_allowed_for_text(mem_db):
|
||||
tokens = ldb.tokenize("Running in cafés", split_identifiers=False)
|
||||
assert _token_texts(tokens) == ["run", "cafe"]
|
||||
|
||||
|
||||
def test_fts_code_analyzer_index_matches_subwords(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"code",
|
||||
data=[{"text": "def parseHTTPRequest(user_id): pass"}, {"text": "unrelated"}],
|
||||
)
|
||||
table.create_index(
|
||||
"text",
|
||||
config=FTS(analyzer="code", split_identifiers=True, preserve_original=True),
|
||||
)
|
||||
|
||||
details = table.list_indices()[0].index_details
|
||||
assert details["base_tokenizer"] == "code"
|
||||
assert details["split_identifiers"] is True
|
||||
assert details["preserve_original"] is True
|
||||
|
||||
for query in ["http", "request", "parseHTTPRequest"]:
|
||||
rows = table.search(query, query_type="fts").to_list()
|
||||
assert [row["text"] for row in rows] == ["def parseHTTPRequest(user_id): pass"]
|
||||
|
||||
|
||||
def test_fts_code_analyzer_without_splitting_does_not_match_subwords(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"code", data=[{"text": "def parseHTTPRequest(user_id): pass"}]
|
||||
)
|
||||
table.create_index("text", config=FTS(analyzer="code", split_identifiers=False))
|
||||
|
||||
assert table.search("request", query_type="fts").to_list() == []
|
||||
assert len(table.search("parseHTTPRequest", query_type="fts").to_list()) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_fts_code_analyzer(mem_db_async):
|
||||
table = await mem_db_async.create_table(
|
||||
"code", data=[{"text": "def parseHTTPRequest(user_id): pass"}]
|
||||
)
|
||||
await table.create_index(
|
||||
"text", config=FTS(analyzer="code", split_identifiers=True)
|
||||
)
|
||||
|
||||
rows = await table.query().nearest_to_text("http").to_list()
|
||||
assert len(rows) == 1
|
||||
|
||||
@@ -20,7 +20,7 @@ import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
from lancedb import col
|
||||
from lancedb.functions import FunctionVersion, udf
|
||||
from lancedb.functions import FunctionDefinition, FunctionVersion, function
|
||||
|
||||
FIXTURES = (
|
||||
Path(__file__).parents[3]
|
||||
@@ -63,7 +63,7 @@ def helper_package(tmp_path, monkeypatch):
|
||||
return write
|
||||
|
||||
|
||||
@udf
|
||||
@function
|
||||
class scale:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -114,11 +114,11 @@ def test_class_function_declares_inputs_output_and_initialization():
|
||||
assert scale.registration_request.artifact.entrypoint == "scale"
|
||||
source = artifact(scale).decode()
|
||||
assert source.startswith("from __future__ import annotations\n")
|
||||
assert "class scale:" in source and "@udf" not in source
|
||||
assert "class scale:" in source and "@function" not in source
|
||||
|
||||
|
||||
def test_function_without_initialization_keeps_its_wire_form():
|
||||
@udf
|
||||
@function
|
||||
def double(value: int) -> int:
|
||||
return value * 2
|
||||
|
||||
@@ -147,11 +147,11 @@ def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_pac
|
||||
"""
|
||||
module = helper_package("fx_batch_annotations", {"__init__.py": source})
|
||||
with pytest.raises(TypeError, match="input_schema and output_schema"):
|
||||
udf(module.identity)
|
||||
function(module.identity)
|
||||
|
||||
|
||||
def test_array_batch_annotations_accept_explicit_schemas():
|
||||
@udf(
|
||||
@function(
|
||||
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
||||
output_schema=pa.int64(),
|
||||
)
|
||||
@@ -168,7 +168,7 @@ def test_array_batch_annotations_accept_explicit_schemas():
|
||||
assert identity(values).equals(values)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("class_udf", [False, True])
|
||||
@pytest.mark.parametrize("class_function", [False, True])
|
||||
@pytest.mark.parametrize("postponed", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("annotation", "nullable"),
|
||||
@@ -185,13 +185,13 @@ def test_array_batch_annotations_accept_explicit_schemas():
|
||||
],
|
||||
)
|
||||
def test_blob_reader_annotations_resolve_in_the_artifact(
|
||||
helper_package, monkeypatch, class_udf, postponed, annotation, nullable
|
||||
helper_package, monkeypatch, class_function, postponed, annotation, nullable
|
||||
):
|
||||
definition = (
|
||||
f"class read_blob:\n"
|
||||
f" def __call__(self, video: {annotation}) -> int:\n"
|
||||
f" return 0\n"
|
||||
if class_udf
|
||||
if class_function
|
||||
else f"def read_blob(video: {annotation}) -> int:\n return 0\n"
|
||||
)
|
||||
module = helper_package(
|
||||
@@ -202,9 +202,9 @@ def test_blob_reader_annotations_resolve_in_the_artifact(
|
||||
+ "import lancedb\n"
|
||||
"from typing import Optional\n"
|
||||
"from lancedb import BlobReader, BlobReader as Reader\n"
|
||||
"from lancedb.functions import udf\n"
|
||||
"from lancedb.functions import function\n"
|
||||
"MaybeReader = Optional[Reader]\n\n"
|
||||
f"@udf\n{definition}"
|
||||
f"@function\n{definition}"
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -221,7 +221,7 @@ def test_blob_reader_annotations_resolve_in_the_artifact(
|
||||
namespace = {}
|
||||
exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace)
|
||||
packaged = namespace["read_blob"]
|
||||
if class_udf:
|
||||
if class_function:
|
||||
packaged = packaged.__call__
|
||||
assert get_type_hints(packaged) == {
|
||||
"video": Optional[worker.BlobReader] if nullable else worker.BlobReader,
|
||||
@@ -237,11 +237,11 @@ def test_blob_reader_annotation_does_not_shadow_body_globals(
|
||||
{
|
||||
"__init__.py": """
|
||||
from lancedb import BlobReader
|
||||
from lancedb.functions import udf
|
||||
from lancedb.functions import function
|
||||
|
||||
_lance_blob_reader = 7
|
||||
|
||||
@udf
|
||||
@function
|
||||
def read_blob(video: BlobReader) -> int:
|
||||
return _lance_blob_reader
|
||||
"""
|
||||
@@ -280,14 +280,14 @@ def test_class_function_rejects_unsupported_initialization(init, message):
|
||||
namespace,
|
||||
)
|
||||
with pytest.raises((TypeError, ValueError), match=message):
|
||||
udf(namespace["bad"])
|
||||
function(namespace["bad"])
|
||||
|
||||
|
||||
def test_class_function_requires_call_and_a_plain_close():
|
||||
with pytest.raises(TypeError, match="synchronous __call__"):
|
||||
udf(NoCall)
|
||||
function(NoCall)
|
||||
with pytest.raises(TypeError, match="close must be a method taking no"):
|
||||
udf(BadClose)
|
||||
function(BadClose)
|
||||
|
||||
|
||||
def test_nested_class_and_closure_are_rejected_with_the_reason():
|
||||
@@ -299,13 +299,13 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
|
||||
return nested
|
||||
|
||||
with pytest.raises(ValueError, match="defined at module level"):
|
||||
udf(build())
|
||||
function(build())
|
||||
|
||||
factor = 3
|
||||
|
||||
with pytest.raises(ValueError, match="capture closure values"):
|
||||
|
||||
@udf
|
||||
@function
|
||||
def closes_over(value: int) -> int:
|
||||
return value * factor
|
||||
|
||||
@@ -372,10 +372,10 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
|
||||
"""
|
||||
import fx_helpers
|
||||
from fx_helpers.rate import TokenBucket
|
||||
from lancedb import udf
|
||||
from lancedb import function
|
||||
|
||||
|
||||
@udf(code=[fx_helpers])
|
||||
@function(code=[fx_helpers])
|
||||
class limited:
|
||||
def __init__(self, tpm: int):
|
||||
self.limiter = TokenBucket(tpm)
|
||||
@@ -388,9 +388,24 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
|
||||
|
||||
def define():
|
||||
sys.modules.pop("fx_helpers_functions", None)
|
||||
importlib.invalidate_caches()
|
||||
return importlib.import_module("fx_helpers_functions").limited
|
||||
|
||||
first = define()
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
first = define()
|
||||
assert len(caught) == 1
|
||||
warning = str(caught[0].message)
|
||||
assert "fx_helpers/fixtures/data.json" in warning
|
||||
assert "fx_helpers/not-a-module.py" in warning
|
||||
assert warning.index("fx_helpers/fixtures/data.json") < warning.index(
|
||||
"fx_helpers/not-a-module.py"
|
||||
)
|
||||
assert "remove 'fx_helpers' from code=" in warning
|
||||
assert "pip=" in warning
|
||||
assert "conda=" in warning
|
||||
assert "__pycache__" not in warning
|
||||
assert ".pyc" not in warning
|
||||
shipped = bundle_files(first)
|
||||
assert sorted(shipped) == [
|
||||
"fx_helpers/__init__.py",
|
||||
@@ -406,7 +421,10 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
|
||||
helper_package(
|
||||
"fx_helpers", {**files, "rate.py": textwrap.dedent(files["rate.py"]) + "# v2\n"}
|
||||
)
|
||||
second = define()
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
second = define()
|
||||
assert len(caught) == 1
|
||||
assert (
|
||||
first.registration_request.artifact.digest
|
||||
!= second.registration_request.artifact.digest
|
||||
@@ -414,6 +432,57 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
|
||||
assert first.registration_request.runtime == second.registration_request.runtime
|
||||
|
||||
|
||||
def test_code_package_cache_artifacts_do_not_warn(helper_package):
|
||||
cache = helper_package(
|
||||
"fx_cache",
|
||||
{
|
||||
"__init__.py": "",
|
||||
"__pycache__/ignored.cpython-312.pyc": "",
|
||||
"stale.pyo": "",
|
||||
},
|
||||
)
|
||||
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
|
||||
@function(code=[cache])
|
||||
def cache_only(value: int) -> int:
|
||||
return value
|
||||
|
||||
assert not caught
|
||||
assert sorted(bundle_files(cache_only)) == [
|
||||
"fx_cache/__init__.py",
|
||||
"user_function.py",
|
||||
]
|
||||
|
||||
|
||||
def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package):
|
||||
resources = helper_package(
|
||||
"fx_resources",
|
||||
{
|
||||
"__init__.py": "",
|
||||
"label-maps/labels.json": "{}",
|
||||
},
|
||||
)
|
||||
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
|
||||
@function(code=[resources])
|
||||
def resource_boundary(value: int) -> int:
|
||||
return value
|
||||
|
||||
assert len(caught) == 1
|
||||
warning = str(caught[0].message)
|
||||
assert "fx_resources/label-maps/" in warning
|
||||
assert "remove 'fx_resources' from code=" in warning
|
||||
assert "labels.json" not in warning
|
||||
assert sorted(bundle_files(resource_boundary)) == [
|
||||
"fx_resources/__init__.py",
|
||||
"user_function.py",
|
||||
]
|
||||
|
||||
|
||||
def test_code_rejects_submodules_duplicates_and_non_modules(helper_package):
|
||||
helpers = helper_package("fx_rejects", {"__init__.py": "", "sub.py": ""})
|
||||
import fx_rejects.sub
|
||||
@@ -426,7 +495,7 @@ def test_code_rejects_submodules_duplicates_and_non_modules(helper_package):
|
||||
]:
|
||||
with pytest.raises((TypeError, ValueError), match=message):
|
||||
|
||||
@udf(code=code)
|
||||
@function(code=code)
|
||||
def f(value: int) -> int:
|
||||
return value
|
||||
|
||||
@@ -445,15 +514,16 @@ def test_local_module_outside_code_warns_at_registration(tmp_path, helper_packag
|
||||
textwrap.dedent(
|
||||
f"""
|
||||
from fx_local import normalize
|
||||
from lancedb import udf
|
||||
from lancedb import function
|
||||
|
||||
|
||||
@udf({options})
|
||||
@function({options})
|
||||
def {name}(value: int) -> int:
|
||||
return normalize(value)
|
||||
"""
|
||||
)
|
||||
)
|
||||
importlib.invalidate_caches()
|
||||
return getattr(importlib.import_module(name), name)
|
||||
|
||||
with pytest.warns(UserWarning, match=r"local module.*code=\[fx_local\]"):
|
||||
@@ -467,6 +537,132 @@ def test_local_module_outside_code_warns_at_registration(tmp_path, helper_packag
|
||||
assert "from fx_local import normalize" in artifact(installed).decode()
|
||||
|
||||
|
||||
def test_local_module_imported_in_function_body_warns_at_registration(
|
||||
tmp_path, helper_package
|
||||
):
|
||||
"""A direct import inside the packaged definition is checked too."""
|
||||
helper_package(
|
||||
"fx_body_local",
|
||||
{"__init__.py": "def normalize(value):\n return value\n"},
|
||||
)
|
||||
sys.modules.pop("fx_body_local", None)
|
||||
|
||||
def define(name, options):
|
||||
(tmp_path / f"{name}.py").write_text(
|
||||
textwrap.dedent(
|
||||
f"""
|
||||
from lancedb import function
|
||||
|
||||
|
||||
@function({options})
|
||||
def {name}(value: int) -> int:
|
||||
import fx_body_local
|
||||
|
||||
return fx_body_local.normalize(value)
|
||||
"""
|
||||
)
|
||||
)
|
||||
importlib.invalidate_caches()
|
||||
return getattr(importlib.import_module(name), name)
|
||||
|
||||
with pytest.warns(UserWarning, match=r"local module.*code=\[fx_body_local\]"):
|
||||
local = define("fx_body_uses_local", "")
|
||||
assert "import fx_body_local" in artifact(local).decode()
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error")
|
||||
installed = define("fx_body_uses_installed", "pip=['fx-body-local==1.0']")
|
||||
assert "import fx_body_local" in artifact(installed).decode()
|
||||
|
||||
|
||||
def test_missing_module_without_declared_package_warns_at_registration(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
package = "fx_missing_remote_package_ent3448"
|
||||
monkeypatch.syspath_prepend(str(tmp_path))
|
||||
|
||||
def define(name):
|
||||
(tmp_path / f"{name}.py").write_text(
|
||||
textwrap.dedent(
|
||||
f"""
|
||||
from lancedb import function
|
||||
|
||||
|
||||
@function(pip=())
|
||||
def {name}(value: int) -> int:
|
||||
import {package}.plugin
|
||||
|
||||
return value
|
||||
"""
|
||||
)
|
||||
)
|
||||
importlib.invalidate_caches()
|
||||
return getattr(importlib.import_module(name), name)
|
||||
|
||||
with pytest.warns(UserWarning) as caught:
|
||||
definition = define("fx_uses_missing_package")
|
||||
|
||||
message = str(caught[0].message)
|
||||
assert f"imports {package!r}" in message
|
||||
assert "unavailable in the client environment" in message
|
||||
assert "no declared pip/conda dependencies" in message
|
||||
assert "Remote availability cannot be verified" in message
|
||||
assert "confirm that the base image provides it" in message
|
||||
assert "cannot import" not in message
|
||||
assert f"import {package}.plugin" in artifact(definition).decode()
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", UserWarning)
|
||||
with pytest.raises(UserWarning, match="Remote availability cannot be verified"):
|
||||
define("fx_missing_package_as_error")
|
||||
|
||||
|
||||
def test_resolved_or_declared_module_imports_do_not_warn(tmp_path, helper_package):
|
||||
package = "fx_missing_remote_package_ent3448"
|
||||
helper_package("fx_declared_code_package", {"__init__.py": ""})
|
||||
|
||||
def define(name, body, options, imports=""):
|
||||
(tmp_path / f"{name}.py").write_text(
|
||||
textwrap.dedent(
|
||||
f"""
|
||||
{imports}
|
||||
from lancedb import function
|
||||
|
||||
|
||||
@function({options})
|
||||
def {name}(value: int) -> int:
|
||||
{body}
|
||||
return value
|
||||
"""
|
||||
)
|
||||
)
|
||||
importlib.invalidate_caches()
|
||||
return getattr(importlib.import_module(name), name)
|
||||
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
define("fx_imports_stdlib", "import os.path", "")
|
||||
# Distribution names need not match the imported top-level module.
|
||||
define(
|
||||
"fx_imports_declared_pip",
|
||||
f"import {package}.plugin",
|
||||
"pip=['Pillow>=10']",
|
||||
)
|
||||
define(
|
||||
"fx_imports_declared_conda",
|
||||
f"import {package}.plugin",
|
||||
"conda=['numpy']",
|
||||
)
|
||||
define(
|
||||
"fx_imports_shipped_code",
|
||||
"import fx_declared_code_package",
|
||||
"code=[fx_declared_code_package]",
|
||||
"import fx_declared_code_package",
|
||||
)
|
||||
|
||||
assert not caught
|
||||
|
||||
|
||||
MMLB_HELPERS = {
|
||||
"__init__.py": "",
|
||||
"rate.py": """
|
||||
@@ -502,20 +698,20 @@ import pyarrow as pa
|
||||
|
||||
import fx_mmlb
|
||||
from fx_mmlb.embedding import OpenAIEmbedder
|
||||
from lancedb import udf
|
||||
from lancedb import function
|
||||
|
||||
TEXT = pa.schema([pa.field("text", pa.string())])
|
||||
EMBEDDING = pa.list_(pa.field("item", pa.float64(), nullable=False))
|
||||
|
||||
|
||||
@udf(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING)
|
||||
@function(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING)
|
||||
class openai_embedding_batch(OpenAIEmbedder):
|
||||
def __call__(self, text: pa.Array) -> pa.Array:
|
||||
item = pa.field("item", pa.float64(), nullable=False)
|
||||
return pa.array(self.embed(text.to_pylist()), pa.list_(item))
|
||||
|
||||
|
||||
@udf(code=[fx_mmlb])
|
||||
@function(code=[fx_mmlb])
|
||||
class openai_embedding(OpenAIEmbedder):
|
||||
def __call__(self, text: str) -> list[float]:
|
||||
return self.embed([text])[0]
|
||||
@@ -527,6 +723,7 @@ def test_shared_helpers_construct_state_on_every_path(tmp_path, helper_package):
|
||||
initialized through the same helper, so neither path can skip it."""
|
||||
helper_package("fx_mmlb", MMLB_HELPERS)
|
||||
(tmp_path / "fx_mmlb_functions.py").write_text(MMLB_FUNCTIONS)
|
||||
importlib.invalidate_caches()
|
||||
functions = importlib.import_module("fx_mmlb_functions")
|
||||
|
||||
signatures = [
|
||||
@@ -586,7 +783,7 @@ def test_main_definitions_travel_by_source(tmp_path):
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
from lancedb import udf
|
||||
from lancedb import function
|
||||
|
||||
SCALE = 2
|
||||
|
||||
@@ -605,7 +802,7 @@ def test_main_definitions_travel_by_source(tmp_path):
|
||||
return helper(value) * self.settings.factor
|
||||
|
||||
|
||||
@udf
|
||||
@function
|
||||
class scaled(Base):
|
||||
def __init__(self, factor: int):
|
||||
self.settings = Settings(factor)
|
||||
@@ -641,11 +838,11 @@ def test_main_lambdas_are_rejected(tmp_path):
|
||||
script.write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
from lancedb import udf
|
||||
from lancedb import function
|
||||
|
||||
double = lambda value: value * 2
|
||||
|
||||
@udf
|
||||
@function
|
||||
def uses_lambda(value: int) -> int:
|
||||
return double(value)
|
||||
"""
|
||||
@@ -656,3 +853,33 @@ def test_main_lambdas_are_rejected(tmp_path):
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert "not lambdas, closures, or nested definitions" in result.stderr
|
||||
|
||||
|
||||
def test_udf_alias_warns_and_packages_like_function(helper_package):
|
||||
def source(decorator: str) -> str:
|
||||
return f"""
|
||||
import lancedb
|
||||
from lancedb import function, udf
|
||||
|
||||
@{decorator}
|
||||
def double(value: int) -> int:
|
||||
return value * 2
|
||||
"""
|
||||
|
||||
current = helper_package("fx_alias_current", {"__init__.py": source("function")})
|
||||
expected = current.double.registration_request.artifact.digest
|
||||
for name, decorator in (("fx_alias_bare", "udf"), ("fx_alias_attr", "lancedb.udf")):
|
||||
with pytest.warns(DeprecationWarning, match="lancedb.udf is deprecated"):
|
||||
module = helper_package(name, {"__init__.py": source(decorator)})
|
||||
assert isinstance(module.double, FunctionDefinition)
|
||||
assert "udf" not in artifact(module.double).decode()
|
||||
assert module.double.registration_request.artifact.digest == expected
|
||||
|
||||
|
||||
def test_udf_definition_alias_warns():
|
||||
with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"):
|
||||
from lancedb import UdfDefinition
|
||||
assert UdfDefinition is FunctionDefinition
|
||||
with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"):
|
||||
from lancedb.functions import UdfDefinition as module_alias
|
||||
assert module_alias is FunctionDefinition
|
||||
|
||||
@@ -103,6 +103,7 @@ async def test_async_hybrid_query_filters(table: AsyncTable):
|
||||
async def test_hybrid_query_with_stale_fixed_size_binary_prefilter(
|
||||
tmpdir_factory,
|
||||
):
|
||||
pytest.importorskip("lance")
|
||||
tmp_path = str(tmpdir_factory.mktemp("stale_scalar_prefilter"))
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
|
||||
|
||||
@@ -34,9 +34,23 @@ def test_native_extension_does_not_link_openssl():
|
||||
)
|
||||
|
||||
|
||||
def test_top_level_version_comes_from_native_module():
|
||||
@pytest.mark.parametrize(
|
||||
"native_version, expected_version",
|
||||
[
|
||||
("0.41.0", "0.41.0"),
|
||||
("0.41.0-alpha.1", "0.41.0a1"),
|
||||
("0.41.0-beta.17", "0.41.0b17"),
|
||||
("0.41.0-rc.1", "0.41.0rc1"),
|
||||
("0.41.0-dev.1", "0.41.0.dev1"),
|
||||
],
|
||||
)
|
||||
def test_top_level_version_comes_from_native_module(native_version, expected_version):
|
||||
child_code = """
|
||||
import importlib
|
||||
import importlib.metadata
|
||||
import sys
|
||||
|
||||
from packaging.version import Version
|
||||
|
||||
orig_version = importlib.metadata.version
|
||||
|
||||
@@ -51,13 +65,17 @@ import lancedb
|
||||
import lancedb._lancedb as native_module
|
||||
import lancedb.db
|
||||
|
||||
assert lancedb.__version__ == native_module.__version__
|
||||
assert lancedb.__version__ == str(Version(native_module.__version__))
|
||||
|
||||
native_module.__version__ = sys.argv[1]
|
||||
importlib.reload(lancedb)
|
||||
assert lancedb.__version__ == sys.argv[2]
|
||||
"""
|
||||
env = os.environ.copy()
|
||||
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", child_code],
|
||||
[sys.executable, "-c", child_code, native_version, expected_version],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
|
||||
@@ -21,6 +21,7 @@ from lancedb.index import (
|
||||
Bitmap,
|
||||
LabelList,
|
||||
Fm,
|
||||
NGram,
|
||||
HnswPq,
|
||||
HnswSq,
|
||||
HnswFlat,
|
||||
@@ -248,6 +249,36 @@ async def test_create_fm_index(some_table: AsyncTable):
|
||||
assert indices[0].columns == ["data"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_ngram_index(db_async):
|
||||
# NGram indexes accelerate substring filters on UTF-8 string columns.
|
||||
data = pa.table(
|
||||
{
|
||||
"id": list(range(5)),
|
||||
"text": ["cat", "category", "concatenate", "dog", "cathedral"],
|
||||
}
|
||||
)
|
||||
table = await db_async.create_table("ngram_table", data)
|
||||
await table.create_index("text", config=NGram())
|
||||
|
||||
indices = await table.list_indices()
|
||||
assert len(indices) == 1
|
||||
assert indices[0].index_type == "NGram"
|
||||
assert indices[0].columns == ["text"]
|
||||
|
||||
stats = await table.index_stats(indices[0].name)
|
||||
assert stats.index_type == "NGRAM"
|
||||
assert stats.num_indexed_rows == await table.count_rows()
|
||||
assert stats.num_unindexed_rows == 0
|
||||
|
||||
# The index accelerates substring predicates without changing their results.
|
||||
result = await table.query().where("contains(text, 'cat')").to_arrow()
|
||||
assert sorted(result["id"].to_pylist()) == [0, 1, 2, 4]
|
||||
|
||||
plan = await table.query().where("contains(text, 'cat')").explain_plan()
|
||||
assert "ScalarIndexQuery" in plan
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_bitmap_index(some_table: AsyncTable):
|
||||
await some_table.create_index("id", config=Bitmap())
|
||||
@@ -559,6 +590,7 @@ def test_index_statistics_index_type_lists_all_supported_values():
|
||||
"BTREE",
|
||||
"BITMAP",
|
||||
"LABEL_LIST",
|
||||
"NGRAM",
|
||||
}
|
||||
|
||||
assert (
|
||||
|
||||
@@ -0,0 +1,708 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from lancedb.exceptions import JobCancelledError, JobFailedError
|
||||
from lancedb.job import AsyncJob, Job, _progress_eta
|
||||
from lancedb.remote.errors import HttpError, RetryError
|
||||
|
||||
|
||||
@pytest.fixture(params=["async", "sync"])
|
||||
def wait_job(request):
|
||||
async def wait(inner, timeout=None, result_decoder=None):
|
||||
job = AsyncJob(inner, result_decoder)
|
||||
if request.param == "sync":
|
||||
return await asyncio.to_thread(Job(job).wait, timeout)
|
||||
return await job.wait(timeout)
|
||||
|
||||
return wait
|
||||
|
||||
|
||||
def transport_error(kind):
|
||||
if kind == "http":
|
||||
return HttpError("error sending request", "req-1", is_transport_error=True)
|
||||
error = RetryError("retries exhausted", "req-1", 0, 3, 0, 3, 3, 3, None)
|
||||
error.__cause__ = transport_error("http")
|
||||
return error
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("kind", ["http", "retry"])
|
||||
async def test_wait_recovers_from_transport_errors(wait_job, kind, monkeypatch):
|
||||
inner = MagicMock(id="job-1", job_type=None)
|
||||
inner.wait = AsyncMock(side_effect=[transport_error(kind), '{"rows": 7}'])
|
||||
inner.status = AsyncMock(side_effect=[transport_error(kind), "running"])
|
||||
sleep = AsyncMock()
|
||||
monkeypatch.setattr("lancedb.job.asyncio.sleep", sleep)
|
||||
|
||||
result = await wait_job(
|
||||
inner, timedelta(hours=24), result_decoder=lambda value: ("decoded", value)
|
||||
)
|
||||
|
||||
assert result == ("decoded", '{"rows": 7}')
|
||||
assert inner.wait.await_count == 2
|
||||
assert inner.status.await_count == 2
|
||||
assert [call.args[0] for call in sleep.await_args_list] == [0.25, 0.5]
|
||||
inner.cancel.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_disconnection_timeout_explains_how_to_reconnect(wait_job):
|
||||
error = transport_error("http")
|
||||
inner = MagicMock(id="job-1", job_type=None)
|
||||
inner.wait = AsyncMock(side_effect=error)
|
||||
inner.status = AsyncMock(side_effect=error)
|
||||
|
||||
with pytest.raises(
|
||||
ConnectionError, match="job 'job-1' may still be running"
|
||||
) as exc:
|
||||
await wait_job(inner, timedelta(milliseconds=10))
|
||||
|
||||
assert "db.open_job('job-1')" in str(exc.value)
|
||||
assert "call wait()" in str(exc.value)
|
||||
assert exc.value.__cause__ is error
|
||||
inner.cancel.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
HttpError("unauthorized", "req-1", 401),
|
||||
HttpError("not found", "req-1", 404),
|
||||
HttpError(
|
||||
"secret not found",
|
||||
"req-1",
|
||||
404,
|
||||
error_code="not_found",
|
||||
resource_kind="secret",
|
||||
),
|
||||
HttpError("failed to parse job description", "req-1"),
|
||||
RetryError("service unavailable", "req-1", 3, 0, 0, 3, 3, 3, 503),
|
||||
JobFailedError("worker failed"),
|
||||
JobCancelledError("job cancelled"),
|
||||
],
|
||||
)
|
||||
async def test_wait_propagates_permanent_and_terminal_errors(wait_job, error):
|
||||
inner = MagicMock(id="job-1")
|
||||
inner.wait = AsyncMock(side_effect=error)
|
||||
|
||||
with pytest.raises(type(error)) as exc:
|
||||
await wait_job(inner, timedelta(seconds=1))
|
||||
|
||||
assert exc.value is error
|
||||
assert inner.wait.await_count == 1
|
||||
inner.status.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_running_job_timeout_is_not_a_connection_error(wait_job):
|
||||
async def running():
|
||||
await asyncio.Event().wait()
|
||||
|
||||
inner = MagicMock(id="job-1")
|
||||
inner.wait = AsyncMock(side_effect=running)
|
||||
with pytest.raises(TimeoutError):
|
||||
await wait_job(inner, timedelta(milliseconds=10))
|
||||
inner.cancel.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_completed_job(wait_job):
|
||||
assert await wait_job(None) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_retries_without_a_timeout_and_caps_backoff(wait_job, monkeypatch):
|
||||
inner = MagicMock(id="job-1", job_type=None)
|
||||
inner.wait = AsyncMock(side_effect=[transport_error("http"), None])
|
||||
inner.status = AsyncMock(side_effect=[transport_error("retry")] * 9 + ["running"])
|
||||
sleep = AsyncMock()
|
||||
monkeypatch.setattr("lancedb.job.asyncio.sleep", sleep)
|
||||
|
||||
assert await wait_job(inner) is None
|
||||
assert [call.args[0] for call in sleep.await_args_list] == [
|
||||
0.25,
|
||||
0.5,
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
8,
|
||||
16,
|
||||
30,
|
||||
30,
|
||||
30,
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("job_type", [None, "query"])
|
||||
async def test_wait_timeout_after_recovery_is_not_a_connection_error(
|
||||
wait_job, monkeypatch, job_type
|
||||
):
|
||||
async def running():
|
||||
await asyncio.Event().wait()
|
||||
|
||||
inner = MagicMock(id="job-1", job_type=job_type)
|
||||
inner.wait = AsyncMock()
|
||||
|
||||
async def wait():
|
||||
if inner.wait.await_count == 1:
|
||||
raise transport_error("http")
|
||||
return await running()
|
||||
|
||||
inner.wait.side_effect = wait
|
||||
inner.status = AsyncMock(return_value="running")
|
||||
monkeypatch.setattr("lancedb.job.asyncio.sleep", AsyncMock())
|
||||
|
||||
with pytest.raises(TimeoutError) as exc:
|
||||
await wait_job(inner, timedelta(milliseconds=10))
|
||||
message = str(exc.value)
|
||||
assert "still running after 0.01 seconds" in message
|
||||
assert "continues on the server" in message
|
||||
if job_type == "query":
|
||||
assert "keep this handle to continue waiting" in message
|
||||
assert "db.open_job" not in message
|
||||
else:
|
||||
assert "db.open_job('job-1').wait()" in message
|
||||
assert inner.status.await_count == 1
|
||||
assert inner.wait.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"error", [JobFailedError("failed"), JobCancelledError("cancel")]
|
||||
)
|
||||
async def test_wait_reports_terminal_error_after_recovery(wait_job, monkeypatch, error):
|
||||
inner = MagicMock(id="job-1", job_type=None)
|
||||
inner.wait = AsyncMock(side_effect=[transport_error("retry"), error])
|
||||
inner.status = AsyncMock(return_value="running")
|
||||
monkeypatch.setattr("lancedb.job.asyncio.sleep", AsyncMock())
|
||||
|
||||
with pytest.raises(type(error)) as exc:
|
||||
await wait_job(inner, timedelta(seconds=1))
|
||||
assert exc.value is error
|
||||
assert inner.wait.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_cancellation_interrupts_backoff(monkeypatch):
|
||||
inner = MagicMock(id="job-1", job_type=None)
|
||||
inner.wait = AsyncMock(side_effect=transport_error("http"))
|
||||
sleeping = asyncio.Event()
|
||||
|
||||
async def sleep(delay):
|
||||
sleeping.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
monkeypatch.setattr("lancedb.job.asyncio.sleep", sleep)
|
||||
task = asyncio.create_task(AsyncJob(inner).wait())
|
||||
await asyncio.wait_for(sleeping.wait(), 1)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
inner.cancel.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_wait_disconnection_does_not_suggest_open_job(wait_job):
|
||||
inner = MagicMock(id="query-1", job_type="query")
|
||||
inner.wait = AsyncMock(side_effect=transport_error("http"))
|
||||
|
||||
with pytest.raises(ConnectionError) as exc:
|
||||
await wait_job(inner, timedelta(milliseconds=10))
|
||||
|
||||
assert "query-1" in str(exc.value)
|
||||
assert "this job handle" in str(exc.value)
|
||||
assert "open_job" not in str(exc.value)
|
||||
|
||||
|
||||
class _PendingJob:
|
||||
id = "job-timeout"
|
||||
job_type = None
|
||||
|
||||
async def wait(self):
|
||||
await asyncio.sleep(60)
|
||||
|
||||
|
||||
class _PendingQuery:
|
||||
id = "query-timeout"
|
||||
job_type = "query"
|
||||
|
||||
async def wait(self):
|
||||
await asyncio.sleep(60)
|
||||
|
||||
|
||||
class _ProgressJob:
|
||||
id = "job-progress"
|
||||
job_type = "refresh_column"
|
||||
|
||||
async def status(self):
|
||||
return "finished"
|
||||
|
||||
async def wait(self, progress=None):
|
||||
if progress is not None:
|
||||
progress({"state": "running", "rows_planned": 4, "rows_computed": 2})
|
||||
progress({"state": "finished", "rows_planned": 4, "rows_computed": 4})
|
||||
return None
|
||||
|
||||
|
||||
def _assert_timeout(error: TimeoutError) -> None:
|
||||
message = str(error)
|
||||
assert "job 'job-timeout' still running after 0.01 seconds" in message
|
||||
assert "continues on the server" in message
|
||||
assert "db.open_job('job-timeout').wait()" in message
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_job_wait_timeout_explains_reattach():
|
||||
job = AsyncJob(_PendingJob())
|
||||
|
||||
with pytest.raises(TimeoutError) as exc_info:
|
||||
await job.wait(timeout=timedelta(seconds=0.01))
|
||||
|
||||
_assert_timeout(exc_info.value)
|
||||
|
||||
|
||||
def test_job_wait_timeout_explains_reattach():
|
||||
job = Job(AsyncJob(_PendingJob()))
|
||||
|
||||
with pytest.raises(TimeoutError) as exc_info:
|
||||
job.wait(timeout=timedelta(seconds=0.01))
|
||||
|
||||
_assert_timeout(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_progress_is_additive_to_string_status_and_returns_none_locally():
|
||||
inner = MagicMock(id="job-progress", job_type="refresh_column")
|
||||
inner.status = AsyncMock(return_value="running")
|
||||
inner._description = type(
|
||||
"Description", (), {"progress": {"state": "running", "rows_computed": 2}}
|
||||
)()
|
||||
job = AsyncJob(inner)
|
||||
|
||||
assert await job.status() == "running"
|
||||
assert await job.progress() == {"state": "running", "rows_computed": 2}
|
||||
assert await AsyncJob(None).progress() is None
|
||||
assert await AsyncJob(_ProgressJob()).progress() is None
|
||||
assert Job(AsyncJob(None)).progress() is None
|
||||
|
||||
|
||||
def test_progress_eta_uses_two_stable_advancing_same_epoch_samples():
|
||||
now = int(time.time() * 1_000)
|
||||
previous = {
|
||||
"state": "running",
|
||||
"execution_epoch": 7,
|
||||
"sample_at_millis": now - 1_000,
|
||||
"rows_planned": 100,
|
||||
"rows_computed": 20,
|
||||
"rows_skipped": 0,
|
||||
"rows_remaining": 80,
|
||||
"fragments_planned": 4,
|
||||
}
|
||||
current = {
|
||||
**previous,
|
||||
"sample_at_millis": now,
|
||||
"rows_computed": 40,
|
||||
"rows_remaining": 60,
|
||||
}
|
||||
assert _progress_eta(previous, current) == 3_000
|
||||
assert _progress_eta(previous, {**current, "rows_planned": 120}) is None
|
||||
assert _progress_eta(previous, {**current, "execution_epoch": 8}) is None
|
||||
assert _progress_eta(previous, {**current, "rows_computed": 20}) is None
|
||||
stale = {
|
||||
**current,
|
||||
"sample_at_millis": now - 11 * 60 * 1_000,
|
||||
}
|
||||
assert (
|
||||
_progress_eta({**previous, "sample_at_millis": now - 12 * 60 * 1_000}, stale)
|
||||
is None
|
||||
)
|
||||
assert _progress_eta(previous, {**current, "state": "finished"}) is None
|
||||
assert (
|
||||
_progress_eta(previous, {**current, "state": "finished", "rows_remaining": 0})
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_progress_retains_eta_from_same_handle_observations():
|
||||
now = int(time.time() * 1_000)
|
||||
first = {
|
||||
"state": "running",
|
||||
"execution_epoch": 7,
|
||||
"sample_at_millis": now - 1_000,
|
||||
"rows_planned": 100,
|
||||
"rows_computed": 20,
|
||||
"rows_skipped": 0,
|
||||
"rows_remaining": 80,
|
||||
"fragments_planned": 4,
|
||||
}
|
||||
second = {
|
||||
**first,
|
||||
"sample_at_millis": now,
|
||||
"rows_computed": 40,
|
||||
"rows_remaining": 60,
|
||||
}
|
||||
inner = MagicMock(id="job-progress", job_type="refresh_column")
|
||||
inner.status = AsyncMock(return_value="running")
|
||||
description = type("Description", (), {"progress": first})()
|
||||
inner._description = description
|
||||
job = AsyncJob(inner)
|
||||
|
||||
assert await job.progress() == first
|
||||
description.progress = second
|
||||
assert (await job.progress())["estimated_remaining_time_millis"] == 3_000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_callback_observes_backend_poll_updates():
|
||||
updates = []
|
||||
|
||||
result = await AsyncJob(_ProgressJob()).wait(progress=updates.append)
|
||||
|
||||
assert result is None
|
||||
assert updates == [
|
||||
{"state": "running", "rows_planned": 4, "rows_computed": 2},
|
||||
{"state": "finished", "rows_planned": 4, "rows_computed": 4},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_callback_uses_the_public_eta_enrichment(monkeypatch):
|
||||
now = 10_000_000
|
||||
monkeypatch.setattr("lancedb.job.time.time", lambda: now / 1_000)
|
||||
|
||||
class EtaJob:
|
||||
id = "job-eta"
|
||||
job_type = "refresh_column"
|
||||
|
||||
async def wait(self, progress):
|
||||
first = {
|
||||
"state": "running",
|
||||
"execution_epoch": 7,
|
||||
"sample_at_millis": now - 1_000,
|
||||
"rows_planned": 100,
|
||||
"rows_computed": 20,
|
||||
"rows_skipped": 0,
|
||||
"rows_remaining": 80,
|
||||
"fragments_planned": 4,
|
||||
}
|
||||
progress(first)
|
||||
progress(
|
||||
{
|
||||
**first,
|
||||
"sample_at_millis": now,
|
||||
"rows_computed": 40,
|
||||
"rows_remaining": 60,
|
||||
}
|
||||
)
|
||||
|
||||
updates = []
|
||||
assert await AsyncJob(EtaJob()).wait(progress=updates.append) is None
|
||||
|
||||
assert "estimated_remaining_time_millis" not in updates[0]
|
||||
assert updates[1]["estimated_remaining_time_millis"] == 3_000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_true_updates_and_closes_only_the_owned_bar(monkeypatch):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
def __init__(self):
|
||||
self.total = None
|
||||
self.updates = []
|
||||
self.phases = []
|
||||
self.closed = False
|
||||
|
||||
def update(self, delta):
|
||||
self.updates.append(delta)
|
||||
|
||||
def set_postfix_str(self, phase):
|
||||
self.phases.append(phase)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
assert await AsyncJob(_ProgressJob()).wait(progress=True) is None
|
||||
assert bar.total == 4
|
||||
assert bar.updates == [2, 2]
|
||||
assert bar.phases == ["running", "finished"]
|
||||
assert bar.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_bar_resumes_caller_owned_bar_after_timeout():
|
||||
class ResumableJob:
|
||||
id = "job-resume"
|
||||
job_type = "refresh_column"
|
||||
|
||||
def __init__(self, bar):
|
||||
self.calls = 0
|
||||
self.bar = bar
|
||||
|
||||
async def wait(self, progress):
|
||||
self.calls += 1
|
||||
if self.calls == 1:
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"execution_epoch": 1,
|
||||
"rows_planned": 4,
|
||||
"rows_remaining": 2,
|
||||
}
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
else:
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"execution_epoch": 2,
|
||||
"rows_planned": 4,
|
||||
"rows_remaining": 3,
|
||||
}
|
||||
)
|
||||
assert self.bar.n == 1
|
||||
progress(
|
||||
{
|
||||
"state": "finished",
|
||||
"execution_epoch": 2,
|
||||
"rows_planned": 4,
|
||||
"rows_remaining": 0,
|
||||
}
|
||||
)
|
||||
|
||||
class Bar:
|
||||
def __init__(self):
|
||||
self.total = None
|
||||
self.n = 0
|
||||
self.updates = []
|
||||
|
||||
def update(self, delta):
|
||||
self.updates.append(delta)
|
||||
self.n += delta
|
||||
|
||||
def set_postfix_str(self, _phase):
|
||||
pass
|
||||
|
||||
bar = Bar()
|
||||
job = AsyncJob(ResumableJob(bar))
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
await job.wait(timeout=timedelta(seconds=0.01), progress=bar)
|
||||
|
||||
assert await job.wait(progress=bar) is None
|
||||
assert bar.total == 4
|
||||
assert bar.n == 4
|
||||
assert bar.updates == [2, 3]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_bar_resets_display_for_new_plan_or_epoch():
|
||||
class ReplannedJob:
|
||||
id = "job-replanned"
|
||||
job_type = "refresh_column"
|
||||
|
||||
async def wait(self, progress):
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"execution_epoch": 1,
|
||||
"rows_planned": 6,
|
||||
"rows_remaining": 2,
|
||||
}
|
||||
)
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"execution_epoch": 1,
|
||||
"rows_planned": 4,
|
||||
"rows_remaining": 3,
|
||||
}
|
||||
)
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"execution_epoch": 2,
|
||||
"rows_planned": 4,
|
||||
"rows_remaining": 3,
|
||||
}
|
||||
)
|
||||
progress(
|
||||
{
|
||||
"state": "finished",
|
||||
"execution_epoch": 2,
|
||||
"rows_planned": 4,
|
||||
"rows_remaining": 0,
|
||||
}
|
||||
)
|
||||
|
||||
class Bar:
|
||||
def __init__(self):
|
||||
self.total = None
|
||||
self.n = 0
|
||||
self.updates = []
|
||||
self.resets = []
|
||||
|
||||
def update(self, delta):
|
||||
self.updates.append(delta)
|
||||
self.n += delta
|
||||
|
||||
def reset(self, total=None):
|
||||
self.resets.append(total)
|
||||
self.total = total
|
||||
self.n = 0
|
||||
|
||||
def set_postfix_str(self, _phase):
|
||||
pass
|
||||
|
||||
bar = Bar()
|
||||
|
||||
assert await AsyncJob(ReplannedJob()).wait(progress=bar) is None
|
||||
assert bar.total == 4
|
||||
assert bar.n == 4
|
||||
assert bar.n <= bar.total
|
||||
assert bar.resets == [4, 4]
|
||||
assert bar.updates == [4, 1, 1, 3]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_bar_uses_remaining_rows_when_computation_is_repeated(
|
||||
monkeypatch,
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
def __init__(self):
|
||||
self.total = None
|
||||
self.updates = []
|
||||
self.closed = False
|
||||
|
||||
def update(self, delta):
|
||||
self.updates.append(delta)
|
||||
|
||||
def set_postfix_str(self, _phase):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
class RepeatedComputationJob:
|
||||
id = "job-recomputed"
|
||||
job_type = "refresh_column"
|
||||
|
||||
async def wait(self, progress):
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"rows_planned": 4,
|
||||
"rows_computed": 6,
|
||||
"rows_remaining": 2,
|
||||
}
|
||||
)
|
||||
progress(
|
||||
{
|
||||
"state": "finished",
|
||||
"rows_planned": 4,
|
||||
"rows_computed": 8,
|
||||
"rows_remaining": 0,
|
||||
}
|
||||
)
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
assert await AsyncJob(RepeatedComputationJob()).wait(progress=True) is None
|
||||
assert bar.total == 4
|
||||
assert bar.updates == [2, 2]
|
||||
assert bar.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_bar_tracks_late_planning_without_regressing(
|
||||
monkeypatch,
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
|
||||
class Bar:
|
||||
def __init__(self):
|
||||
self.total = None
|
||||
self.updates = []
|
||||
self.closed = False
|
||||
|
||||
def update(self, delta):
|
||||
self.updates.append(delta)
|
||||
|
||||
def set_postfix_str(self, _phase):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
class RegressingPlanJob:
|
||||
id = "job-regressing-plan"
|
||||
job_type = "refresh_column"
|
||||
|
||||
async def wait(self, progress):
|
||||
samples = [
|
||||
(0, 0),
|
||||
(4, 2),
|
||||
(4, 3),
|
||||
(4, 2),
|
||||
(6, 1),
|
||||
(6, 0),
|
||||
]
|
||||
for planned, remaining in samples:
|
||||
progress(
|
||||
{
|
||||
"state": "running",
|
||||
"rows_planned": planned,
|
||||
"rows_remaining": remaining,
|
||||
}
|
||||
)
|
||||
|
||||
bar = Bar()
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", lambda **kwargs: bar)
|
||||
|
||||
assert await AsyncJob(RegressingPlanJob()).wait(progress=True) is None
|
||||
assert bar.total == 6
|
||||
# The remaining-row dip at (4, 3) must not rewind the high-water mark.
|
||||
assert bar.updates == [2, 3, 1]
|
||||
assert bar.closed
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
|
||||
class NoProgressArgument:
|
||||
id = "job-legacy"
|
||||
job_type = None
|
||||
|
||||
async def wait(self):
|
||||
return None
|
||||
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_wait_timeout_requires_keeping_original_handle():
|
||||
job = AsyncJob(_PendingQuery())
|
||||
|
||||
with pytest.raises(TimeoutError) as exc_info:
|
||||
await job.wait(timeout=timedelta(seconds=0.01))
|
||||
|
||||
message = str(exc_info.value)
|
||||
assert "query 'query-timeout' still running after 0.01 seconds" in message
|
||||
assert "continues on the server" in message
|
||||
assert "keep this handle to continue waiting" in message
|
||||
assert "db.open_job" not in message
|
||||
@@ -84,7 +84,7 @@ async def advance(items, asynchronous):
|
||||
return await items.__anext__() if asynchronous else next(items)
|
||||
|
||||
|
||||
KINDS = ["secrets", "views", "jobs", "functions"]
|
||||
KINDS = ["jobs"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -63,7 +63,17 @@ def mock_remote_materialized_view_refresh():
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
@pytest.mark.parametrize("background", [False, True])
|
||||
@pytest.mark.parametrize("full", [False, True])
|
||||
async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
@pytest.mark.parametrize(
|
||||
"resources",
|
||||
[
|
||||
{},
|
||||
{"gpu_count": 2, "gpu_class": "h100"},
|
||||
{"cpu_millis": 8000, "memory_bytes": 16 * 1024**3, "gpu_count": 0},
|
||||
],
|
||||
)
|
||||
async def test_remote_refresh_reports_unknown_metrics(
|
||||
sync, background, full, resources
|
||||
):
|
||||
flight = pytest.importorskip("pyarrow.flight")
|
||||
|
||||
class RefreshServer(flight.FlightServerBase):
|
||||
@@ -90,7 +100,7 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
mock_remote_materialized_view_refresh() as (host, requests),
|
||||
RefreshServer() as server,
|
||||
):
|
||||
options = {"full": True} if full else {}
|
||||
options = {"full": full, **resources}
|
||||
connect = lancedb.connect if sync else lancedb.connect_async
|
||||
db = connect(
|
||||
"db://dev",
|
||||
@@ -140,7 +150,28 @@ async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
|
||||
)
|
||||
(refresh,) = refreshes
|
||||
assert b'REFRESH MATERIALIZED VIEW "view"' in refresh
|
||||
assert (b"WITH (full = true)" in refresh) is full
|
||||
assert (b"full = true" in refresh) is full
|
||||
for key, value in resources.items():
|
||||
expected = (
|
||||
f"{key} = '{value}'" if key == "gpu_class" else f"{key} = {value}"
|
||||
)
|
||||
assert expected.encode() in refresh
|
||||
previous = len(server.commands)
|
||||
for invalid in [
|
||||
{"cpu_millis": 0},
|
||||
{"memory_bytes": 1},
|
||||
{"gpu_count": -1},
|
||||
{"gpu_count": True},
|
||||
{"gpu_count": 2**32},
|
||||
{"gpu_class": "H200:8"},
|
||||
{"gpu_count": 0, "gpu_class": "h100"},
|
||||
]:
|
||||
with pytest.raises(ValueError):
|
||||
if sync:
|
||||
view.refresh(**invalid)
|
||||
else:
|
||||
await view.refresh(**invalid)
|
||||
assert len(server.commands) == previous
|
||||
assert not any("count_rows" in path for path in requests)
|
||||
|
||||
|
||||
@@ -725,7 +756,7 @@ def test_embedded_create_refuses_automatic_refresh_before_creating_view(
|
||||
tmp_path, options
|
||||
):
|
||||
db = make_db(tmp_path)
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
|
||||
db.create_materialized_view("adults", "people", **options)
|
||||
assert "adults" not in db.table_names()
|
||||
|
||||
@@ -742,7 +773,7 @@ def test_remote_create_rejects_invalid_interval_without_request(seconds):
|
||||
@pytest.mark.experimental_functions
|
||||
def test_namespace_forwards_automatic_refresh_request(tmp_path):
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
|
||||
db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
|
||||
|
||||
|
||||
@@ -750,7 +781,7 @@ def test_namespace_forwards_automatic_refresh_request(tmp_path):
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_namespace_forwards_automatic_refresh_request(tmp_path):
|
||||
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)})
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="requires LanceDB Enterprise"):
|
||||
await db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
|
||||
|
||||
|
||||
|
||||
@@ -278,7 +278,7 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path):
|
||||
|
||||
# with_row_id is unsupported by the LSM scanner; on an RTE table the default
|
||||
# (auto-routed) read hard-errors instead of silently reading a stale base.
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(Exception, match=r"with_row_id.*use_rte\(false\)"):
|
||||
table.search().with_row_id(True).to_arrow()
|
||||
|
||||
# use_rte(False) is the escape hatch: it reads the base table only.
|
||||
@@ -563,19 +563,28 @@ def test_lsm_read_time_travel_errors(tmp_path):
|
||||
assert sorted(base["id"].to_pylist()) == [1, 2, 3]
|
||||
|
||||
|
||||
def test_lsm_read_take_row_ids_errors(tmp_path):
|
||||
@pytest.mark.parametrize("with_row_id", [False, True])
|
||||
@pytest.mark.parametrize("use_rte", [None, True])
|
||||
def test_lsm_read_take_row_ids_errors(tmp_path, with_row_id, use_rte):
|
||||
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
|
||||
table = db.create_table("t", _reader([1, 2, 3]))
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.unsharded())
|
||||
_lsm_upsert(table, [4])
|
||||
# take-by-row-id auto-routes through the LSM scanner, which has no stable _rowid,
|
||||
# so it hard-errors instead of failing with an opaque column-not-found error.
|
||||
with pytest.raises(Exception, match="row id"):
|
||||
table.take_row_ids([0, 1]).to_arrow()
|
||||
# Automatic and explicit RTE routing must explain the unsupported take,
|
||||
# including when row IDs are only requested internally for ordering.
|
||||
take = table.take_row_ids([1, 0, 1, 2**64 - 1], with_row_id=with_row_id)
|
||||
if use_rte is not None:
|
||||
take = take.use_rte(use_rte)
|
||||
with pytest.raises(Exception, match=r"take by row id.*use_rte\(false\)"):
|
||||
take.to_arrow()
|
||||
# use_rte(False) is the escape hatch: it reads the base table.
|
||||
base = table.take_row_ids([0, 1]).use_rte(False).to_arrow()
|
||||
assert base.num_rows == 2
|
||||
base = take.use_rte(False).to_arrow()
|
||||
assert base["id"].to_pylist() == [2, 1, 2]
|
||||
assert base["value"].to_pylist() == [1, 0, 1]
|
||||
assert ("_rowid" in base.column_names) == with_row_id
|
||||
if with_row_id:
|
||||
assert base["_rowid"].to_pylist() == [1, 0, 1]
|
||||
|
||||
|
||||
def test_lsm_read_fts_postfilter_errors(tmp_path):
|
||||
|
||||
@@ -11,13 +11,20 @@ import http.server
|
||||
import json
|
||||
from urllib.parse import parse_qs, unquote, urlparse
|
||||
import pytest
|
||||
import builtins
|
||||
import copy
|
||||
import pyarrow as pa
|
||||
import lancedb
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
from utils import start_server_thread
|
||||
from lancedb.listing import AsyncListing, Listing
|
||||
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
|
||||
from lancedb.namespace import _MAX_QUERY_K, _query_to_namespace_request
|
||||
from lancedb.namespace import (
|
||||
_MAX_QUERY_K,
|
||||
LanceNamespace,
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
@@ -31,6 +38,7 @@ class TestNamespaceCreateTableOptions:
|
||||
@pytest.mark.parametrize("version", ["legacy", "stable"])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
def test_deprecated_storage_version(self, tmp_path, version, empty):
|
||||
pytest.importorskip("lance")
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "namespace")})
|
||||
data = None if empty else [{"id": 1}]
|
||||
schema = pa.schema([("id", pa.int64())])
|
||||
@@ -64,6 +72,7 @@ class TestNamespaceCreateTableOptions:
|
||||
@pytest.mark.parametrize("version", ["legacy", "stable"])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
async def test_deprecated_storage_version_async(self, tmp_path, version, empty):
|
||||
pytest.importorskip("lance")
|
||||
root = str(tmp_path / "namespace")
|
||||
db = lancedb.connect_namespace_async("dir", {"root": root})
|
||||
data = None if empty else [{"id": 1}]
|
||||
@@ -166,6 +175,9 @@ class _FailingSyncInner:
|
||||
async def to_arrow(self):
|
||||
raise RuntimeError("direct table to_arrow should not be used")
|
||||
|
||||
async def _execute_query(self, query, **kwargs):
|
||||
raise RuntimeError("local execution reached")
|
||||
|
||||
|
||||
class _FailingAsyncInner:
|
||||
def name(self):
|
||||
@@ -441,13 +453,14 @@ class TestNamespaceConnection:
|
||||
assert len(table_names) == 1
|
||||
|
||||
# Verify empty table
|
||||
result = table.to_pandas()
|
||||
result = table.to_arrow()
|
||||
assert len(result) == 0
|
||||
assert list(result.columns) == ["id", "vector", "text"]
|
||||
assert result.column_names == ["id", "vector", "text"]
|
||||
|
||||
def test_table_to_pandas_blob_lazy_through_namespace(self):
|
||||
"""Namespace-backed tables should use Lance blob-aware pandas conversion."""
|
||||
pytest.importorskip("lance")
|
||||
pytest.importorskip("pandas")
|
||||
db = lancedb.connect_namespace("dir", {"root": self.temp_dir})
|
||||
db.create_namespace(["test_ns"])
|
||||
data = pa.table(
|
||||
@@ -504,9 +517,9 @@ class TestNamespaceConnection:
|
||||
assert table.id == "test_ns$test_table"
|
||||
|
||||
# Verify empty table with correct schema
|
||||
result = table.to_pandas()
|
||||
result = table.to_arrow()
|
||||
assert len(result) == 0
|
||||
assert list(result.columns) == ["id", "vector"]
|
||||
assert result.column_names == ["id", "vector"]
|
||||
|
||||
def test_drop_table_through_namespace(self):
|
||||
"""Test dropping a table through namespace."""
|
||||
@@ -575,37 +588,43 @@ class TestNamespaceConnection:
|
||||
assert table_schema.field("id").type == pa.int64()
|
||||
assert table_schema.field("text").type == pa.string()
|
||||
|
||||
def test_rename_table(self):
|
||||
"""Test that rename_table renames a table in the namespace.
|
||||
|
||||
The `dir` namespace implementation in lance-namespace-impls does not
|
||||
implement `rename_table` yet (only the `rest` backend does), so it
|
||||
currently falls back to the default trait method which raises
|
||||
NotSupported. This is expected to start passing once the `dir`
|
||||
backend gains rename_table support upstream.
|
||||
"""
|
||||
@pytest.mark.parametrize("destination_namespace", ["test_ns", "destination_ns"])
|
||||
def test_rename_table(self, destination_namespace):
|
||||
"""Test that renaming a table preserves its data and namespace registration."""
|
||||
db = lancedb.connect_namespace("dir", {"root": self.temp_dir})
|
||||
|
||||
# Create a child namespace first
|
||||
db.create_namespace(["test_ns"])
|
||||
if destination_namespace != "test_ns":
|
||||
db.create_namespace([destination_namespace])
|
||||
|
||||
# Create a table in child namespace
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), 2)),
|
||||
]
|
||||
)
|
||||
db.create_table("old_name", schema=schema, namespace_path=["test_ns"])
|
||||
data = pa.Table.from_pylist(
|
||||
[{"id": 1, "vector": [1.0, 2.0]}, {"id": 2, "vector": [3.0, 4.0]}],
|
||||
schema=schema,
|
||||
)
|
||||
db.create_table("old_name", data=data, namespace_path=["test_ns"])
|
||||
|
||||
# Rename the table within the same namespace
|
||||
with pytest.raises(NotImplementedError, match="rename_table not implemented"):
|
||||
db.rename_table(
|
||||
"old_name",
|
||||
"new_name",
|
||||
cur_namespace_path=["test_ns"],
|
||||
new_namespace_path=["test_ns"],
|
||||
)
|
||||
db.rename_table(
|
||||
"old_name",
|
||||
"new_name",
|
||||
cur_namespace_path=["test_ns"],
|
||||
new_namespace_path=[destination_namespace],
|
||||
)
|
||||
|
||||
reopened = lancedb.connect_namespace("dir", {"root": self.temp_dir})
|
||||
assert "old_name" not in reopened.table_names(namespace_path=["test_ns"])
|
||||
assert "new_name" in reopened.table_names(
|
||||
namespace_path=[destination_namespace]
|
||||
)
|
||||
with pytest.raises(TableNotFoundError):
|
||||
reopened.open_table("old_name", namespace_path=["test_ns"])
|
||||
table = reopened.open_table("new_name", namespace_path=[destination_namespace])
|
||||
assert table.namespace == [destination_namespace]
|
||||
assert table.to_arrow().equals(data)
|
||||
|
||||
def test_drop_all_tables(self):
|
||||
"""Test dropping all tables through namespace."""
|
||||
@@ -656,9 +675,9 @@ class TestNamespaceConnection:
|
||||
table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"])
|
||||
|
||||
# Verify empty table was created
|
||||
result = table.to_pandas()
|
||||
result = table.to_arrow()
|
||||
assert len(result) == 0
|
||||
assert list(result.columns) == ["id", "vector", "text"]
|
||||
assert result.column_names == ["id", "vector", "text"]
|
||||
|
||||
# Test add data to the table
|
||||
new_data = [
|
||||
@@ -666,19 +685,19 @@ class TestNamespaceConnection:
|
||||
{"id": 2, "vector": [2.0, 3.0], "text": "item_2"},
|
||||
]
|
||||
table.add(new_data)
|
||||
result = table.to_pandas()
|
||||
result = table.to_arrow()
|
||||
assert len(result) == 2
|
||||
|
||||
# Test delete
|
||||
table.delete("id = 1")
|
||||
result = table.to_pandas()
|
||||
result = table.to_arrow()
|
||||
assert len(result) == 1
|
||||
assert result["id"].values[0] == 2
|
||||
assert result["id"][0].as_py() == 2
|
||||
|
||||
# Test update
|
||||
table.update(where="id = 2", values={"text": "updated"})
|
||||
result = table.to_pandas()
|
||||
assert result["text"].values[0] == "updated"
|
||||
result = table.to_arrow()
|
||||
assert result["text"][0].as_py() == "updated"
|
||||
|
||||
def test_storage_options(self):
|
||||
"""Test passing storage options through namespace connection."""
|
||||
@@ -818,28 +837,28 @@ class TestNamespaceConnection:
|
||||
opened_table_a = db.open_table(
|
||||
"same_name_table", namespace_path=["namespace_a"]
|
||||
)
|
||||
result_a = opened_table_a.to_pandas().sort_values("id").reset_index(drop=True)
|
||||
result_a = opened_table_a.to_arrow().sort_by([("id", "ascending")])
|
||||
assert len(result_a) == 2
|
||||
assert result_a["id"].tolist() == [1, 2]
|
||||
assert result_a["text"].tolist() == [
|
||||
assert result_a["id"].to_pylist() == [1, 2]
|
||||
assert result_a["text"].to_pylist() == [
|
||||
"data_from_namespace_a",
|
||||
"also_from_namespace_a",
|
||||
]
|
||||
assert [v.tolist() for v in result_a["vector"]] == [[1.0, 2.0], [3.0, 4.0]]
|
||||
assert result_a["vector"].to_pylist() == [[1.0, 2.0], [3.0, 4.0]]
|
||||
|
||||
# Verify data in namespace_b table
|
||||
opened_table_b = db.open_table(
|
||||
"same_name_table", namespace_path=["namespace_b"]
|
||||
)
|
||||
result_b = opened_table_b.to_pandas().sort_values("id").reset_index(drop=True)
|
||||
result_b = opened_table_b.to_arrow().sort_by([("id", "ascending")])
|
||||
assert len(result_b) == 3
|
||||
assert result_b["id"].tolist() == [10, 20, 30]
|
||||
assert result_b["text"].tolist() == [
|
||||
assert result_b["id"].to_pylist() == [10, 20, 30]
|
||||
assert result_b["text"].to_pylist() == [
|
||||
"data_from_namespace_b",
|
||||
"also_from_namespace_b",
|
||||
"more_from_namespace_b",
|
||||
]
|
||||
assert [v.tolist() for v in result_b["vector"]] == [
|
||||
assert result_b["vector"].to_pylist() == [
|
||||
[10.0, 20.0],
|
||||
[30.0, 40.0],
|
||||
[50.0, 60.0],
|
||||
@@ -1020,9 +1039,8 @@ class TestAsyncNamespaceConnection:
|
||||
assert result.schema.field("vector").type == pa.list_(pa.float32(), 2)
|
||||
|
||||
# Verify data content
|
||||
result_df = result.to_pandas()
|
||||
assert result_df["id"].tolist() == [1, 2, 3]
|
||||
assert [v.tolist() for v in result_df["vector"]] == [
|
||||
assert result["id"].to_pylist() == [1, 2, 3]
|
||||
assert result["vector"].to_pylist() == [
|
||||
[1.0, 2.0],
|
||||
[3.0, 4.0],
|
||||
[5.0, 6.0],
|
||||
@@ -1031,15 +1049,13 @@ class TestAsyncNamespaceConnection:
|
||||
# Test update operation
|
||||
await table.update({"id": 20}, where="id = 2")
|
||||
result = await table.to_arrow()
|
||||
result_df = result.to_pandas().sort_values("id").reset_index(drop=True)
|
||||
assert result_df["id"].tolist() == [1, 3, 20]
|
||||
assert result.sort_by([("id", "ascending")])["id"].to_pylist() == [1, 3, 20]
|
||||
|
||||
# Test delete operation
|
||||
await table.delete("id = 1")
|
||||
result = await table.to_arrow()
|
||||
assert len(result) == 2
|
||||
result_df = result.to_pandas().sort_values("id").reset_index(drop=True)
|
||||
assert result_df["id"].tolist() == [3, 20]
|
||||
assert result.sort_by([("id", "ascending")])["id"].to_pylist() == [3, 20]
|
||||
|
||||
async def test_drop_table_async(self):
|
||||
"""Test dropping a table asynchronously through namespace."""
|
||||
@@ -1232,25 +1248,45 @@ class TestPushdownOperations:
|
||||
db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir})
|
||||
assert db._route_pushdown_to_rust is True
|
||||
|
||||
def test_lance_table_to_arrow_uses_query_pushdown(self):
|
||||
@pytest.mark.parametrize("as_pandas", [False, True], ids=["arrow", "pandas"])
|
||||
def test_lance_table_query_pushdown(self, as_pandas):
|
||||
if as_pandas:
|
||||
pytest.importorskip("pandas")
|
||||
namespace_client = _NamespaceClient()
|
||||
table = _namespace_lance_table(namespace_client)
|
||||
|
||||
assert table.to_arrow().equals(PUSHDOWN_DATA)
|
||||
assert table.to_pandas()["id"].tolist() == list(range(12))
|
||||
assert len(namespace_client.requests) == 2
|
||||
if as_pandas:
|
||||
assert table.to_pandas()["id"].tolist() == list(range(12))
|
||||
else:
|
||||
assert table.to_arrow().equals(PUSHDOWN_DATA)
|
||||
assert len(namespace_client.requests) == 1
|
||||
assert [request.id for request in namespace_client.requests] == [
|
||||
["geneva", "hist"],
|
||||
["geneva", "hist"],
|
||||
["geneva", "hist"]
|
||||
]
|
||||
# Unlimited reads cap k at i32::MAX (the namespace query_table `k`
|
||||
# field is i32); sys.maxsize would overflow the Rust binding.
|
||||
assert [request.k for request in namespace_client.requests] == [
|
||||
_MAX_QUERY_K,
|
||||
_MAX_QUERY_K,
|
||||
]
|
||||
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)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query_kwargs",
|
||||
[
|
||||
{"approx_mode": "fast"},
|
||||
{"search_effort": 0.75},
|
||||
{"approx_mode": "fast", "search_effort": 0.75},
|
||||
],
|
||||
ids=["approx_mode", "search_effort", "both"],
|
||||
)
|
||||
def test_lance_table_local_only_options_are_not_pushed_down(self, query_kwargs):
|
||||
namespace_client = _NamespaceClient()
|
||||
table = _namespace_lance_table(namespace_client)
|
||||
|
||||
# The QueryTable request cannot carry these options, so the query has to
|
||||
# run locally rather than silently ignore them.
|
||||
with pytest.raises(RuntimeError, match="local execution reached"):
|
||||
table._execute_query(Query(vector=[1.0, 2.0], **query_kwargs))
|
||||
assert namespace_client.requests == []
|
||||
|
||||
def test_probe_fields_pass_through_independently(self):
|
||||
request = _query_to_namespace_request(
|
||||
["geneva", "hist"],
|
||||
@@ -1310,7 +1346,10 @@ class TestAsyncPushdownOperations:
|
||||
db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir})
|
||||
assert len(db._namespace_client_pushdown_operations) == 0
|
||||
|
||||
async def test_async_table_to_arrow_uses_query_pushdown(self):
|
||||
@pytest.mark.parametrize("as_pandas", [False, True], ids=["arrow", "pandas"])
|
||||
async def test_async_table_query_pushdown(self, as_pandas):
|
||||
if as_pandas:
|
||||
pytest.importorskip("pandas")
|
||||
namespace_client = _NamespaceClient()
|
||||
|
||||
table = AsyncTable(
|
||||
@@ -1320,23 +1359,49 @@ class TestAsyncPushdownOperations:
|
||||
pushdown_operations={"QueryTable"},
|
||||
)
|
||||
|
||||
assert (await table.to_arrow()).equals(PUSHDOWN_DATA)
|
||||
assert (await table.to_pandas())["id"].tolist() == list(range(12))
|
||||
assert len(namespace_client.requests) == 2
|
||||
if as_pandas:
|
||||
assert (await table.to_pandas())["id"].tolist() == list(range(12))
|
||||
else:
|
||||
assert (await table.to_arrow()).equals(PUSHDOWN_DATA)
|
||||
assert len(namespace_client.requests) == 1
|
||||
assert [request.id for request in namespace_client.requests] == [
|
||||
["geneva", "hist"],
|
||||
["geneva", "hist"],
|
||||
["geneva", "hist"]
|
||||
]
|
||||
# Unlimited reads cap k at i32::MAX (the namespace query_table `k`
|
||||
# field is i32); sys.maxsize would overflow the Rust binding.
|
||||
assert [request.k for request in namespace_client.requests] == [
|
||||
_MAX_QUERY_K,
|
||||
_MAX_QUERY_K,
|
||||
]
|
||||
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)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query_kwargs",
|
||||
[
|
||||
{"approx_mode": "fast"},
|
||||
{"search_effort": 0.75},
|
||||
{"approx_mode": "fast", "search_effort": 0.75},
|
||||
],
|
||||
ids=["approx_mode", "search_effort", "both"],
|
||||
)
|
||||
async def test_async_table_local_only_options_are_not_pushed_down(
|
||||
self, query_kwargs
|
||||
):
|
||||
namespace_client = _NamespaceClient()
|
||||
|
||||
def test_local_table_to_arrow_and_to_pandas_are_unchanged(tmp_path):
|
||||
table = AsyncTable(
|
||||
_FailingAsyncInner(),
|
||||
namespace_path=["geneva"],
|
||||
namespace_client=namespace_client,
|
||||
pushdown_operations={"QueryTable"},
|
||||
)
|
||||
|
||||
with pytest.raises(AssertionError, match="direct async query"):
|
||||
await table._execute_query(Query(vector=[1.0, 2.0], **query_kwargs))
|
||||
assert namespace_client.requests == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("as_pandas", [False, True], ids=["arrow", "pandas"])
|
||||
def test_local_table_to_arrow_and_to_pandas_are_unchanged(tmp_path, as_pandas):
|
||||
if as_pandas:
|
||||
pytest.importorskip("pandas")
|
||||
db = lancedb.connect(str(tmp_path / "db"))
|
||||
table = db.create_table(
|
||||
"local",
|
||||
@@ -1346,8 +1411,10 @@ def test_local_table_to_arrow_and_to_pandas_are_unchanged(tmp_path):
|
||||
],
|
||||
)
|
||||
|
||||
assert table.to_arrow().column("id").to_pylist() == [1, 2]
|
||||
assert table.to_pandas()["id"].tolist() == [1, 2]
|
||||
if as_pandas:
|
||||
assert table.to_pandas()["id"].tolist() == [1, 2]
|
||||
else:
|
||||
assert table.to_arrow().column("id").to_pylist() == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("effort", [0.0, 0.5, 1.0])
|
||||
@@ -1360,3 +1427,59 @@ def test_namespace_request_rejects_search_effort(effort):
|
||||
_query_to_namespace_request(
|
||||
["test"], Query(vector=[1.0, 0.0], search_effort=effort)
|
||||
)
|
||||
|
||||
|
||||
class AttributeAccessNamespace(LanceNamespace):
|
||||
"""A Python namespace that reads request fields as attributes.
|
||||
|
||||
Python implementations such as ``lance_namespace_impls.glue.GlueNamespace``
|
||||
read requests like pydantic models (``request.id``), and expect omitted
|
||||
optional fields to be ``None``. This fake records what it read and then
|
||||
delegates to ``DirectoryNamespace`` so the test runs locally.
|
||||
"""
|
||||
|
||||
def __init__(self, root: str):
|
||||
from lance.namespace import DirectoryNamespace
|
||||
|
||||
self._inner = DirectoryNamespace(root=root)
|
||||
self.seen = {}
|
||||
|
||||
def namespace_id(self) -> str:
|
||||
return f"AttributeAccessNamespace[{self._inner.namespace_id()}]"
|
||||
|
||||
def list_tables(self, request):
|
||||
self.seen["list_tables"] = request
|
||||
_ = request.id
|
||||
_ = request.page_token
|
||||
return self._inner.list_tables(request)
|
||||
|
||||
def describe_table(self, request):
|
||||
self.seen["describe_table"] = request
|
||||
_ = request.id
|
||||
# Optional field omitted by the Rust side; must read as None.
|
||||
assert request.load_detailed_metadata is None
|
||||
return self._inner.describe_table(request)
|
||||
|
||||
|
||||
def test_python_namespace_attribute_access(tmp_path):
|
||||
pytest.importorskip("lance.namespace")
|
||||
root = str(tmp_path)
|
||||
data = pa.table({"id": [1, 2, 3], "text": ["alpha", "beta", "gamma"]})
|
||||
lancedb.connect_namespace("dir", {"root": root}).create_table("t", data)
|
||||
|
||||
ns = AttributeAccessNamespace(root)
|
||||
db = LanceNamespaceDBConnection(ns)
|
||||
|
||||
assert list(db.list_tables()) == ["t"]
|
||||
assert db.open_table("t").to_arrow().to_pylist() == data.to_pylist()
|
||||
|
||||
# Mapping access and model_dump() keep working.
|
||||
request = ns.seen["describe_table"]
|
||||
assert isinstance(request, builtins._DictWithModelDump)
|
||||
assert request["id"] == request.id == ["t"]
|
||||
assert request.model_dump() == dict(request)
|
||||
assert "load_detailed_metadata" not in request
|
||||
|
||||
# Missing dunder lookups still raise, so copy/hasattr probes work.
|
||||
assert not hasattr(request, "__missing_dunder__")
|
||||
assert copy.deepcopy(request) == request
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import importlib
|
||||
import importlib.metadata
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -9,6 +10,18 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("distribution", ["lancedb", "lancedb-compat"])
|
||||
def test_version_matches_package_metadata(distribution):
|
||||
import lancedb
|
||||
|
||||
try:
|
||||
package_version = importlib.metadata.version(distribution)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
pytest.skip(f"{distribution} is not installed")
|
||||
|
||||
assert lancedb.__version__ == package_version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["JobInfo", "JobDescription", "JobFailureInfo"])
|
||||
def test_job_metadata_types_have_resolvable_modules(name):
|
||||
"""Documentation tools resolve re-exports through each type's module."""
|
||||
@@ -18,6 +31,15 @@ def test_job_metadata_types_have_resolvable_modules(name):
|
||||
assert getattr(defining_module, public_type.__name__, None) is public_type
|
||||
|
||||
|
||||
def test_gpu_class_reexport_has_resolvable_module():
|
||||
import lancedb
|
||||
|
||||
public_type = lancedb.GpuClass
|
||||
defining_module = importlib.import_module(public_type.__module__)
|
||||
|
||||
assert getattr(defining_module, public_type.__name__, None) is public_type
|
||||
|
||||
|
||||
def test_pyo3_abi_matches_minimum_supported_python():
|
||||
project_dir = Path(__file__).parents[2]
|
||||
pyproject = (project_dir / "pyproject.toml").read_text()
|
||||
|
||||
@@ -946,12 +946,12 @@ def test_iter_with_different_formats(some_permutation: Permutation):
|
||||
python_batches = list(python_perm.iter(batch_size, skip_last_batch=False))
|
||||
assert all(isinstance(batch, list) for batch in python_batches)
|
||||
|
||||
# Test with pandas format
|
||||
|
||||
def test_iter_with_pandas_format(some_permutation: Permutation):
|
||||
pd = pytest.importorskip("pandas")
|
||||
batch_size = 100
|
||||
pandas_perm = some_permutation.with_format("pandas")
|
||||
pandas_batches = list(pandas_perm.iter(batch_size, skip_last_batch=False))
|
||||
# Import pandas to check the type
|
||||
import pandas as pd
|
||||
|
||||
assert all(isinstance(batch, pd.DataFrame) for batch in pandas_batches)
|
||||
|
||||
|
||||
@@ -1053,8 +1053,6 @@ def test_identity_permutation(mem_db):
|
||||
|
||||
|
||||
def test_transform_fn(mem_db):
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import polars as pl
|
||||
|
||||
tbl = mem_db.create_table(
|
||||
@@ -1062,20 +1060,6 @@ def test_transform_fn(mem_db):
|
||||
)
|
||||
permutation = Permutation.identity(tbl)
|
||||
|
||||
np_result = list(permutation.with_format("numpy").iter(10, skip_last_batch=False))[
|
||||
0
|
||||
]
|
||||
assert np_result.shape == (10, 2)
|
||||
assert np_result.dtype == np.int64
|
||||
assert isinstance(np_result, np.ndarray)
|
||||
|
||||
pd_result = list(permutation.with_format("pandas").iter(10, skip_last_batch=False))[
|
||||
0
|
||||
]
|
||||
assert pd_result.shape == (10, 2)
|
||||
assert pd_result.dtypes.tolist() == [np.int64, np.int64]
|
||||
assert isinstance(pd_result, pd.DataFrame)
|
||||
|
||||
pl_result = list(permutation.with_format("polars").iter(10, skip_last_batch=False))[
|
||||
0
|
||||
]
|
||||
@@ -1141,6 +1125,27 @@ def test_transform_fn(mem_db):
|
||||
assert isinstance(arrow_result, pa.RecordBatch)
|
||||
|
||||
|
||||
def test_transform_fn_pandas(mem_db):
|
||||
pd = pytest.importorskip("pandas")
|
||||
import numpy as np
|
||||
|
||||
tbl = mem_db.create_table(
|
||||
"test_table", pa.table({"id": range(10), "value": range(10)})
|
||||
)
|
||||
permutation = Permutation.identity(tbl)
|
||||
numpy_result = list(
|
||||
permutation.with_format("numpy").iter(10, skip_last_batch=False)
|
||||
)[0]
|
||||
assert numpy_result.shape == (10, 2)
|
||||
assert numpy_result.dtype == np.int64
|
||||
assert isinstance(numpy_result, np.ndarray)
|
||||
|
||||
result = list(permutation.with_format("pandas").iter(10, skip_last_batch=False))[0]
|
||||
assert result.shape == (10, 2)
|
||||
assert result.dtypes.tolist() == [np.int64, np.int64]
|
||||
assert isinstance(result, pd.DataFrame)
|
||||
|
||||
|
||||
def test_custom_transform(mem_db):
|
||||
tbl = mem_db.create_table(
|
||||
"test_table", pa.table({"id": range(10), "value": range(10)})
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Tuple
|
||||
from typing import List, Literal, Optional, Tuple
|
||||
|
||||
import pyarrow as pa
|
||||
import pydantic
|
||||
@@ -16,6 +16,7 @@ from lancedb.pydantic import (
|
||||
Vector,
|
||||
pydantic_to_schema,
|
||||
)
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
|
||||
@@ -791,6 +792,305 @@ async def test_aliases_in_lance_model_async(mem_db_async):
|
||||
assert model.distance < 0.01
|
||||
|
||||
|
||||
def test_aliased_lance_model_reads_back_its_own_table(mem_db):
|
||||
# The schema and add() use field names, so to_pydantic() must accept rows
|
||||
# keyed by field name even though pydantic validates by alias.
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(alias="userId")
|
||||
vector: Vector(2)
|
||||
|
||||
tbl = mem_db.create_table("aliased_items", schema=Item)
|
||||
tbl.add([Item(userId=1, vector=[0.1, 0.2])])
|
||||
assert tbl.schema.names == ["user_id", "vector"]
|
||||
|
||||
[item] = tbl.search([0.1, 0.2]).limit(1).to_pydantic(Item)
|
||||
assert item.user_id == 1
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.user_id == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"validation_alias",
|
||||
[
|
||||
pydantic.AliasChoices("userId"),
|
||||
pydantic.AliasPath("userId"),
|
||||
],
|
||||
ids=["alias-choices", "alias-path"],
|
||||
)
|
||||
def test_aliased_lance_model_with_complex_validation_alias_reads_back_its_own_table(
|
||||
mem_db, validation_alias
|
||||
):
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(validation_alias=validation_alias)
|
||||
vector: Vector(2)
|
||||
|
||||
tbl = mem_db.create_table("aliased_items", schema=Item)
|
||||
tbl.add([Item(userId=1, vector=[0.1, 0.2])])
|
||||
assert tbl.schema.names == ["user_id", "vector"]
|
||||
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.user_id == 1
|
||||
|
||||
|
||||
def test_lower_priority_alias_takes_precedence_over_field_name(mem_db):
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(
|
||||
validation_alias=pydantic.AliasChoices("primaryId", "secondaryId")
|
||||
)
|
||||
|
||||
row = {"user_id": 1, "secondaryId": 2}
|
||||
tbl = mem_db.create_table("aliased_items", data=[row])
|
||||
|
||||
[arrow_row] = tbl.search().to_arrow().to_pylist()
|
||||
assert Item(**arrow_row).user_id == 2
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.user_id == 2
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
Version(pydantic.VERSION) < Version("2.11"),
|
||||
reason="validate_by_alias/validate_by_name require pydantic>=2.11",
|
||||
)
|
||||
def test_aliased_lance_model_with_name_only_validation(mem_db):
|
||||
class Item(LanceModel):
|
||||
model_config = pydantic.ConfigDict(
|
||||
validate_by_alias=False, validate_by_name=True
|
||||
)
|
||||
user_id: int = Field(default=0, alias="userId")
|
||||
|
||||
tbl = mem_db.create_table("name_only_items", schema=Item)
|
||||
item = Item(user_id=42)
|
||||
assert item.user_id == 42
|
||||
tbl.add([item])
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.user_id == 42
|
||||
|
||||
|
||||
def test_aliased_lance_model_with_populate_by_name(mem_db):
|
||||
class Item(LanceModel):
|
||||
model_config = pydantic.ConfigDict(populate_by_name=True)
|
||||
user_id: int = Field(default=0, alias="userId")
|
||||
|
||||
tbl = mem_db.create_table("populate_by_name_items", schema=Item)
|
||||
item = Item(user_id=42)
|
||||
assert item.user_id == 42
|
||||
tbl.add([item])
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.user_id == 42
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
Version(pydantic.VERSION) < Version("2.11"),
|
||||
reason="validate_by_name requires pydantic>=2.11",
|
||||
)
|
||||
def test_explicit_validate_by_name_false_overrides_populate_by_name(mem_db):
|
||||
class Item(LanceModel):
|
||||
model_config = pydantic.ConfigDict(
|
||||
populate_by_name=True,
|
||||
validate_by_name=False,
|
||||
)
|
||||
user_id: int = Field(default=0, alias="userId")
|
||||
|
||||
tbl = mem_db.create_table("validate_by_name_precedence_items", schema=Item)
|
||||
item = Item(userId=42)
|
||||
assert item.user_id == 42
|
||||
tbl.add([item])
|
||||
assert tbl.schema.names == ["user_id"]
|
||||
assert tbl.search().to_arrow().to_pylist() == [{"user_id": 42}]
|
||||
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.user_id == 42
|
||||
|
||||
|
||||
def test_field_name_fallback_preserves_populate_by_name_reader(mem_db):
|
||||
class Item(LanceModel):
|
||||
model_config = pydantic.ConfigDict(populate_by_name=True)
|
||||
value: int = Field(default=0, validation_alias="id")
|
||||
id: int = Field(default=-1, alias="recordId")
|
||||
|
||||
row = {"value": 1}
|
||||
assert Item(**row).model_dump() == {"value": 1, "id": -1}
|
||||
tbl = mem_db.create_table("populate_by_name_readers", data=[row])
|
||||
|
||||
[arrow_row] = tbl.search().to_arrow().to_pylist()
|
||||
assert arrow_row == row
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.model_dump() == {"value": 1, "id": -1}
|
||||
|
||||
|
||||
def test_field_name_that_is_another_fields_alias_keeps_its_meaning(mem_db):
|
||||
class Item(LanceModel):
|
||||
record_id: int = Field(default=0, alias="id")
|
||||
id: int = Field(default=-1, alias="legacy_id")
|
||||
|
||||
tbl = mem_db.create_table("alias_collision_items", data=[{"id": 42}])
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.model_dump() == {"record_id": 42, "id": -1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"validation_alias",
|
||||
[
|
||||
pydantic.AliasChoices("id", "recordId"),
|
||||
pydantic.AliasPath("id"),
|
||||
pydantic.AliasChoices(pydantic.AliasPath("id"), "recordId"),
|
||||
],
|
||||
)
|
||||
def test_field_name_read_by_another_fields_alias_choices_or_path(
|
||||
mem_db, validation_alias
|
||||
):
|
||||
class Item(LanceModel):
|
||||
record_id: int = Field(default=0, validation_alias=validation_alias)
|
||||
id: int = Field(default=-1, alias="legacy_id")
|
||||
|
||||
tbl = mem_db.create_table("alias_choices_items", data=[{"id": 42}])
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.model_dump() == {"record_id": 42, "id": -1}
|
||||
|
||||
|
||||
def test_field_name_fallback_does_not_change_another_fields_alias_choice(mem_db):
|
||||
class Item(LanceModel):
|
||||
value: int = Field(
|
||||
default=0, validation_alias=pydantic.AliasChoices("id", "valueId")
|
||||
)
|
||||
record_id: int = Field(
|
||||
default=-1, validation_alias=pydantic.AliasChoices("id", "recordId")
|
||||
)
|
||||
|
||||
row = {"value": 1, "recordId": 42}
|
||||
assert Item(**row).model_dump() == {"value": 0, "record_id": 42}
|
||||
tbl = mem_db.create_table("shared_alias_items", data=[row])
|
||||
|
||||
[arrow_row] = tbl.search().to_arrow().to_pylist()
|
||||
assert arrow_row == row
|
||||
[item] = tbl.search().to_pydantic(Item)
|
||||
assert item.model_dump() == {"value": 0, "record_id": 42}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aliased_lance_model_reads_back_its_own_table_async(mem_db_async):
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(alias="userId")
|
||||
vector: Vector(2)
|
||||
|
||||
tbl = await mem_db_async.create_table("aliased_items", schema=Item)
|
||||
await tbl.add([Item(userId=1, vector=[0.1, 0.2])])
|
||||
|
||||
[item] = await tbl.vector_search([0.1, 0.2]).limit(1).to_pydantic(Item)
|
||||
assert item.user_id == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"validation_alias",
|
||||
[
|
||||
pydantic.AliasChoices("userId"),
|
||||
pydantic.AliasPath("userId"),
|
||||
],
|
||||
ids=["alias-choices", "alias-path"],
|
||||
)
|
||||
async def test_aliased_lance_model_with_complex_validation_alias_reads_back_async(
|
||||
mem_db_async, validation_alias
|
||||
):
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(validation_alias=validation_alias)
|
||||
vector: Vector(2)
|
||||
|
||||
tbl = await mem_db_async.create_table("aliased_items", schema=Item)
|
||||
await tbl.add([Item(userId=1, vector=[0.1, 0.2])])
|
||||
assert (await tbl.schema()).names == ["user_id", "vector"]
|
||||
|
||||
[item] = await tbl.vector_search([0.1, 0.2]).limit(1).to_pydantic(Item)
|
||||
assert item.user_id == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lower_priority_alias_takes_precedence_over_field_name_async(
|
||||
mem_db_async,
|
||||
):
|
||||
class Item(LanceModel):
|
||||
user_id: int = Field(
|
||||
validation_alias=pydantic.AliasChoices("primaryId", "secondaryId")
|
||||
)
|
||||
|
||||
row = {"user_id": 1, "secondaryId": 2}
|
||||
tbl = await mem_db_async.create_table("aliased_items", data=[row])
|
||||
|
||||
[arrow_row] = (await (await tbl.search()).to_arrow()).to_pylist()
|
||||
assert Item(**arrow_row).user_id == 2
|
||||
[item] = await (await tbl.search()).to_pydantic(Item)
|
||||
assert item.user_id == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_field_name_fallback_does_not_change_another_fields_alias_choice_async(
|
||||
mem_db_async,
|
||||
):
|
||||
class Item(LanceModel):
|
||||
value: int = Field(
|
||||
default=0, validation_alias=pydantic.AliasChoices("id", "valueId")
|
||||
)
|
||||
record_id: int = Field(
|
||||
default=-1, validation_alias=pydantic.AliasChoices("id", "recordId")
|
||||
)
|
||||
|
||||
row = {"value": 1, "recordId": 42}
|
||||
assert Item(**row).model_dump() == {"value": 0, "record_id": 42}
|
||||
tbl = await mem_db_async.create_table("shared_alias_items", data=[row])
|
||||
|
||||
[arrow_row] = (await (await tbl.search()).to_arrow()).to_pylist()
|
||||
assert arrow_row == row
|
||||
[item] = await (await tbl.search()).to_pydantic(Item)
|
||||
assert item.model_dump() == {"value": 0, "record_id": 42}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_field_name_fallback_preserves_populate_by_name_reader_async(
|
||||
mem_db_async,
|
||||
):
|
||||
class Item(LanceModel):
|
||||
model_config = pydantic.ConfigDict(populate_by_name=True)
|
||||
value: int = Field(default=0, validation_alias="id")
|
||||
id: int = Field(default=-1, alias="recordId")
|
||||
|
||||
row = {"value": 1}
|
||||
assert Item(**row).model_dump() == {"value": 1, "id": -1}
|
||||
tbl = await mem_db_async.create_table("populate_by_name_readers", data=[row])
|
||||
|
||||
[arrow_row] = (await (await tbl.search()).to_arrow()).to_pylist()
|
||||
assert arrow_row == row
|
||||
[item] = await (await tbl.search()).to_pydantic(Item)
|
||||
assert item.model_dump() == {"value": 1, "id": -1}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.skipif(
|
||||
Version(pydantic.VERSION) < Version("2.11"),
|
||||
reason="validate_by_name requires pydantic>=2.11",
|
||||
)
|
||||
async def test_explicit_validate_by_name_false_overrides_populate_by_name_async(
|
||||
mem_db_async,
|
||||
):
|
||||
class Item(LanceModel):
|
||||
model_config = pydantic.ConfigDict(
|
||||
populate_by_name=True,
|
||||
validate_by_name=False,
|
||||
)
|
||||
user_id: int = Field(default=0, alias="userId")
|
||||
|
||||
tbl = await mem_db_async.create_table(
|
||||
"validate_by_name_precedence_items", schema=Item
|
||||
)
|
||||
item = Item(userId=42)
|
||||
assert item.user_id == 42
|
||||
await tbl.add([item])
|
||||
assert (await tbl.schema()).names == ["user_id"]
|
||||
assert (await (await tbl.search()).to_arrow()).to_pylist() == [{"user_id": 42}]
|
||||
|
||||
[item] = await (await tbl.search()).to_pydantic(Item)
|
||||
assert item.user_id == 42
|
||||
|
||||
|
||||
def test_enum_types():
|
||||
"""Enum fields should map to the Arrow type of their value (issue #1846)."""
|
||||
|
||||
@@ -817,6 +1117,36 @@ def test_enum_types():
|
||||
assert schema.field("opt_status").nullable
|
||||
|
||||
|
||||
@pytest.mark.parametrize("container", ["field", "optional", "list", "nested"])
|
||||
@pytest.mark.parametrize("values", [("text", 7), (1, 2.5), (False, "no")])
|
||||
def test_mixed_enum_values_are_rejected(container, values):
|
||||
Mixed = Enum("Mixed", {"FIRST": values[0], "SECOND": values[1]})
|
||||
|
||||
class Nested(pydantic.BaseModel):
|
||||
value: Mixed
|
||||
|
||||
annotation = {
|
||||
"field": Mixed,
|
||||
"optional": Optional[Mixed],
|
||||
"list": List[Mixed],
|
||||
"nested": Nested,
|
||||
}[container]
|
||||
model = pydantic.create_model("Model", value=(annotation, ...))
|
||||
|
||||
with pytest.raises(TypeError, match="Enum.*Mixed.*same type"):
|
||||
pydantic_to_schema(model)
|
||||
|
||||
|
||||
def test_empty_enum_schema_is_unchanged():
|
||||
class Empty(Enum):
|
||||
pass
|
||||
|
||||
class Model(pydantic.BaseModel):
|
||||
value: Empty
|
||||
|
||||
assert pydantic_to_schema(Model).field("value").type == pa.utf8()
|
||||
|
||||
|
||||
def test_plain_enum_values_are_written(mem_db):
|
||||
"""Members of an Enum without a str/int mixin are written as their values."""
|
||||
|
||||
@@ -864,3 +1194,111 @@ def test_plain_enum_values_are_written(mem_db):
|
||||
{"color": "blue", "priority": 1, "opt_color": None},
|
||||
]
|
||||
assert tbl.search().to_pydantic(TestModel) == rows
|
||||
|
||||
|
||||
def test_literal_time_and_timedelta_types():
|
||||
class TestModel(pydantic.BaseModel):
|
||||
status: Literal["todo", "done"]
|
||||
priority: Literal[1, 2, 3]
|
||||
flag: Literal[True]
|
||||
tags: List[Literal["a", "b"]]
|
||||
opt_status: Optional[Literal["todo", "done"]] = None
|
||||
starts: time
|
||||
starts_list: List[time]
|
||||
opt_starts: Optional[time] = None
|
||||
duration: timedelta
|
||||
durations: List[timedelta]
|
||||
|
||||
schema = pydantic_to_schema(TestModel)
|
||||
|
||||
assert schema.field("status").type == pa.utf8()
|
||||
assert schema.field("priority").type == pa.int64()
|
||||
assert schema.field("flag").type == pa.bool_()
|
||||
assert schema.field("tags").type == pa.list_(pa.utf8())
|
||||
assert schema.field("opt_status").type == pa.utf8()
|
||||
assert schema.field("opt_status").nullable
|
||||
assert schema.field("starts").type == pa.time64("us")
|
||||
assert schema.field("starts_list").type == pa.list_(pa.time64("us"))
|
||||
assert schema.field("opt_starts").type == pa.time64("us")
|
||||
assert schema.field("opt_starts").nullable
|
||||
assert schema.field("duration").type == pa.duration("us")
|
||||
assert schema.field("durations").type == pa.list_(pa.duration("us"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"annotation",
|
||||
[
|
||||
Literal["a", 1],
|
||||
Optional[Literal["a", 1]],
|
||||
List[Literal["a", 1]],
|
||||
],
|
||||
ids=["field", "optional", "list"],
|
||||
)
|
||||
def test_literal_with_mixed_value_types_raises_type_error(annotation):
|
||||
TestModel = pydantic.create_model("TestModel", value=(annotation, ...))
|
||||
|
||||
with pytest.raises(TypeError, match="same type"):
|
||||
pydantic_to_schema(TestModel)
|
||||
|
||||
|
||||
def test_literal_time_and_timedelta_round_trip(mem_db):
|
||||
class TestModel(LanceModel):
|
||||
status: Literal["todo", "done"]
|
||||
starts: time
|
||||
duration: timedelta
|
||||
vector: Vector(2)
|
||||
|
||||
rows = [
|
||||
TestModel(
|
||||
status="done",
|
||||
starts=time(9, 30),
|
||||
duration=timedelta(minutes=45),
|
||||
vector=[1.0, 2.0],
|
||||
),
|
||||
TestModel(
|
||||
status="todo",
|
||||
starts=time(17, 0, 0, 250),
|
||||
duration=timedelta(days=1, microseconds=5),
|
||||
vector=[3.0, 4.0],
|
||||
),
|
||||
]
|
||||
tbl = mem_db.create_table("test", schema=TestModel)
|
||||
tbl.add(rows)
|
||||
|
||||
assert tbl.search().to_pydantic(TestModel) == rows
|
||||
|
||||
|
||||
@pytest.mark.parametrize("container", ["field", "list", "nested", "enum"])
|
||||
def test_tz_aware_time_is_rejected_before_write(mem_db, container):
|
||||
class Nested(LanceModel):
|
||||
starts: time
|
||||
|
||||
aware = time(9, 30, tzinfo=timezone(timedelta(hours=5, minutes=30)))
|
||||
AwareTime = Enum("AwareTime", {"MORNING": aware})
|
||||
Model = pydantic.create_model(
|
||||
"TestModel",
|
||||
__base__=LanceModel,
|
||||
**{
|
||||
container: {
|
||||
"field": (time, ...),
|
||||
"list": (List[time], ...),
|
||||
"nested": (Nested, ...),
|
||||
"enum": (AwareTime, ...),
|
||||
}[container]
|
||||
},
|
||||
)
|
||||
row = Model(
|
||||
**{
|
||||
container: {
|
||||
"field": aware,
|
||||
"list": [aware],
|
||||
"nested": Nested(starts=aware),
|
||||
"enum": AwareTime.MORNING,
|
||||
}[container]
|
||||
}
|
||||
)
|
||||
|
||||
table_name = f"timezone_aware_{container}"
|
||||
with pytest.raises(ValueError, match="timezone-naive wall-clock.*tzinfo"):
|
||||
mem_db.create_table(table_name, data=[row])
|
||||
assert table_name not in mem_db.table_names()
|
||||
|
||||
@@ -1308,6 +1308,28 @@ async def test_invalid_nprobes_async(table_async: AsyncTable):
|
||||
)
|
||||
|
||||
|
||||
def test_approx_mode_works_sync(table):
|
||||
for mode in ["fast", "normal", "accurate"]:
|
||||
LanceVectorQueryBuilder(table, [0, 0], "vector").approx_mode(mode).to_list()
|
||||
|
||||
|
||||
def test_invalid_approx_mode_sync(table):
|
||||
with pytest.raises(ValueError, match="approx_mode must be one of"):
|
||||
LanceVectorQueryBuilder(table, [0, 0], "vector").approx_mode("turbo").to_list()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approx_mode_works_async(table_async: AsyncTable):
|
||||
for mode in ["fast", "normal", "accurate"]:
|
||||
await table_async.vector_search([0, 0]).approx_mode(mode).to_list()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_approx_mode_async(table_async: AsyncTable):
|
||||
with pytest.raises(ValueError, match="approx_mode must be one of"):
|
||||
table_async.vector_search([0, 0]).approx_mode("turbo")
|
||||
|
||||
|
||||
def test_query_builder_with_prefilter(table):
|
||||
df = (
|
||||
LanceVectorQueryBuilder(table, [0, 0], "vector")
|
||||
@@ -1962,6 +1984,9 @@ def test_query_serialization_sync(table: lancedb.table.Table):
|
||||
q = table.search([5.0, 6.0]).ef(7).to_query_object()
|
||||
check_set_props(q, ef=7, vector_column="vector", vector=[5.0, 6.0])
|
||||
|
||||
q = table.search([5.0, 6.0]).approx_mode("fast").to_query_object()
|
||||
check_set_props(q, approx_mode="fast", vector_column="vector", vector=[5.0, 6.0])
|
||||
|
||||
q = table.search([5.0, 6.0]).bypass_vector_index().to_query_object()
|
||||
check_set_props(
|
||||
q, bypass_vector_index=True, vector_column="vector", vector=[5.0, 6.0]
|
||||
@@ -2190,6 +2215,19 @@ async def test_query_serialization_async(table_async: AsyncTable):
|
||||
limit=10,
|
||||
)
|
||||
|
||||
q = (await table_async.search([5.0, 6.0])).approx_mode("fast").to_query_object()
|
||||
check_set_props(
|
||||
q,
|
||||
approx_mode="fast",
|
||||
vector=sample_vector,
|
||||
postfilter=False,
|
||||
minimum_nprobes=None,
|
||||
maximum_nprobes=None,
|
||||
with_row_id=False,
|
||||
bypass_vector_index=False,
|
||||
limit=10,
|
||||
)
|
||||
|
||||
q = (await table_async.search([5.0, 6.0])).bypass_vector_index().to_query_object()
|
||||
check_set_props(
|
||||
q,
|
||||
@@ -2228,6 +2266,20 @@ async def test_query_serialization_async(table_async: AsyncTable):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hybrid_query_serialization_async(table_async: AsyncTable):
|
||||
q = (
|
||||
table_async.query()
|
||||
.nearest_to([5.0, 6.0])
|
||||
.nearest_to_text(MatchQuery("dog", "text"))
|
||||
.ef(7)
|
||||
.approx_mode("fast")
|
||||
.to_query_object()
|
||||
)
|
||||
assert q.ef == 7
|
||||
assert q.approx_mode == "fast"
|
||||
|
||||
|
||||
def test_query_schema(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
tbl = db.create_table(
|
||||
@@ -2365,13 +2417,36 @@ 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]
|
||||
|
||||
|
||||
@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):
|
||||
@@ -2380,6 +2455,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
|
||||
|
||||
@@ -2394,6 +2470,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
|
||||
|
||||
@@ -2420,16 +2497,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):
|
||||
@@ -2585,17 +2658,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)
|
||||
@@ -2679,7 +2759,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:
|
||||
|
||||
@@ -13,6 +13,8 @@ from lancedb.namespace import LanceNamespaceDBConnection
|
||||
@pytest.mark.parametrize("seconds", [-1.0, -0.000001])
|
||||
@pytest.mark.parametrize("kind", ["sync", "namespace", "namespace_async", "client"])
|
||||
def test_negative_read_consistency_interval(tmp_path, seconds, kind):
|
||||
if kind == "client":
|
||||
pytest.importorskip("lance")
|
||||
interval = timedelta(seconds=seconds)
|
||||
with pytest.raises(ValueError, match="read_consistency_interval"):
|
||||
if kind == "sync":
|
||||
@@ -44,6 +46,8 @@ async def test_negative_async_read_consistency_interval(tmp_path, seconds):
|
||||
async def test_binding_rejects_invalid_read_consistency_interval(
|
||||
tmp_path, seconds, kind
|
||||
):
|
||||
if kind == "client":
|
||||
pytest.importorskip("lance")
|
||||
with pytest.raises(ValueError, match="read_consistency_interval"):
|
||||
if kind == "connect":
|
||||
await _lancedb.connect(str(tmp_path), read_consistency_interval=seconds)
|
||||
@@ -71,12 +75,23 @@ async def test_valid_read_consistency_intervals(tmp_path, interval):
|
||||
assert await db.get_read_consistency_interval() == interval
|
||||
db.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)]
|
||||
)
|
||||
def test_valid_namespace_read_consistency_intervals(tmp_path, interval):
|
||||
db = lancedb.connect_namespace(
|
||||
"dir", {"root": str(tmp_path / "namespace")}, read_consistency_interval=interval
|
||||
)
|
||||
assert db.read_consistency_interval == interval
|
||||
db.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)]
|
||||
)
|
||||
def test_valid_namespace_client_read_consistency_intervals(tmp_path, interval):
|
||||
pytest.importorskip("lance")
|
||||
client = connect_namespace_client("dir", {"root": str(tmp_path / "client")})
|
||||
db = LanceNamespaceDBConnection(client, read_consistency_interval=interval)
|
||||
assert db.read_consistency_interval == interval
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -87,7 +87,7 @@ async def test_remote_create_rejects_write_options(storage_options, empty):
|
||||
kwargs["data"] = [{"value": 1}]
|
||||
async with mock_lancedb_connection_async(handler) as db:
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="write_options.*LanceDB Distributed"
|
||||
NotImplementedError, match="write_options.*LanceDB Enterprise"
|
||||
):
|
||||
await db.create_table("t", storage_options=storage_options, **kwargs)
|
||||
assert requests == []
|
||||
@@ -110,7 +110,7 @@ def test_sync_remote_create_rejects_write_options(options):
|
||||
request.end_headers()
|
||||
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Enterprise"):
|
||||
db.create_table("t", [{"value": 1}], **options)
|
||||
assert requests == []
|
||||
|
||||
@@ -131,11 +131,11 @@ async def test_remote_open_rejects_local_options(options, asynchronous):
|
||||
|
||||
if asynchronous:
|
||||
async with mock_lancedb_connection_async(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Enterprise"):
|
||||
await db.open_table("t", **options)
|
||||
else:
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="LanceDB Enterprise"):
|
||||
db.open_table("t", **options)
|
||||
assert requests == []
|
||||
|
||||
@@ -151,6 +151,6 @@ async def test_remote_open_rejects_location():
|
||||
request.wfile.write(b'{"version": 1, "schema": {"fields": []}}')
|
||||
|
||||
async with mock_lancedb_connection_async(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="location.*LanceDB Distributed"):
|
||||
with pytest.raises(NotImplementedError, match="location.*LanceDB Enterprise"):
|
||||
await db.open_table("t", location="/tmp/zzz")
|
||||
assert requests == []
|
||||
|
||||
@@ -28,6 +28,7 @@ from lancedb.rerankers import (
|
||||
WatsonxReranker,
|
||||
)
|
||||
from lancedb.table import LanceTable
|
||||
from lancedb.rerankers.base import Reranker
|
||||
|
||||
|
||||
def get_test_table(tmp_path):
|
||||
@@ -126,7 +127,7 @@ def _run_test_reranker(
|
||||
if deterministic:
|
||||
assert result1 == result2
|
||||
|
||||
query_vector = table.to_pandas()["vector"][0]
|
||||
query_vector = table.to_arrow()["vector"][0].as_py()
|
||||
result = (
|
||||
table.search(query_type="hybrid", vector_column_name="vector")
|
||||
.vector(query_vector)
|
||||
@@ -249,7 +250,7 @@ def _run_test_hybrid_reranker(reranker, tmp_path):
|
||||
assert result1 == result3 # 2 & 3 should be the same as they use score as score
|
||||
|
||||
query = "Our father who art in heaven"
|
||||
query_vector = table.to_pandas()["vector"][0]
|
||||
query_vector = table.to_arrow()["vector"][0].as_py()
|
||||
result = (
|
||||
table.search(query_type="hybrid", vector_column_name="vector")
|
||||
.vector(query_vector)
|
||||
@@ -358,6 +359,19 @@ def test_mrr_reranker(tmp_path):
|
||||
assert len(result_deduped) == len(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deduplicate", [False, True])
|
||||
def test_base_reranker_multivector_empty_input(deduplicate):
|
||||
class VectorReranker(Reranker):
|
||||
def rerank_hybrid(self, query, vector_results, fts_results):
|
||||
raise AssertionError("should not rerank")
|
||||
|
||||
def rerank_vector(self, query, vector_results):
|
||||
raise AssertionError("should not rerank")
|
||||
|
||||
with pytest.raises(ValueError, match="vector_results must not be empty"):
|
||||
VectorReranker().rerank_multivector([], None, deduplicate=deduplicate)
|
||||
|
||||
|
||||
def test_mrr_reranker_empty_input():
|
||||
reranker = MRRReranker()
|
||||
with pytest.raises(ValueError, match="must not be empty"):
|
||||
@@ -836,6 +850,56 @@ def test_empty_hybrid_result_reranker():
|
||||
assert "_rowid" in result.column_names
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reranker_cls", [LinearCombinationReranker, RRFReranker])
|
||||
@pytest.mark.parametrize("return_score", ["relevance", "all"])
|
||||
def test_empty_hybrid_result_keeps_reranker_columns(
|
||||
tmp_path, reranker_cls, return_score
|
||||
):
|
||||
# A filter that matches nothing must not change which columns come back.
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"t",
|
||||
pa.table(
|
||||
{
|
||||
"text": ["red fox", "blue fox"],
|
||||
"vector": pa.array([[1.0, 2.0], [3.0, 4.0]], pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
table.create_fts_index("text")
|
||||
reranker = reranker_cls(return_score=return_score)
|
||||
|
||||
def columns(where):
|
||||
query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("fox")
|
||||
query = query.where(where, prefilter=True).rerank(reranker)
|
||||
return query.to_arrow().column_names
|
||||
|
||||
assert columns("text = 'none'") == columns("text != 'none'")
|
||||
|
||||
|
||||
def test_empty_hybrid_result_skips_keep_relevance_score_override(tmp_path):
|
||||
# An override written for non-empty results must not run on the empty path.
|
||||
class FirstRowReranker(LinearCombinationReranker):
|
||||
def _keep_relevance_score(self, combined_results):
|
||||
combined_results["_relevance_score"][0]
|
||||
return super()._keep_relevance_score(combined_results)
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"t",
|
||||
pa.table(
|
||||
{
|
||||
"text": ["red fox", "blue fox"],
|
||||
"vector": pa.array([[1.0, 2.0], [3.0, 4.0]], pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
table.create_fts_index("text")
|
||||
query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("fox")
|
||||
query = query.where("text = 'none'", prefilter=True).rerank(FirstRowReranker())
|
||||
assert query.to_arrow().num_rows == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("norm", ["score", "rank"])
|
||||
def test_hybrid_return_all_restores_original_scores(norm):
|
||||
from lancedb.query import LanceHybridQueryBuilder
|
||||
@@ -1100,6 +1164,52 @@ def test_linear_combination_missing_fts_is_penalised():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("empty_side", ["vector", "fts"])
|
||||
def test_linear_combination_empty_side_scores_are_null(empty_side):
|
||||
"""With return_score="all", the missing side's score column is null, not NaN."""
|
||||
from lancedb.query import LanceHybridQueryBuilder
|
||||
|
||||
vector_results = pa.table(
|
||||
{
|
||||
"_rowid": pa.array([1, 2], pa.uint64()),
|
||||
"_distance": pa.array([0.1, 0.2], pa.float32()),
|
||||
}
|
||||
)
|
||||
fts_results = pa.table(
|
||||
{
|
||||
"_rowid": pa.array([1, 2], pa.uint64()),
|
||||
"_score": pa.array([5.0, 4.0], pa.float32()),
|
||||
}
|
||||
)
|
||||
if empty_side == "vector":
|
||||
expected_present = fts_results["_score"].to_pylist()
|
||||
vector_results = vector_results.slice(0, 0)
|
||||
missing = "_distance"
|
||||
present = "_score"
|
||||
else:
|
||||
expected_present = vector_results["_distance"].to_pylist()
|
||||
fts_results = fts_results.slice(0, 0)
|
||||
missing = "_score"
|
||||
present = "_distance"
|
||||
|
||||
result = LanceHybridQueryBuilder._combine_hybrid_results(
|
||||
fts_results=fts_results,
|
||||
vector_results=vector_results,
|
||||
norm="score",
|
||||
fts_query="query",
|
||||
reranker=LinearCombinationReranker(return_score="all"),
|
||||
limit=10,
|
||||
with_row_ids=True,
|
||||
)
|
||||
|
||||
assert result[missing].type == pa.float32()
|
||||
assert result[missing].null_count == len(result) == 2
|
||||
assert result[present].to_pylist() == expected_present
|
||||
assert result["_relevance_score"].to_pylist() == sorted(
|
||||
result["_relevance_score"].to_pylist(), reverse=True
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("WATSONX_API_KEY") is None
|
||||
or (
|
||||
|
||||
@@ -281,3 +281,63 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent():
|
||||
received = echoed.column("vector").combine_chunks().flatten().to_numpy()
|
||||
assert received.view(np.uint32).tolist() == vector.view(np.uint32).tolist()
|
||||
assert echoed.column("k").to_pylist() == [10]
|
||||
|
||||
|
||||
@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")
|
||||
from lancedb.exceptions import JobFailedError, ColumnNotFoundError
|
||||
from lancedb.remote.errors import SqlColumnNotFoundError
|
||||
|
||||
request_ids = []
|
||||
|
||||
class Metadata(flight.ServerMiddleware):
|
||||
def sending_headers(self):
|
||||
headers = {
|
||||
"x-lancedb-error-code": "column_not_found",
|
||||
"x-job-request-id": "worker-request",
|
||||
}
|
||||
if job_id is not None:
|
||||
headers["x-lancedb-sql-job-id"] = job_id
|
||||
return headers
|
||||
|
||||
class Factory(flight.ServerMiddlewareFactory):
|
||||
def start_call(self, info, headers):
|
||||
request_ids.append(headers["x-request-id"][0])
|
||||
return Metadata()
|
||||
|
||||
class RejectingServer(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0", middleware={"metadata": Factory()})
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
context.add_trailer("x-lancedb-error-code", "column_not_found")
|
||||
context.add_trailer("x-job-request-id", "worker-request")
|
||||
if job_id is not None:
|
||||
context.add_trailer("x-lancedb-sql-job-id", job_id)
|
||||
raise pa.ArrowInvalid("No column 'missing' in table events")
|
||||
|
||||
with RejectingServer() as server:
|
||||
db = lancedb.connect(
|
||||
"db://analytics",
|
||||
api_key="test-key",
|
||||
host_override="http://localhost:10024",
|
||||
sql_host_override=f"grpc://127.0.0.1:{server.port}",
|
||||
)
|
||||
expected = JobFailedError if job_id is not None else SqlColumnNotFoundError
|
||||
with pytest.raises(expected) as exc_info:
|
||||
db.execute_query("SELECT missing FROM events").read_all()
|
||||
error = exc_info.value
|
||||
if job_id is not None:
|
||||
assert error.job_id == job_id
|
||||
assert error.request_id == request_ids[-1]
|
||||
assert error.job_request_id == "worker-request"
|
||||
error = error.__cause__
|
||||
assert isinstance(error, SqlColumnNotFoundError)
|
||||
assert isinstance(error, ColumnNotFoundError)
|
||||
assert error.request_id == request_ids[-1]
|
||||
assert error.job_id == job_id
|
||||
assert error.job_request_id == "worker-request"
|
||||
assert error.grpc_code == 3
|
||||
assert str(error).startswith("No column 'missing' in table events")
|
||||
assert not str(error).startswith("SQL error")
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import pyarrow as pa
|
||||
import pyarrow.flight as flight
|
||||
|
||||
import lancedb
|
||||
from lancedb.authz import Object, Privilege
|
||||
from lancedb.db import AsyncConnection, DBConnection
|
||||
from lancedb.catalog import Catalog, AsyncCatalog
|
||||
from lancedb.storage_integration import SecretReference, StorageIntegrationInfo
|
||||
|
||||
|
||||
INFO = json.loads(
|
||||
(
|
||||
Path(__file__).parents[3]
|
||||
/ "rust/lancedb/tests/fixtures/storage_integration.json"
|
||||
).read_text()
|
||||
)
|
||||
NAME = "raw"
|
||||
ROLE = "arn:aws:iam::123456789012:role/access"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def remote_server(text_type=pa.string()):
|
||||
calls = []
|
||||
info = dict(INFO)
|
||||
|
||||
class Server(flight.FlightServerBase):
|
||||
def __init__(self):
|
||||
super().__init__("grpc://127.0.0.1:0")
|
||||
|
||||
def do_get(self, context, ticket):
|
||||
command = ticket.ticket
|
||||
calls.append(command)
|
||||
if b"SHOW STORAGE INTEGRATIONS" in command:
|
||||
result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
|
||||
elif b"DROP STORAGE INTEGRATION" in command:
|
||||
result = pa.table({"dropped": [True]})
|
||||
else:
|
||||
if b"STORAGE_PROVIDER = 'HUGGINGFACE'" in command:
|
||||
info.update(
|
||||
storage_provider="HUGGINGFACE",
|
||||
storage_prefix="hf://datasets/acme/private/raw/",
|
||||
aws_role_arn=None,
|
||||
aws_region=None,
|
||||
aws_account_id="",
|
||||
aws_iam_principal_arn="",
|
||||
trust_policy=None,
|
||||
permissions_policy=None,
|
||||
configuration_instructions=(
|
||||
"Grant the referenced identity access to the prefix."
|
||||
),
|
||||
huggingface_token_secret=(
|
||||
dict(
|
||||
database="shared",
|
||||
namespace_path=["credentials"],
|
||||
name="hf_token",
|
||||
)
|
||||
if b"HUGGINGFACE_TOKEN_SECRET" in command
|
||||
else None
|
||||
),
|
||||
)
|
||||
if b"GCP_CREDENTIALS_JSON_SECRET" in command:
|
||||
info.update(
|
||||
storage_provider="GCP",
|
||||
storage_prefix="gs://customer-data/raw/",
|
||||
aws_role_arn=None,
|
||||
aws_region=None,
|
||||
aws_account_id="",
|
||||
aws_iam_principal_arn="",
|
||||
trust_policy=None,
|
||||
permissions_policy=None,
|
||||
configuration_instructions=(
|
||||
"Grant the referenced identity access to the prefix."
|
||||
),
|
||||
gcp_credentials_json_secret=dict(
|
||||
database="shared",
|
||||
namespace_path=["credentials"],
|
||||
name="gcp",
|
||||
),
|
||||
)
|
||||
if b"STORAGE_AZURE_STORAGE_ACCOUNT" in command:
|
||||
info.update(
|
||||
storage_provider="AZURE",
|
||||
storage_prefix="az://customer-data@customeraccount.blob.core.windows.net/raw/",
|
||||
azure_storage_account="customeraccount",
|
||||
aws_role_arn=None,
|
||||
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_AWS_ACCESS_KEY_ID_SECRET" in command:
|
||||
info["aws_role_arn"] = None
|
||||
info["trust_policy"] = None
|
||||
info["aws_access_key_id_secret"] = {
|
||||
"database": "shared",
|
||||
"namespace_path": ["credentials"],
|
||||
"name": "access_key",
|
||||
}
|
||||
info["aws_secret_access_key_secret"] = {
|
||||
"database": "shared",
|
||||
"namespace_path": ["credentials"],
|
||||
"name": "secret_key",
|
||||
}
|
||||
row = dict(info)
|
||||
for field in [
|
||||
"namespace_path",
|
||||
"trust_policy",
|
||||
"permissions_policy",
|
||||
"aws_access_key_id_secret",
|
||||
"aws_secret_access_key_secret",
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
"gcp_credentials_json_secret",
|
||||
"huggingface_token_secret",
|
||||
]:
|
||||
if field in row and row[field] is not None:
|
||||
row[field] = json.dumps(row[field])
|
||||
row.setdefault("aws_access_key_id_secret", None)
|
||||
row.setdefault("aws_secret_access_key_secret", None)
|
||||
result = pa.table(
|
||||
{
|
||||
field: pa.array(
|
||||
[value],
|
||||
type=(
|
||||
pa.bool_()
|
||||
if field == "access_verified"
|
||||
else pa.int64()
|
||||
if field == "created_at_millis"
|
||||
else text_type
|
||||
),
|
||||
)
|
||||
for field, value in row.items()
|
||||
}
|
||||
)
|
||||
return flight.RecordBatchStream(result)
|
||||
|
||||
with Server() as server:
|
||||
yield f"grpc://127.0.0.1:{server.port}", calls
|
||||
|
||||
|
||||
def connect(host):
|
||||
return lancedb.connect(
|
||||
"db://default",
|
||||
api_key="fake",
|
||||
sql_host_override=host,
|
||||
host_override="http://127.0.0.1:1",
|
||||
)
|
||||
|
||||
|
||||
def test_storage_integration_methods_belong_to_databases():
|
||||
assert hasattr(DBConnection, "create_storage_integration")
|
||||
assert hasattr(AsyncConnection, "create_storage_integration")
|
||||
assert not hasattr(Catalog, "create_storage_integration")
|
||||
assert not hasattr(AsyncCatalog, "create_storage_integration")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text_type", [pa.string(), pa.large_string(), pa.string_view()]
|
||||
)
|
||||
def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
|
||||
with remote_server(text_type) as (host, calls):
|
||||
db = connect(host)
|
||||
info = db.create_storage_integration(
|
||||
NAME, INFO["storage_prefix"], aws_role_arn=ROLE
|
||||
)
|
||||
assert isinstance(info, lancedb.StorageIntegrationInfo)
|
||||
assert info.aws_account_id == "001122334455"
|
||||
assert not info.access_verified
|
||||
assert (
|
||||
info.trust_policy["Statement"][0]["Condition"]["StringEquals"][
|
||||
"sts:ExternalId"
|
||||
]
|
||||
== info.aws_external_id
|
||||
)
|
||||
assert db.describe_storage_integration(NAME) == info
|
||||
listing = db.list_storage_integrations(page_limit=1)
|
||||
assert len(calls) == 2
|
||||
assert list(listing) == ["raw", "zeta"]
|
||||
assert db.drop_storage_integration(NAME) is None
|
||||
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]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_storage_integration_lifecycle():
|
||||
with remote_server() as (host, _calls):
|
||||
db = await lancedb.connect_async(
|
||||
"db://default",
|
||||
api_key="fake",
|
||||
sql_host_override=host,
|
||||
host_override="http://127.0.0.1:1",
|
||||
)
|
||||
info = await db.create_storage_integration(
|
||||
NAME, INFO["storage_prefix"], aws_role_arn=ROLE
|
||||
)
|
||||
assert await db.describe_storage_integration(NAME) == info
|
||||
assert [name async for name in db.list_storage_integrations()] == [
|
||||
"raw",
|
||||
"zeta",
|
||||
]
|
||||
await db.drop_storage_integration(NAME)
|
||||
with pytest.raises(ValueError):
|
||||
await db.describe_storage_integration("a//b")
|
||||
|
||||
|
||||
def test_integration_authorization_object_and_creation_privilege():
|
||||
value = Object.storage_integration(database="default", name=NAME)
|
||||
assert str(value) == "storage_integration:default:public$raw"
|
||||
assert Privilege.CREATE_STORAGE_INTEGRATION.value == "CREATE_STORAGE_INTEGRATION"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text_type", [pa.string(), pa.large_string(), pa.string_view()]
|
||||
)
|
||||
def test_static_credentials_use_explicit_cross_database_secret_references(text_type):
|
||||
with remote_server(text_type) as (host, calls):
|
||||
db = connect(host)
|
||||
info = db.create_storage_integration(
|
||||
"raw",
|
||||
INFO["storage_prefix"],
|
||||
aws_access_key_id_secret=SecretReference(
|
||||
"access_key", database="shared", namespace_path=("credentials",)
|
||||
),
|
||||
aws_secret_access_key_secret=SecretReference(
|
||||
"secret_key", database="shared", namespace_path=("credentials",)
|
||||
),
|
||||
)
|
||||
assert info.aws_role_arn is None
|
||||
assert db.describe_storage_integration("raw") == info
|
||||
assert info.aws_access_key_id_secret.database == "shared"
|
||||
assert b"STORAGE_AWS_ROLE_ARN" not in calls[0]
|
||||
assert (
|
||||
b'STORAGE_AWS_ACCESS_KEY_ID_SECRET = "shared"."credentials"."access_key"'
|
||||
in calls[0]
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
db.create_storage_integration(
|
||||
"bad",
|
||||
INFO["storage_prefix"],
|
||||
aws_role_arn=ROLE,
|
||||
aws_access_key_id_secret="key",
|
||||
)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_metadata_defaults_an_omitted_role_to_none():
|
||||
data = dict(INFO)
|
||||
data.pop("aws_role_arn")
|
||||
assert StorageIntegrationInfo(**data).aws_role_arn is None
|
||||
|
||||
|
||||
def test_namespace_connections_keep_existing_apis_available(tmp_path):
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
|
||||
with pytest.raises(NotImplementedError):
|
||||
db.create_storage_integration("raw", "s3://customer/raw/", aws_role_arn=ROLE)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text_type", [pa.string(), pa.large_string(), pa.string_view()]
|
||||
)
|
||||
def test_azure_lifecycle_uses_three_qualified_secret_references(text_type):
|
||||
with remote_server(text_type) as (host, calls):
|
||||
db = connect(host)
|
||||
refs = [
|
||||
SecretReference(name, database="shared", namespace_path=("credentials",))
|
||||
for name in ("tenant", "client", "credential")
|
||||
]
|
||||
info = db.create_storage_integration(
|
||||
"blobs",
|
||||
"az://customer-data/raw/",
|
||||
storage_provider="AZURE",
|
||||
azure_storage_account="customeraccount",
|
||||
azure_tenant_id_secret=refs[0],
|
||||
azure_client_id_secret=refs[1],
|
||||
azure_client_secret_secret=refs[2],
|
||||
)
|
||||
assert info.storage_provider == "AZURE"
|
||||
assert info.azure_storage_account == "customeraccount"
|
||||
assert info.azure_tenant_id_secret.name == "tenant"
|
||||
assert info.azure_client_id_secret.database == "shared"
|
||||
assert info.azure_client_secret_secret.name == "credential"
|
||||
assert info.trust_policy is None
|
||||
assert info.permissions_policy is None
|
||||
assert not info.access_verified
|
||||
assert db.describe_storage_integration("blobs") == info
|
||||
assert list(db.list_storage_integrations()) == ["raw", "zeta"]
|
||||
db.drop_storage_integration("blobs")
|
||||
sql = calls[0]
|
||||
assert b"STORAGE_PROVIDER = 'AZURE'" in sql
|
||||
assert b"STORAGE_AZURE_STORAGE_ACCOUNT = 'customeraccount'" in sql
|
||||
assert (
|
||||
b'STORAGE_AZURE_CLIENT_SECRET_SECRET = "shared"."credentials"."credential"'
|
||||
in sql
|
||||
)
|
||||
assert b"STORAGE_AWS" not in sql
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_azure_requires_account_and_all_three_secret_references():
|
||||
with remote_server() as (host, calls):
|
||||
db = await lancedb.connect_async(
|
||||
"db://default",
|
||||
api_key="fake",
|
||||
sql_host_override=host,
|
||||
host_override="http://127.0.0.1:1",
|
||||
)
|
||||
config = dict(
|
||||
storage_provider="AZURE",
|
||||
azure_storage_account="customeraccount",
|
||||
azure_tenant_id_secret="tenant",
|
||||
azure_client_id_secret="client",
|
||||
azure_client_secret_secret="credential",
|
||||
)
|
||||
for missing in (
|
||||
"azure_storage_account",
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
):
|
||||
partial = dict(config)
|
||||
partial.pop(missing)
|
||||
with pytest.raises(ValueError):
|
||||
await db.create_storage_integration(
|
||||
"blobs", "az://customer-data/raw/", **partial
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
await db.create_storage_integration(
|
||||
"blobs", "az://customer-data/raw/", aws_role_arn=ROLE, **config
|
||||
)
|
||||
assert calls == []
|
||||
info = await db.create_storage_integration(
|
||||
"blobs", "az://customer-data/raw/", **config
|
||||
)
|
||||
assert info.storage_provider == "AZURE"
|
||||
assert b'STORAGE_AZURE_TENANT_ID_SECRET = "public"."tenant"' in calls[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text_type", [pa.string(), pa.large_string(), pa.string_view()]
|
||||
)
|
||||
def test_gcp_lifecycle_uses_one_qualified_json_secret(text_type):
|
||||
with remote_server(text_type) as (host, calls):
|
||||
db = connect(host)
|
||||
info = db.create_storage_integration(
|
||||
"gcs",
|
||||
"gs://customer-data/raw/",
|
||||
storage_provider="GCP",
|
||||
gcp_credentials_json_secret=SecretReference(
|
||||
"gcp", database="shared", namespace_path=("credentials",)
|
||||
),
|
||||
)
|
||||
assert info.storage_provider == "GCP"
|
||||
assert info.gcp_credentials_json_secret.name == "gcp"
|
||||
assert info.gcp_credentials_json_secret.database == "shared"
|
||||
assert info.aws_role_arn is None
|
||||
assert info.azure_storage_account is None
|
||||
assert info.aws_iam_principal_arn == ""
|
||||
assert info.trust_policy is None
|
||||
assert not info.access_verified
|
||||
assert db.describe_storage_integration("gcs") == info
|
||||
assert list(db.list_storage_integrations()) == ["raw", "zeta"]
|
||||
db.drop_storage_integration("gcs")
|
||||
assert b"STORAGE_PROVIDER = 'GCP'" in calls[0]
|
||||
assert b'GCP_CREDENTIALS_JSON_SECRET = "shared"."credentials"."gcp"' in calls[0]
|
||||
assert b"STORAGE_AWS" not in calls[0]
|
||||
assert b"STORAGE_AZURE" not in calls[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_gcp_requires_one_secret_and_rejects_other_cloud_options():
|
||||
with remote_server() as (host, calls):
|
||||
db = await lancedb.connect_async(
|
||||
"db://default",
|
||||
api_key="fake",
|
||||
sql_host_override=host,
|
||||
host_override="http://127.0.0.1:1",
|
||||
)
|
||||
for invalid in (
|
||||
{},
|
||||
{"gcp_credentials_json_secret": "gcp", "aws_role_arn": ROLE},
|
||||
{"gcp_credentials_json_secret": "gcp", "azure_storage_account": "account"},
|
||||
):
|
||||
with pytest.raises(ValueError):
|
||||
await db.create_storage_integration(
|
||||
"gcs", "gs://customer-data/raw/", storage_provider="GCP", **invalid
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
await db.create_storage_integration(
|
||||
"gcs",
|
||||
"gs://customer-data/raw/",
|
||||
aws_role_arn=ROLE,
|
||||
gcp_credentials_json_secret="gcp",
|
||||
)
|
||||
assert calls == []
|
||||
info = await db.create_storage_integration(
|
||||
"gcs",
|
||||
"gs://customer-data/raw/",
|
||||
storage_provider="GCP",
|
||||
gcp_credentials_json_secret="gcp",
|
||||
)
|
||||
assert info.storage_provider == "GCP"
|
||||
assert b'GCP_CREDENTIALS_JSON_SECRET = "public"."gcp"' in calls[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text_type", [pa.string(), pa.large_string(), pa.string_view()]
|
||||
)
|
||||
def test_huggingface_lifecycle_uses_one_qualified_token_secret(text_type):
|
||||
with remote_server(text_type) as (host, calls):
|
||||
db = connect(host)
|
||||
info = db.create_storage_integration(
|
||||
"hub",
|
||||
"hf://datasets/acme/private/raw/",
|
||||
storage_provider="HUGGINGFACE",
|
||||
huggingface_token_secret=SecretReference(
|
||||
"hf_token", database="shared", namespace_path=("credentials",)
|
||||
),
|
||||
)
|
||||
assert info.storage_provider == "HUGGINGFACE"
|
||||
assert info.huggingface_token_secret.name == "hf_token"
|
||||
assert info.huggingface_token_secret.database == "shared"
|
||||
assert info.aws_role_arn is None
|
||||
assert info.azure_storage_account is None
|
||||
assert info.aws_iam_principal_arn == ""
|
||||
assert info.trust_policy is None
|
||||
assert not info.access_verified
|
||||
assert db.describe_storage_integration("hub") == info
|
||||
assert list(db.list_storage_integrations()) == ["raw", "zeta"]
|
||||
db.drop_storage_integration("hub")
|
||||
assert b"STORAGE_PROVIDER = 'HUGGINGFACE'" in calls[0]
|
||||
assert (
|
||||
b'HUGGINGFACE_TOKEN_SECRET = "shared"."credentials"."hf_token"' in calls[0]
|
||||
)
|
||||
assert b"STORAGE_AWS" not in calls[0]
|
||||
assert b"STORAGE_AZURE" not in calls[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_huggingface_rejects_other_cloud_options():
|
||||
with remote_server() as (host, calls):
|
||||
db = await lancedb.connect_async(
|
||||
"db://default",
|
||||
api_key="fake",
|
||||
sql_host_override=host,
|
||||
host_override="http://127.0.0.1:1",
|
||||
)
|
||||
for invalid in (
|
||||
{"huggingface_token_secret": "hf_token", "aws_role_arn": ROLE},
|
||||
{
|
||||
"huggingface_token_secret": "hf_token",
|
||||
"azure_storage_account": "account",
|
||||
},
|
||||
):
|
||||
with pytest.raises(ValueError):
|
||||
await db.create_storage_integration(
|
||||
"hub",
|
||||
"hf://datasets/acme/private/raw/",
|
||||
storage_provider="HUGGINGFACE",
|
||||
**invalid,
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
await db.create_storage_integration(
|
||||
"hub",
|
||||
"hf://datasets/acme/private/raw/",
|
||||
aws_role_arn=ROLE,
|
||||
huggingface_token_secret="hf_token",
|
||||
)
|
||||
assert calls == []
|
||||
info = await db.create_storage_integration(
|
||||
"hub",
|
||||
"hf://datasets/acme/private/raw/",
|
||||
storage_provider="HUGGINGFACE",
|
||||
huggingface_token_secret="hf_token",
|
||||
)
|
||||
assert info.storage_provider == "HUGGINGFACE"
|
||||
assert b'HUGGINGFACE_TOKEN_SECRET = "public"."hf_token"' in calls[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text_type", [pa.string(), pa.large_string(), pa.string_view()]
|
||||
)
|
||||
def test_anonymous_huggingface_lifecycle_omits_token_secret(text_type):
|
||||
with remote_server(text_type) as (host, calls):
|
||||
db = connect(host)
|
||||
info = db.create_storage_integration(
|
||||
"public_hub",
|
||||
"hf://datasets/acme/public/raw/",
|
||||
storage_provider="HUGGINGFACE",
|
||||
)
|
||||
assert info.storage_provider == "HUGGINGFACE"
|
||||
assert info.huggingface_token_secret is None
|
||||
assert db.describe_storage_integration("public_hub") == info
|
||||
assert list(db.list_storage_integrations()) == ["raw", "zeta"]
|
||||
db.drop_storage_integration("public_hub")
|
||||
assert b"HUGGINGFACE_TOKEN_SECRET" not in calls[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_huggingface_allows_anonymous_access():
|
||||
with remote_server() as (host, calls):
|
||||
db = await lancedb.connect_async(
|
||||
"db://default",
|
||||
api_key="fake",
|
||||
sql_host_override=host,
|
||||
host_override="http://127.0.0.1:1",
|
||||
)
|
||||
info = await db.create_storage_integration(
|
||||
"public_hub",
|
||||
"hf://datasets/acme/public/raw/",
|
||||
storage_provider="HUGGINGFACE",
|
||||
)
|
||||
assert info.huggingface_token_secret is None
|
||||
assert b"HUGGINGFACE_TOKEN_SECRET" not in calls[0]
|
||||
@@ -10,10 +10,12 @@ import sys
|
||||
import threading
|
||||
import warnings
|
||||
import weakref
|
||||
from collections import UserDict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal, localcontext
|
||||
from time import sleep
|
||||
from types import MappingProxyType
|
||||
from typing import Any, List
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -31,6 +33,7 @@ from lancedb.db import AsyncConnection, DBConnection
|
||||
from lancedb.embeddings import EmbeddingFunctionConfig, EmbeddingFunctionRegistry
|
||||
from lancedb.expr import col, lit
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
from lancedb.scannable import to_scannable
|
||||
from lancedb.table import LanceTable
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -300,6 +303,7 @@ def test_table_to_pandas_invalid_blob_mode_non_blob_table(tmp_db: DBConnection):
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["lazy", "bytes", "descriptions"])
|
||||
def test_table_to_pandas_blob_modes(tmp_db: DBConnection, blob_mode):
|
||||
pytest.importorskip("pandas")
|
||||
pytest.importorskip("lance")
|
||||
table = tmp_db.create_table(
|
||||
f"test_to_pandas_blob_{blob_mode}",
|
||||
@@ -322,6 +326,7 @@ def test_table_to_pandas_blob_modes(tmp_db: DBConnection, blob_mode):
|
||||
|
||||
@pytest.mark.parametrize("blob_schema", ["v1", "v2"])
|
||||
def test_table_to_pandas_blob_bytes(tmp_db: DBConnection, blob_schema):
|
||||
pytest.importorskip("pandas")
|
||||
pytest.importorskip("lance")
|
||||
table = _blob_table(tmp_db, f"test_to_pandas_blob_{blob_schema}_bytes", blob_schema)
|
||||
|
||||
@@ -347,6 +352,7 @@ def test_table_to_pandas_kwargs(tmp_db: DBConnection):
|
||||
async def test_async_table_to_pandas_blob_bytes(
|
||||
tmp_db_async: AsyncConnection, blob_schema
|
||||
):
|
||||
pytest.importorskip("pandas")
|
||||
pytest.importorskip("lance")
|
||||
table = await _blob_table_async(
|
||||
tmp_db_async, f"test_async_to_pandas_blob_{blob_schema}_bytes", blob_schema
|
||||
@@ -930,8 +936,8 @@ def test_add_nullability(mem_db: DBConnection):
|
||||
assert table.to_arrow() == expected
|
||||
|
||||
|
||||
def test_add_pydantic_model(mem_db: DBConnection):
|
||||
pytest.importorskip("pandas")
|
||||
@pytest.fixture
|
||||
def pydantic_model_table(mem_db: DBConnection):
|
||||
# https://github.com/lancedb/lancedb/issues/562
|
||||
|
||||
class Metadata(BaseModel):
|
||||
@@ -949,9 +955,6 @@ def test_add_pydantic_model(mem_db: DBConnection):
|
||||
payload: Document
|
||||
|
||||
tbl = mem_db.create_table("mytable", schema=LanceSchema, mode="overwrite")
|
||||
assert tbl.schema == LanceSchema.to_arrow_schema()
|
||||
|
||||
# add works
|
||||
expected = LanceSchema(
|
||||
id="id",
|
||||
vector=[0.0, 0.0],
|
||||
@@ -961,11 +964,21 @@ def test_add_pydantic_model(mem_db: DBConnection):
|
||||
),
|
||||
)
|
||||
add_res = tbl.add([expected])
|
||||
return tbl, LanceSchema, expected, add_res
|
||||
|
||||
|
||||
def test_add_pydantic_model(pydantic_model_table):
|
||||
tbl, LanceSchema, expected, add_res = pydantic_model_table
|
||||
assert tbl.schema == LanceSchema.to_arrow_schema()
|
||||
assert add_res.version == 2
|
||||
|
||||
result = tbl.search([0.0, 0.0]).limit(1).to_pydantic(LanceSchema)[0]
|
||||
assert result == expected
|
||||
|
||||
|
||||
def test_add_pydantic_model_pandas(pydantic_model_table):
|
||||
pytest.importorskip("pandas")
|
||||
tbl, _, _, _ = pydantic_model_table
|
||||
flattened = tbl.search([0.0, 0.0]).limit(1).to_pandas(flatten=1)
|
||||
assert len(flattened.columns) == 6 # _distance is automatically added
|
||||
|
||||
@@ -1933,6 +1946,66 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
|
||||
)
|
||||
|
||||
|
||||
@patch("lancedb.table.AsyncTable.get_table_overrides")
|
||||
def test_get_table_overrides_method(mock_get_table_overrides, mem_db: DBConnection):
|
||||
expected = {"job_types": {"cleanup": {"enabled": False}}}
|
||||
mock_get_table_overrides.return_value = expected
|
||||
table = mem_db.create_table("test", data=[{"id": 1}])
|
||||
|
||||
assert table.get_table_overrides() == expected
|
||||
mock_get_table_overrides.assert_called_once_with()
|
||||
|
||||
|
||||
@patch("lancedb.table.AsyncTable.update_table_overrides")
|
||||
def test_update_table_overrides_method(
|
||||
mock_update_table_overrides, mem_db: DBConnection
|
||||
):
|
||||
overrides = {
|
||||
"job_types": {
|
||||
"cleanup": {"enabled": False},
|
||||
"index": {
|
||||
"scalar": {
|
||||
"reindex": {
|
||||
"row_threshold": 1000,
|
||||
"ttl_millis": 300000,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
mock_update_table_overrides.return_value = overrides
|
||||
table = mem_db.create_table("test", data=[{"id": 1}])
|
||||
|
||||
assert table.update_table_overrides(**overrides) == overrides
|
||||
mock_update_table_overrides.assert_called_once_with(**overrides)
|
||||
|
||||
|
||||
@patch("lancedb.table.AsyncTable.reset_table_overrides")
|
||||
def test_reset_table_overrides_method(mock_reset_table_overrides, mem_db: DBConnection):
|
||||
expected = {}
|
||||
mock_reset_table_overrides.return_value = expected
|
||||
table = mem_db.create_table("test", data=[{"id": 1}])
|
||||
|
||||
assert table.reset_table_overrides() == expected
|
||||
mock_reset_table_overrides.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_update_table_overrides_encodes_json():
|
||||
class MockInner:
|
||||
async def update_table_overrides(self, encoded_overrides):
|
||||
assert json.loads(encoded_overrides) == {
|
||||
"job_types": {"cleanup": {"enabled": False}}
|
||||
}
|
||||
return json.dumps({"job_types": {"cleanup": {"enabled": False}}})
|
||||
|
||||
table = lancedb.table.AsyncTable(MockInner())
|
||||
|
||||
assert await table.update_table_overrides(
|
||||
job_types={"cleanup": {"enabled": False}}
|
||||
) == {"job_types": {"cleanup": {"enabled": False}}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["legacy", "unified"])
|
||||
@pytest.mark.parametrize("cuda_failure", ["unavailable", "init_error"])
|
||||
def test_create_index_cuda_failure_suggests_cpu(
|
||||
@@ -2774,6 +2847,260 @@ def test_update(mem_db: DBConnection):
|
||||
assert np.allclose(v, np.array([[1.2, 1.9], [1.1, 1.1]]))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_api", [False, True])
|
||||
@pytest.mark.parametrize("use_sql", [False, True])
|
||||
@pytest.mark.parametrize("where", [None, "id = 1", col("id") == 1])
|
||||
@pytest.mark.parametrize("source_target", ["text", "`text`"])
|
||||
async def test_update_embedding_source_requires_vector(
|
||||
tmp_path, async_api, use_sql, where, source_target
|
||||
):
|
||||
func = MockTextEmbeddingFunction.create()
|
||||
|
||||
class Doc(LanceModel):
|
||||
id: int
|
||||
text: str = func.SourceField()
|
||||
vector: Vector(func.ndims()) = func.VectorField()
|
||||
|
||||
data = [{"id": 1, "text": "hello world"}, {"id": 2, "text": "goodbye world"}]
|
||||
if async_api:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", data, schema=Doc)
|
||||
before = await table.to_arrow()
|
||||
version = await table.version()
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", data, schema=Doc)
|
||||
before = table.to_arrow()
|
||||
version = table.version
|
||||
|
||||
# Rejection must happen before any rows or the table version change.
|
||||
updates = {source_target: "text || ' updated'" if use_sql else "updated text"}
|
||||
with pytest.raises(
|
||||
ValueError, match="source column 'text'.*vector column 'vector'"
|
||||
):
|
||||
if async_api:
|
||||
if use_sql:
|
||||
await table.update(where=where, updates_sql=updates)
|
||||
else:
|
||||
await table.update(updates, where=where)
|
||||
elif use_sql:
|
||||
table.update(where=where, values_sql=updates)
|
||||
else:
|
||||
table.update(where=where, values=updates)
|
||||
|
||||
if async_api:
|
||||
assert (await table.to_arrow()).equals(before)
|
||||
assert await table.version() == version
|
||||
else:
|
||||
assert table.to_arrow().equals(before)
|
||||
assert table.version == version
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_api", [False, True])
|
||||
@pytest.mark.parametrize("use_sql", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"source_target,vector_target,other_vector_target",
|
||||
[
|
||||
("text", "vector", "other_vector"),
|
||||
("`text`", "vector", "`other_vector`"),
|
||||
("text", "`vector`", "other_vector"),
|
||||
("`text`", "`vector`", "`other_vector`"),
|
||||
],
|
||||
)
|
||||
async def test_update_embedding_source_with_multiple_vectors(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
async_api,
|
||||
use_sql,
|
||||
source_target,
|
||||
vector_target,
|
||||
other_vector_target,
|
||||
):
|
||||
func = MockTextEmbeddingFunction.create()
|
||||
|
||||
class Doc(LanceModel):
|
||||
id: int
|
||||
text: str
|
||||
vector: Vector(func.ndims())
|
||||
other_vector: Vector(func.ndims())
|
||||
|
||||
configs = [
|
||||
EmbeddingFunctionConfig(
|
||||
source_column="text", vector_column=column, function=func
|
||||
)
|
||||
for column in ["vector", "other_vector"]
|
||||
]
|
||||
data = [{"id": 1, "text": "hello world"}, {"id": 2, "text": "goodbye world"}]
|
||||
if async_api:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"docs", data, schema=Doc, embedding_functions=configs
|
||||
)
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", data, schema=Doc, embedding_functions=configs)
|
||||
|
||||
async def update(values):
|
||||
if async_api:
|
||||
if use_sql:
|
||||
return await table.update(updates_sql=values, where=col("id") == 1)
|
||||
return await table.update(values, where=col("id") == 1)
|
||||
if use_sql:
|
||||
return table.update(values_sql=values, where=col("id") == 1)
|
||||
return table.update(values=values, where=col("id") == 1)
|
||||
|
||||
vector = func.compute_source_embeddings(["updated text"])[0]
|
||||
updates = {source_target: "updated text", vector_target: vector}
|
||||
if use_sql:
|
||||
updates = {
|
||||
key: table_module.value_to_sql(value) for key, value in updates.items()
|
||||
}
|
||||
|
||||
# Checking column dependencies must not require loading an embedding model.
|
||||
monkeypatch.delitem(EmbeddingFunctionRegistry.get_instance()._functions, "test")
|
||||
with pytest.raises(ValueError, match="vector column 'other_vector'"):
|
||||
await update(updates)
|
||||
|
||||
updates[other_vector_target] = updates[vector_target]
|
||||
result = await update(updates)
|
||||
assert result.rows_updated == 1
|
||||
actual = await table.to_arrow() if async_api else table.to_arrow()
|
||||
rows = actual.sort_by("id").to_pylist()
|
||||
assert rows[0]["text"] == "updated text"
|
||||
assert np.allclose(rows[0]["vector"], vector)
|
||||
assert np.allclose(rows[0]["other_vector"], vector)
|
||||
assert rows[1]["text"] == "goodbye world"
|
||||
|
||||
# Vector-only and unrelated updates are still allowed on embedding tables.
|
||||
assert (await update({vector_target: updates[vector_target]})).rows_updated == 1
|
||||
assert (await update({"id": "3" if use_sql else 3})).rows_updated == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_api", [False, True])
|
||||
@pytest.mark.parametrize("source_target", ["text", "`text`"])
|
||||
async def test_update_embedding_source_requires_native_vector_metadata(
|
||||
tmp_path, async_api, source_target
|
||||
):
|
||||
vector_type = pa.list_(pa.float32(), 2)
|
||||
column_definitions = [
|
||||
{"kind": "Physical"},
|
||||
{"kind": "Physical"},
|
||||
{
|
||||
"kind": {
|
||||
"Embedding": {
|
||||
"source_column": "text",
|
||||
"dest_column": "vector",
|
||||
"embedding_name": "native-explicit",
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": {
|
||||
"Embedding": {
|
||||
"source_column": "text",
|
||||
"dest_column": None,
|
||||
"embedding_name": "native-default",
|
||||
}
|
||||
}
|
||||
},
|
||||
]
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("text", pa.string()),
|
||||
pa.field("vector", vector_type),
|
||||
pa.field("text_embedding", vector_type),
|
||||
],
|
||||
metadata={
|
||||
b"lancedb::column_definitions": json.dumps(column_definitions).encode()
|
||||
},
|
||||
)
|
||||
data = pa.Table.from_pylist(
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"text": "hello world",
|
||||
"vector": [1.0, 0.0],
|
||||
"text_embedding": [0.0, 1.0],
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"text": "goodbye world",
|
||||
"vector": [0.5, 0.5],
|
||||
"text_embedding": [0.25, 0.75],
|
||||
},
|
||||
],
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
if async_api:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", data)
|
||||
table_schema = await table.schema()
|
||||
before = await table.to_arrow()
|
||||
version = await table.version()
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", data)
|
||||
table_schema = table.schema
|
||||
before = table.to_arrow()
|
||||
version = table.version
|
||||
|
||||
metadata = table_schema.metadata or {}
|
||||
assert b"lancedb::column_definitions" in metadata
|
||||
assert b"embedding_functions" not in metadata
|
||||
|
||||
async def update(values):
|
||||
if async_api:
|
||||
return await table.update(values, where="id = 1")
|
||||
return table.update(values=values, where="id = 1")
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="source column 'text'.*vector column 'vector'"
|
||||
):
|
||||
await update({source_target: "updated text"})
|
||||
|
||||
if async_api:
|
||||
assert (await table.to_arrow()).equals(before)
|
||||
assert await table.version() == version
|
||||
else:
|
||||
assert table.to_arrow().equals(before)
|
||||
assert table.version == version
|
||||
|
||||
with pytest.raises(
|
||||
ValueError, match="source column 'text'.*vector column 'text_embedding'"
|
||||
):
|
||||
await update({source_target: "updated text", "vector": [2.0, 3.0]})
|
||||
|
||||
if async_api:
|
||||
assert (await table.to_arrow()).equals(before)
|
||||
assert await table.version() == version
|
||||
else:
|
||||
assert table.to_arrow().equals(before)
|
||||
assert table.version == version
|
||||
|
||||
result = await update(
|
||||
{
|
||||
source_target: "updated text",
|
||||
"vector": [2.0, 3.0],
|
||||
"text_embedding": [4.0, 5.0],
|
||||
}
|
||||
)
|
||||
assert result.rows_updated == 1
|
||||
assert (await update({"vector": [6.0, 7.0]})).rows_updated == 1
|
||||
assert (await update({"id": 99})).rows_updated == 1
|
||||
|
||||
actual = await table.to_arrow() if async_api else table.to_arrow()
|
||||
rows = {row["id"]: row for row in actual.to_pylist()}
|
||||
assert rows[99]["text"] == "updated text"
|
||||
assert np.allclose(rows[99]["vector"], [6.0, 7.0])
|
||||
assert np.allclose(rows[99]["text_embedding"], [4.0, 5.0])
|
||||
assert rows[2]["text"] == "goodbye world"
|
||||
|
||||
|
||||
def test_update_expr_filter_literals(mem_db: DBConnection):
|
||||
values = ["5", "4.66e-84", "it's"]
|
||||
table = mem_db.create_table(
|
||||
@@ -3260,6 +3587,41 @@ async def test_merge_insert_source_collect_threshold_connection_option_async(
|
||||
assert res.num_inserted_rows == 2
|
||||
|
||||
|
||||
def test_merge_insert_with_schema_metadata(mem_db: DBConnection):
|
||||
schema = pa.schema(
|
||||
[pa.field("id", pa.int64()), pa.field("value", pa.string())],
|
||||
metadata={b"schema_key": b"schema_value"},
|
||||
)
|
||||
table = mem_db.create_table("my_table", schema=schema)
|
||||
new_data = pa.table({"id": [1, 2], "value": ["one", "two"]})
|
||||
assert new_data.schema.metadata is None
|
||||
|
||||
async def do_merge_insert():
|
||||
return await table._inner.execute_merge_insert(
|
||||
to_scannable(new_data.to_reader()),
|
||||
{
|
||||
"on": ["id"],
|
||||
"when_matched_update_all": True,
|
||||
"when_matched_update_all_condition": None,
|
||||
"when_not_matched_insert_all": True,
|
||||
"when_not_matched_by_source_delete": False,
|
||||
"when_not_matched_by_source_condition": None,
|
||||
"when_not_matched_by_source_condition_expr": None,
|
||||
"timeout": None,
|
||||
"use_index": True,
|
||||
"use_rte": None,
|
||||
"validate_single_shard": None,
|
||||
"source_collect_threshold_bytes": None,
|
||||
},
|
||||
)
|
||||
|
||||
result = table_module.LOOP.run(do_merge_insert())
|
||||
|
||||
assert result.num_inserted_rows == 2
|
||||
assert table.to_arrow() == new_data
|
||||
assert table.schema.metadata == schema.metadata
|
||||
|
||||
|
||||
def test_merge_insert_composite_key(mem_db: DBConnection):
|
||||
table = mem_db.create_table(
|
||||
"my_table",
|
||||
@@ -4741,6 +5103,69 @@ def test_restore_consistency(tmp_path):
|
||||
|
||||
|
||||
# Schema evolution
|
||||
@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType])
|
||||
def test_add_columns_sql_mapping(mem_db, mapping_type):
|
||||
table = mem_db.create_table("mapping_columns", pa.table({"id": [0, 1]}))
|
||||
result = table.add_columns(mapping_type({"score": "id + 10"}))
|
||||
assert result.version == 2
|
||||
assert table.to_arrow().to_pydict() == {"id": [0, 1], "score": [10, 11]}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType])
|
||||
async def test_add_columns_sql_mapping_async(mem_db_async, mapping_type):
|
||||
table = await mem_db_async.create_table("mapping_columns", pa.table({"id": [0, 1]}))
|
||||
result = await table.add_columns(mapping_type({"score": "id + 10"}))
|
||||
assert result.version == 2
|
||||
assert (await table.to_arrow()).to_pydict() == {"id": [0, 1], "score": [10, 11]}
|
||||
|
||||
|
||||
def test_add_columns_tuple_batches(mem_db):
|
||||
table = mem_db.create_table("tuple_columns", pa.table({"id": [0, 1]}))
|
||||
result = table.add_columns(
|
||||
(pa.record_batch({"score": [10]}), pa.record_batch({"score": [20]}))
|
||||
)
|
||||
assert result.version == 2
|
||||
assert table.to_arrow().to_pydict() == {"id": [0, 1], "score": [10, 20]}
|
||||
|
||||
|
||||
def _add_columns_input(kind):
|
||||
values = pa.table({"score": [10, None, 30]})
|
||||
if kind == "pandas":
|
||||
pd = pytest.importorskip("pandas")
|
||||
return pd.DataFrame(
|
||||
{"score": pd.array([10, None, 30], dtype="Int64")},
|
||||
index=pd.Index([9, 7, 5], name="source_index"),
|
||||
)
|
||||
if kind == "polars":
|
||||
return pl.from_arrow(values)
|
||||
if kind == "batch":
|
||||
return values.to_batches()[0]
|
||||
if kind == "reader":
|
||||
return values.to_reader(max_chunksize=1)
|
||||
return values
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["pandas", "polars", "table", "batch", "reader"])
|
||||
def test_add_columns_data(mem_db, kind):
|
||||
table = mem_db.create_table("columns_data", pa.table({"id": [2, 0, 1]}))
|
||||
result = table.add_columns(_add_columns_input(kind))
|
||||
assert result.version == 2
|
||||
assert table.to_arrow().to_pydict() == {"id": [2, 0, 1], "score": [10, None, 30]}
|
||||
assert table.schema.field("score").type == pa.int64()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("kind", ["pandas", "polars", "table", "batch", "reader"])
|
||||
async def test_add_columns_data_async(mem_db_async, kind):
|
||||
table = await mem_db_async.create_table("columns_data", pa.table({"id": [2, 0, 1]}))
|
||||
result = await table.add_columns(_add_columns_input(kind))
|
||||
assert result.version == 2
|
||||
data = await table.to_arrow()
|
||||
assert data.to_pydict() == {"id": [2, 0, 1], "score": [10, None, 30]}
|
||||
assert data.schema.field("score").type == pa.int64()
|
||||
|
||||
|
||||
def test_add_columns(mem_db: DBConnection):
|
||||
data = pa.table({"id": [0, 1]})
|
||||
table = LanceTable.create(mem_db, "my_table", data=data)
|
||||
@@ -5558,14 +5983,15 @@ async def test_async_search_runs_embedding_on_dedicated_executor(
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
def test_computed_column_declare_and_refresh(tmp_path):
|
||||
@pytest.mark.parametrize("batch_size", [None, 8])
|
||||
def test_computed_column_declare_and_refresh(tmp_path, batch_size):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("computed", [{"x": 1}, {"x": 2}])
|
||||
|
||||
table.add_columns(computed={"doubled": "x * 2"})
|
||||
assert table.to_arrow()["doubled"].to_pylist() == [None, None]
|
||||
|
||||
result = table.refresh_column("doubled")
|
||||
result = table.refresh_column("doubled", batch_size=batch_size)
|
||||
assert result.rows_filled == 2
|
||||
assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4]
|
||||
|
||||
@@ -5607,32 +6033,80 @@ def test_computed_column_blob_projection_inherits_semantics(tmp_path):
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
async def test_computed_column_async(tmp_path):
|
||||
@pytest.mark.parametrize("batch_size", [None, 8])
|
||||
async def test_computed_column_async(tmp_path, batch_size):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("computed_async", [{"x": 3}])
|
||||
|
||||
await table.add_columns(computed={"tripled": "x * 3"})
|
||||
await table.refresh_column("tripled")
|
||||
await table.refresh_column("tripled", batch_size=batch_size)
|
||||
|
||||
assert (await table.to_arrow())["tripled"].to_pylist() == [9]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["refresh_column", "refresh_column_async"])
|
||||
@pytest.mark.parametrize("batch_size", [0, -1])
|
||||
def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("invalid_refresh_batch", [{"x": 1}])
|
||||
with pytest.raises(ValueError, match="batch_size must be greater than zero"):
|
||||
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"),
|
||||
({"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])
|
||||
async def test_async_refresh_column_rejects_invalid_batch_size(
|
||||
tmp_path, method, batch_size
|
||||
):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("invalid_refresh_batch", [{"x": 1}])
|
||||
with pytest.raises(ValueError, match="batch_size must be greater than zero"):
|
||||
await getattr(table, method)("x", batch_size=batch_size)
|
||||
|
||||
|
||||
def test_function_errors_are_remote_only(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", [{"x": 1}])
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="recorded only in LanceDB Distributed"
|
||||
NotImplementedError, match="recorded only in LanceDB Enterprise"
|
||||
):
|
||||
table.function_errors()
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
def test_refresh_column_async_returns_job(tmp_path):
|
||||
@pytest.mark.parametrize("batch_size", [None, 8])
|
||||
def test_refresh_column_async_returns_job(tmp_path, batch_size):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("computed_job", [{"x": 1}, {"x": 2}])
|
||||
table.add_columns(computed={"doubled": "x * 2"})
|
||||
|
||||
job = table.refresh_column_async("doubled")
|
||||
job = table.refresh_column_async("doubled", batch_size=batch_size)
|
||||
assert job.id is None # in-process jobs have no server id
|
||||
result = job.wait()
|
||||
assert isinstance(result, lancedb.RefreshColumnResult)
|
||||
@@ -5657,12 +6131,13 @@ def test_refresh_column_async_returns_job(tmp_path):
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_column_async_job_async_table(tmp_path):
|
||||
@pytest.mark.parametrize("batch_size", [None, 8])
|
||||
async def test_refresh_column_async_job_async_table(tmp_path, batch_size):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("computed_job_async", [{"x": 3}])
|
||||
await table.add_columns(computed={"tripled": "x * 3"})
|
||||
|
||||
job = await table.refresh_column_async("tripled")
|
||||
job = await table.refresh_column_async("tripled", batch_size=batch_size)
|
||||
result = await job.wait()
|
||||
assert isinstance(result, lancedb.RefreshColumnResult)
|
||||
assert result.rows_assigned == 1
|
||||
@@ -5672,6 +6147,139 @@ async def test_refresh_column_async_job_async_table(tmp_path):
|
||||
assert (await table.to_arrow())["tripled"].to_pylist() == [9]
|
||||
|
||||
|
||||
def test_add_columns_reader_deleted_rows_and_fragments(mem_db):
|
||||
table = mem_db.create_table("column_fragments", pa.table({"id": [9, 3]}))
|
||||
table.add(pa.table({"id": [7, 1, 5]}))
|
||||
table.delete("id = 3")
|
||||
before = table.to_arrow()
|
||||
values = pa.table({"score": [90, 70, 10, 50]})
|
||||
reader = values.to_reader(max_chunksize=3)
|
||||
version = table.version
|
||||
result = table.add_columns(reader)
|
||||
assert result.version == version + 1
|
||||
assert table.to_arrow().to_pydict() == {
|
||||
"id": before["id"].to_pylist(),
|
||||
"score": [90, 70, 10, 50],
|
||||
}
|
||||
assert before["id"].to_pylist() == [9, 7, 1, 5]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("count", [0, 1, 3])
|
||||
def test_add_columns_reader_wrong_count_is_atomic(mem_db, count):
|
||||
table = mem_db.create_table("column_counts", pa.table({"id": [0, 1]}))
|
||||
before, version = table.to_arrow(), table.version
|
||||
reader = pa.table({"score": pa.array(range(count), type=pa.int64())}).to_reader()
|
||||
with pytest.raises(ValueError, match="Stream"):
|
||||
table.add_columns(reader)
|
||||
assert table.version == version
|
||||
assert table.to_arrow().equals(before)
|
||||
|
||||
|
||||
def test_add_columns_reader_empty_table(mem_db):
|
||||
table = mem_db.create_table("empty_columns", schema=pa.schema([("id", pa.int64())]))
|
||||
schema = pa.schema([("score", pa.float32())])
|
||||
result = table.add_columns(pa.RecordBatchReader.from_batches(schema, []))
|
||||
assert result.version == 2
|
||||
assert table.schema.names == ["id", "score"]
|
||||
assert table.schema.field("score").type == pa.float32()
|
||||
assert table.count_rows() == 0
|
||||
|
||||
|
||||
def test_add_columns_reader_error_is_atomic(mem_db):
|
||||
table = mem_db.create_table("column_error", pa.table({"id": [0, 1]}))
|
||||
before, version = table.to_arrow(), table.version
|
||||
|
||||
def batches():
|
||||
yield pa.record_batch({"score": [10]})
|
||||
raise RuntimeError("reader failed deliberately")
|
||||
|
||||
reader = pa.RecordBatchReader.from_batches(
|
||||
pa.schema([("score", pa.int64())]), batches()
|
||||
)
|
||||
with pytest.raises((RuntimeError, OSError), match="reader failed deliberately"):
|
||||
table.add_columns(reader)
|
||||
assert table.version == version
|
||||
assert table.to_arrow().equals(before)
|
||||
|
||||
|
||||
def test_add_columns_reader_collision_is_atomic(mem_db):
|
||||
table = mem_db.create_table("column_collision", pa.table({"id": [0, 1]}))
|
||||
before, version = table.to_arrow(), table.version
|
||||
with pytest.raises(ValueError, match="id"):
|
||||
table.add_columns(pa.table({"id": [4, 5]}).to_reader())
|
||||
assert table.version == version
|
||||
assert table.to_arrow().equals(before)
|
||||
|
||||
|
||||
def test_add_columns_preserves_arrow_types(mem_db):
|
||||
table = mem_db.create_table("column_types", pa.table({"id": [0, 1]}))
|
||||
vectors = pa.array([[1.0, 2.0], [3.0, 4.0]], type=pa.list_(pa.float64(), 2))
|
||||
values = pa.table({"vector": vectors, "score": pa.array([None, 2.5], pa.float32())})
|
||||
table.add_columns(values)
|
||||
assert table.schema.field("vector").type == pa.list_(pa.float64(), 2)
|
||||
assert table.schema.field("score").type == pa.float32()
|
||||
assert table.to_arrow().select(values.column_names).equals(values)
|
||||
|
||||
|
||||
def test_add_columns_dataframe_computed_conflict(mem_db):
|
||||
table = mem_db.create_table("column_conflict", pa.table({"id": [0, 1, 2]}))
|
||||
before, version = table.to_arrow(), table.version
|
||||
with pytest.raises(ValueError, match="cannot take both transforms and computed"):
|
||||
table.add_columns(_add_columns_input("pandas"), computed={"x": "id + 1"})
|
||||
assert table.version == version
|
||||
assert table.to_arrow().equals(before)
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.parametrize(
|
||||
"transforms", [{}, pa.schema([]), UserDict(), MappingProxyType({})]
|
||||
)
|
||||
def test_add_columns_computed_with_empty_transforms(mem_db, transforms):
|
||||
table = mem_db.create_table("empty_transforms", pa.table({"id": [0, 1]}))
|
||||
result = table.add_columns(transforms, computed={"x": "id + 1"})
|
||||
assert result.version == 2
|
||||
table.refresh_column("x")
|
||||
assert table.to_arrow()["x"].to_pylist() == [1, 2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["batch", "reader", "leading_and_trailing"])
|
||||
def test_add_columns_empty_batches(mem_db, kind):
|
||||
ids = [0] if kind == "leading_and_trailing" else []
|
||||
table = mem_db.create_table(
|
||||
"empty_batches", pa.table({"id": pa.array(ids, pa.int64())})
|
||||
)
|
||||
schema = pa.schema([("score", pa.int64())])
|
||||
empty = pa.RecordBatch.from_arrays([pa.array([], pa.int64())], schema=schema)
|
||||
if kind == "batch":
|
||||
data = empty
|
||||
elif kind == "reader":
|
||||
data = pa.RecordBatchReader.from_batches(schema, [empty])
|
||||
else:
|
||||
values = pa.RecordBatch.from_arrays([pa.array([10])], schema=schema)
|
||||
data = pa.RecordBatchReader.from_batches(schema, [empty, values, empty])
|
||||
result = table.add_columns(data)
|
||||
assert result.version == 2
|
||||
assert table.to_arrow().to_pydict() == {"id": ids, "score": [10] if ids else []}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["table", "reader"])
|
||||
def test_add_columns_data_rejects_computed_metadata(mem_db, kind):
|
||||
table = mem_db.create_table("foreign_metadata", pa.table({"id": [0]}))
|
||||
before, version = table.to_arrow(), table.version
|
||||
schema = pa.schema(
|
||||
[pa.field("score", pa.int64(), metadata={b"computed_column": b"true"})]
|
||||
)
|
||||
data = pa.Table.from_arrays([pa.array([10])], schema=schema)
|
||||
if kind == "reader":
|
||||
data = data.to_reader()
|
||||
with pytest.raises(ValueError, match="computed"):
|
||||
table.add_columns(data)
|
||||
assert table.version == version
|
||||
assert table.to_arrow().equals(before)
|
||||
table.add(pa.table({"id": [1]}))
|
||||
assert table.count_rows() == 2
|
||||
|
||||
|
||||
@pytest.mark.experimental_functions
|
||||
@pytest.mark.parametrize("interval", [None, 300])
|
||||
def test_computed_auto_refresh_options(tmp_path, interval):
|
||||
|
||||
@@ -192,7 +192,10 @@ def test_remote_optimize_options():
|
||||
with pytest.raises(NotImplementedError, match="remote optimize"):
|
||||
table.optimize(cleanup_older_than=age, delete_unverified=True, retrain=True)
|
||||
handle.optimize.assert_awaited_once_with(
|
||||
cleanup_older_than=age, delete_unverified=True, retrain=True
|
||||
cleanup_older_than=age,
|
||||
delete_unverified=True,
|
||||
retrain=True,
|
||||
compaction_options=None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,12 +4,11 @@
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
from datetime import time, timedelta, timezone
|
||||
from decimal import Decimal, localcontext
|
||||
from typing import Optional
|
||||
|
||||
import lance
|
||||
from lance.blob import BlobType as LanceBlobType
|
||||
from lancedb.conftest import MockTextEmbeddingFunction
|
||||
from lancedb.embeddings.base import EmbeddingFunctionConfig
|
||||
from lancedb.embeddings.registry import EmbeddingFunctionRegistry
|
||||
@@ -26,7 +25,6 @@ from lancedb.table import (
|
||||
sanitize_create_table,
|
||||
)
|
||||
import pyarrow as pa
|
||||
import pandas as pd
|
||||
import polars as pl
|
||||
import pytest
|
||||
import lancedb
|
||||
@@ -180,7 +178,8 @@ def test_value_to_sql_string(tmp_path):
|
||||
)
|
||||
for value in values:
|
||||
table.update(where=f"search = {value_to_sql(value)}", values={"replace": value})
|
||||
assert table.to_pandas().query("search == @value")["replace"].item() == value
|
||||
rows = table.to_arrow().to_pylist()
|
||||
assert next(row["replace"] for row in rows if row["search"] == value) == value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -275,10 +274,15 @@ def test_value_to_sql_time_and_timedelta(tmp_path):
|
||||
def test_value_to_sql_keeps_nanoseconds(tmp_path):
|
||||
# Arrow scalars and pandas.Timedelta values can hold nanoseconds, which a
|
||||
# Python timedelta or time would round to microseconds.
|
||||
assert (
|
||||
value_to_sql(pd.Timedelta(1001, "ns"))
|
||||
== "arrow_cast(1001, 'Duration(Nanosecond)')"
|
||||
)
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
if pd is not None:
|
||||
assert (
|
||||
value_to_sql(pd.Timedelta(1001, "ns"))
|
||||
== "arrow_cast(1001, 'Duration(Nanosecond)')"
|
||||
)
|
||||
assert value_to_sql(pa.scalar(None, pa.duration("ns"))) == "NULL"
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
@@ -780,15 +784,20 @@ class TestModel(lancedb.pydantic.LanceModel):
|
||||
lambda: pa.table({"a": [1], "b": [2]}),
|
||||
lambda: pa.table({"a": [1], "b": [2]}).to_reader(),
|
||||
lambda: iter(pa.table({"a": [1], "b": [2]}).to_batches()),
|
||||
lambda: lance.write_dataset(
|
||||
lambda: tuple(pa.table({"a": [1], "b": [2]}).to_batches()),
|
||||
lambda: pytest.importorskip("lance").write_dataset(
|
||||
pa.table({"a": [1], "b": [2]}),
|
||||
"memory://test",
|
||||
),
|
||||
lambda: lance.write_dataset(
|
||||
pa.table({"a": [1], "b": [2]}),
|
||||
"memory://test",
|
||||
).scanner(),
|
||||
lambda: pd.DataFrame({"a": [1], "b": [2]}),
|
||||
lambda: (
|
||||
pytest.importorskip("lance")
|
||||
.write_dataset(
|
||||
pa.table({"a": [1], "b": [2]}),
|
||||
"memory://test",
|
||||
)
|
||||
.scanner()
|
||||
),
|
||||
lambda: pytest.importorskip("pandas").DataFrame({"a": [1], "b": [2]}),
|
||||
lambda: pl.DataFrame({"a": [1], "b": [2]}),
|
||||
lambda: pl.LazyFrame({"a": [1], "b": [2]}),
|
||||
lambda: [TestModel(a=1, b=2)],
|
||||
@@ -799,6 +808,7 @@ class TestModel(lancedb.pydantic.LanceModel):
|
||||
"pa.Table",
|
||||
"pa.RecordBatchReader",
|
||||
"batch_iter",
|
||||
"batch_tuple",
|
||||
"lance.LanceDataset",
|
||||
"lance.LanceScanner",
|
||||
"pd.DataFrame",
|
||||
@@ -813,6 +823,12 @@ def test_into_pyarrow_table(data):
|
||||
assert output == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", ["score", ""])
|
||||
def test_into_pyarrow_reader_rejects_text(data):
|
||||
with pytest.raises(TypeError, match="Unknown data type"):
|
||||
_into_pyarrow_reader(data)
|
||||
|
||||
|
||||
def test_infer_target_schema():
|
||||
example = pa.schema(
|
||||
{
|
||||
@@ -958,10 +974,10 @@ def test_infer_target_schema_with_vector_embedding_names():
|
||||
@pytest.mark.parametrize(
|
||||
"data",
|
||||
[
|
||||
[{"id": 1, "text": "hello"}],
|
||||
pa.RecordBatch.from_pylist([{"id": 1, "text": "hello"}]),
|
||||
pd.DataFrame({"id": [1], "text": ["hello"]}),
|
||||
pl.DataFrame({"id": [1], "text": ["hello"]}),
|
||||
lambda: [{"id": 1, "text": "hello"}],
|
||||
lambda: pa.RecordBatch.from_pylist([{"id": 1, "text": "hello"}]),
|
||||
lambda: pytest.importorskip("pandas").DataFrame({"id": [1], "text": ["hello"]}),
|
||||
lambda: pl.DataFrame({"id": [1], "text": ["hello"]}),
|
||||
],
|
||||
ids=["rows", "pa.RecordBatch", "pd.DataFrame", "pl.DataFrame"],
|
||||
)
|
||||
@@ -993,6 +1009,7 @@ def test_sanitize_data(
|
||||
schema: Optional[pa.Schema],
|
||||
with_embedding: bool,
|
||||
):
|
||||
data = data()
|
||||
if with_embedding:
|
||||
registry = EmbeddingFunctionRegistry.get_instance()
|
||||
registry.register("test")(MockTextEmbeddingFunction)
|
||||
@@ -1017,7 +1034,9 @@ def test_sanitize_data(
|
||||
# polars uses large_string, pandas 3.0+ uses large_string, others use string
|
||||
if isinstance(data, pl.DataFrame):
|
||||
text_type = pa.large_utf8()
|
||||
elif isinstance(data, pd.DataFrame):
|
||||
elif (pd := sys.modules.get("pandas")) is not None and isinstance(
|
||||
data, pd.DataFrame
|
||||
):
|
||||
text_type = pandas_string_type()
|
||||
else:
|
||||
text_type = pa.string()
|
||||
@@ -1352,6 +1371,8 @@ def test_fixed_size_list_blob_coercion_keeps_null_rows():
|
||||
|
||||
|
||||
def test_cast_to_target_schema_accepts_pylance_blob_v2():
|
||||
lance = pytest.importorskip("lance")
|
||||
LanceBlobType = pytest.importorskip("lance.blob").BlobType
|
||||
target_type = lancedb.BlobType()
|
||||
source = lance.blob_array([b"hello", None])
|
||||
assert type(source.type) is LanceBlobType
|
||||
@@ -1371,6 +1392,8 @@ def test_cast_to_target_schema_accepts_pylance_blob_v2():
|
||||
|
||||
|
||||
def test_cast_to_target_schema_rejects_different_blob_v2_class():
|
||||
lance = pytest.importorskip("lance")
|
||||
|
||||
class OtherBlobType(pa.ExtensionType):
|
||||
def __init__(self):
|
||||
super().__init__(lancedb.BlobType().storage_type, "lance.blob.v2")
|
||||
|
||||
@@ -262,6 +262,19 @@ impl AuthzObject {
|
||||
}))
|
||||
}
|
||||
|
||||
#[staticmethod]
|
||||
fn storage_integration(
|
||||
database: &str,
|
||||
namespace: &Bound<'_, PyAny>,
|
||||
name: &str,
|
||||
) -> PyResult<Self> {
|
||||
Self::validated(Object::StorageIntegration(StorageIntegrationObject {
|
||||
database: database.into(),
|
||||
namespace: namespace_path(namespace)?,
|
||||
storage_integration: name.into(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[staticmethod]
|
||||
fn function(database: &str, namespace: &Bound<'_, PyAny>, name: &str) -> PyResult<Self> {
|
||||
Self::validated(Object::Function(FunctionObject {
|
||||
|
||||
@@ -24,6 +24,8 @@ use lancedb::{
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
database::{CreateTableMode, Database, ReadConsistency},
|
||||
function::GpuClass as LanceGpuClass,
|
||||
graph::PropertyGraphDefinition,
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
|
||||
@@ -37,6 +39,62 @@ pub struct Connection {
|
||||
inner: Option<LanceConnection>,
|
||||
}
|
||||
|
||||
/// Configured hardware and worker limits of a Function GPU class.
|
||||
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GpuClass {
|
||||
pub name: String,
|
||||
pub resource_name: String,
|
||||
pub gpu_model: Option<String>,
|
||||
pub gpu_memory_bytes: Option<u64>,
|
||||
pub max_gpu_count_per_worker: Option<u32>,
|
||||
pub cpu_millis: Option<u64>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub ephemeral_storage_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
impl From<LanceGpuClass> for GpuClass {
|
||||
fn from(class: LanceGpuClass) -> Self {
|
||||
Self {
|
||||
name: class.name,
|
||||
resource_name: class.resource_name,
|
||||
gpu_model: class.gpu_model,
|
||||
gpu_memory_bytes: class.gpu_memory_bytes,
|
||||
max_gpu_count_per_worker: class.max_gpu_count_per_worker,
|
||||
cpu_millis: class.cpu_millis,
|
||||
memory_bytes: class.memory_bytes,
|
||||
ephemeral_storage_bytes: class.ephemeral_storage_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl GpuClass {
|
||||
fn __repr__(&self) -> String {
|
||||
let gpu_model = self
|
||||
.gpu_model
|
||||
.as_ref()
|
||||
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
|
||||
let optional = |value: Option<u64>| {
|
||||
value.map_or_else(|| "None".to_string(), |value| value.to_string())
|
||||
};
|
||||
let max_gpu_count = self
|
||||
.max_gpu_count_per_worker
|
||||
.map_or_else(|| "None".to_string(), |value| value.to_string());
|
||||
format!(
|
||||
"GpuClass(name={:?}, resource_name={:?}, gpu_model={gpu_model}, \
|
||||
gpu_memory_bytes={}, max_gpu_count_per_worker={max_gpu_count}, \
|
||||
cpu_millis={}, memory_bytes={}, ephemeral_storage_bytes={})",
|
||||
self.name,
|
||||
self.resource_name,
|
||||
optional(self.gpu_memory_bytes),
|
||||
optional(self.cpu_millis),
|
||||
optional(self.memory_bytes),
|
||||
optional(self.ephemeral_storage_bytes),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
pub(crate) fn new(inner: LanceConnection) -> Self {
|
||||
Self { inner: Some(inner) }
|
||||
@@ -870,6 +928,23 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, version, namespace_path=None))]
|
||||
pub fn _drop_function_with_warnings(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
version: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.drop_function_with_warnings(name, version, &namespace_path)
|
||||
.await
|
||||
.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, version, namespace_path=None))]
|
||||
pub fn drop_function_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
@@ -888,6 +963,72 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, request, namespace_path=None))]
|
||||
pub fn create_storage_integration<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
name: String,
|
||||
request: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self.get_inner()?.clone();
|
||||
let request: lancedb::storage_integration::CreateStorageIntegrationRequest =
|
||||
serde_json::from_str(&request)
|
||||
.map_err(|error| PyValueError::new_err(error.to_string()))?;
|
||||
future_into_py(py, async move {
|
||||
let info = inner
|
||||
.create_storage_integration(name, request, &namespace_path.unwrap_or_default())
|
||||
.await
|
||||
.infer_error()?;
|
||||
serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string()))
|
||||
})
|
||||
}
|
||||
#[pyo3(signature = (name, namespace_path=None))]
|
||||
pub fn describe_storage_integration<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
name: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self.get_inner()?.clone();
|
||||
future_into_py(py, async move {
|
||||
let info = inner
|
||||
.describe_storage_integration(name, &namespace_path.unwrap_or_default())
|
||||
.await
|
||||
.infer_error()?;
|
||||
serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string()))
|
||||
})
|
||||
}
|
||||
#[pyo3(signature = (*, namespace_path=None, page_token=None, page_limit=None))]
|
||||
pub fn list_storage_integrations(
|
||||
&self,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
page_token: Option<String>,
|
||||
page_limit: Option<u32>,
|
||||
) -> PyResult<crate::listing::NameListing> {
|
||||
Ok(crate::listing::NameListing::new(
|
||||
self.get_inner()?.list_storage_integrations(
|
||||
&namespace_path.unwrap_or_default(),
|
||||
crate::listing::options(page_token, page_limit),
|
||||
),
|
||||
))
|
||||
}
|
||||
#[pyo3(signature = (name, namespace_path=None))]
|
||||
pub fn drop_storage_integration<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
name: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self.get_inner()?.clone();
|
||||
future_into_py(py, async move {
|
||||
inner
|
||||
.drop_storage_integration(name, &namespace_path.unwrap_or_default())
|
||||
.await
|
||||
.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, value, namespace_path=None))]
|
||||
pub fn create_secret(
|
||||
self_: PyRef<'_, Self>,
|
||||
@@ -1050,6 +1191,79 @@ impl Connection {
|
||||
))
|
||||
}
|
||||
|
||||
/// Create a property graph from its definition's JSON, and return its
|
||||
/// description's JSON. The Python layer names the fields; the JSON keeps
|
||||
/// the binding free of classes kept in step with the Rust structs.
|
||||
#[pyo3(signature = (name, definition_json, namespace_path=None))]
|
||||
pub fn create_property_graph(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
definition_json: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
let definition = PropertyGraphDefinition::from_json(&definition_json).infer_error()?;
|
||||
inner
|
||||
.create_property_graph(name, &definition, &namespace_path)
|
||||
.await
|
||||
.infer_error()?
|
||||
.to_json()
|
||||
.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON description of the property graph named `name`.
|
||||
#[pyo3(signature = (name, namespace_path=None))]
|
||||
pub fn describe_property_graph(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.describe_property_graph(name, &namespace_path)
|
||||
.await
|
||||
.infer_error()?
|
||||
.to_json()
|
||||
.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (name, namespace_path=None))]
|
||||
pub fn drop_property_graph(
|
||||
self_: PyRef<'_, Self>,
|
||||
name: String,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let namespace_path = namespace_path.unwrap_or_default();
|
||||
future_into_py(self_.py(), async move {
|
||||
inner
|
||||
.drop_property_graph(name, &namespace_path)
|
||||
.await
|
||||
.infer_error()
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (namespace_path=None, *, page_token=None, page_limit=None))]
|
||||
pub fn list_property_graphs(
|
||||
&self,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
page_token: Option<String>,
|
||||
page_limit: Option<u32>,
|
||||
) -> PyResult<crate::listing::NameListing> {
|
||||
Ok(crate::listing::NameListing::new(
|
||||
self.get_inner()?.list_property_graphs(
|
||||
&namespace_path.unwrap_or_default(),
|
||||
crate::listing::options(page_token, page_limit),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
#[pyo3(signature = (*, page_token=None, page_limit=None))]
|
||||
pub fn list_jobs(
|
||||
&self,
|
||||
@@ -1062,6 +1276,14 @@ impl Connection {
|
||||
))
|
||||
}
|
||||
|
||||
pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let classes = inner.list_gpu_classes().await.infer_error()?;
|
||||
Ok(classes.into_iter().map(GpuClass::from).collect::<Vec<_>>())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cancel_job(self_: PyRef<'_, Self>, job_id: String) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
+498
-14
@@ -2,13 +2,13 @@
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use pyo3::{
|
||||
PyErr, PyResult, Python,
|
||||
Bound, PyAny, PyErr, PyResult, Python,
|
||||
exceptions::{PyIOError, PyNotImplementedError, PyOSError, PyRuntimeError, PyValueError},
|
||||
intern,
|
||||
types::{PyAnyMethods, PyNone},
|
||||
};
|
||||
|
||||
use lancedb::error::Error as LanceError;
|
||||
use lancedb::error::{Error as LanceError, HttpErrorDetails, RemoteErrorMetadata};
|
||||
|
||||
pub trait PythonErrorExt<T> {
|
||||
/// Convert to a python error based on the Lance error type
|
||||
@@ -28,12 +28,67 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
|
||||
Err(err) => match err {
|
||||
LanceError::InvalidInput { .. }
|
||||
| LanceError::InvalidTableName { .. }
|
||||
| LanceError::TableNotFound { .. }
|
||||
| LanceError::NotAMaterializedView { .. }
|
||||
| LanceError::Schema { .. }
|
||||
| LanceError::DatabaseNotFound { .. }
|
||||
| LanceError::DatabaseAlreadyExists { .. }
|
||||
| LanceError::TableAlreadyExists { .. } => self.value_error(),
|
||||
LanceError::TableNotFound { source, .. } => {
|
||||
let Some(
|
||||
request_error @ LanceError::Http {
|
||||
request_id,
|
||||
status_code,
|
||||
source: http_source,
|
||||
},
|
||||
) = source.downcast_ref::<LanceError>()
|
||||
else {
|
||||
return self.value_error();
|
||||
};
|
||||
Python::attach(|py| {
|
||||
let status_code = status_code.map(|s| s.as_u16());
|
||||
let metadata = request_error.remote_error_metadata();
|
||||
let details = request_error.http_error_details();
|
||||
let py_err = if details.is_some()
|
||||
|| metadata.is_some_and(|metadata| metadata.error_code.is_some())
|
||||
{
|
||||
new_py_http_error(
|
||||
py,
|
||||
http_source.to_string(),
|
||||
request_id,
|
||||
status_code,
|
||||
details,
|
||||
metadata,
|
||||
false,
|
||||
)?
|
||||
} else {
|
||||
let cls = py
|
||||
.import(intern!(py, "lancedb.remote.errors"))?
|
||||
.getattr(intern!(py, "TableNotFoundError"))?;
|
||||
let error = cls.call1((err.to_string(), request_id, status_code))?;
|
||||
error.setattr(
|
||||
"job_id",
|
||||
metadata.and_then(|value| value.job_id.as_deref()),
|
||||
)?;
|
||||
error.setattr(
|
||||
"job_request_id",
|
||||
metadata.and_then(|value| value.job_request_id.as_deref()),
|
||||
)?;
|
||||
error
|
||||
};
|
||||
let cause =
|
||||
http_from_rust_error(py, source.as_ref(), request_id, status_code)?;
|
||||
py_err.setattr(intern!(py, "__cause__"), cause)?;
|
||||
Err(PyErr::from_value(py_err))
|
||||
})
|
||||
}
|
||||
LanceError::ColumnNotFound { .. } | LanceError::FieldNotFound { .. } => {
|
||||
Python::attach(|py| {
|
||||
let cls = py
|
||||
.import(intern!(py, "lancedb.exceptions"))?
|
||||
.getattr(intern!(py, "ColumnNotFoundError"))?;
|
||||
Err(PyErr::from_value(cls.call1((err.to_string(),))?))
|
||||
})
|
||||
}
|
||||
LanceError::CreateDir { .. } => self.os_error(),
|
||||
LanceError::ObjectStore { .. } => Err(PyIOError::new_err(err.to_string())),
|
||||
LanceError::NotSupported { .. } => {
|
||||
@@ -44,15 +99,23 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
|
||||
source,
|
||||
status_code,
|
||||
} => Python::attach(|py| {
|
||||
let message = err.to_string();
|
||||
let http_err_cls = py
|
||||
.import(intern!(py, "lancedb.remote.errors"))?
|
||||
.getattr(intern!(py, "HttpError"))?;
|
||||
let err = http_err_cls.call1((
|
||||
let message = if err
|
||||
.remote_error_metadata()
|
||||
.is_some_and(|metadata| metadata.error_code.is_some())
|
||||
{
|
||||
source.to_string()
|
||||
} else {
|
||||
err.to_string()
|
||||
};
|
||||
let err = new_py_http_error(
|
||||
py,
|
||||
message,
|
||||
request_id,
|
||||
status_code.map(|s| s.as_u16()),
|
||||
))?;
|
||||
err.http_error_details(),
|
||||
err.remote_error_metadata(),
|
||||
is_transport_error(source.as_ref()),
|
||||
)?;
|
||||
|
||||
if let Some(cause) = source.source() {
|
||||
// The HTTP error already includes the first cause. But
|
||||
@@ -105,11 +168,68 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
|
||||
err.setattr(intern!(py, "__cause__"), cause_err)?;
|
||||
Err(PyErr::from_value(err))
|
||||
}),
|
||||
LanceError::JobFailed { .. } => Python::attach(|py| {
|
||||
LanceError::ResponseInterrupted {
|
||||
request_id,
|
||||
batches,
|
||||
rows,
|
||||
table_version,
|
||||
source,
|
||||
} => Python::attach(|py| {
|
||||
let error = py
|
||||
.import(intern!(py, "lancedb.remote.errors"))?
|
||||
.getattr(intern!(py, "ResponseInterruptedError"))?
|
||||
.call1((
|
||||
err.to_string(),
|
||||
request_id,
|
||||
*batches,
|
||||
*rows,
|
||||
*table_version,
|
||||
is_transport_error(&**source),
|
||||
))?;
|
||||
let cause = http_from_rust_error(py, &**source, request_id, None)?;
|
||||
error.setattr(intern!(py, "__cause__"), cause)?;
|
||||
Err(PyErr::from_value(error))
|
||||
}),
|
||||
LanceError::Sql {
|
||||
message,
|
||||
request_id,
|
||||
grpc_code,
|
||||
metadata,
|
||||
} => Python::attach(|py| {
|
||||
Err(PyErr::from_value(new_py_sql_error(
|
||||
py, message, request_id, *grpc_code, metadata,
|
||||
)?))
|
||||
}),
|
||||
LanceError::JobFailed { job_id, failure } => Python::attach(|py| {
|
||||
let cls = py
|
||||
.import(intern!(py, "lancedb.exceptions"))?
|
||||
.getattr(intern!(py, "JobFailedError"))?;
|
||||
Err(PyErr::from_value(cls.call1((err.to_string(),))?))
|
||||
let sql_source = match failure.source.as_deref() {
|
||||
Some(LanceError::Sql {
|
||||
message,
|
||||
request_id,
|
||||
grpc_code,
|
||||
metadata,
|
||||
}) => Some((
|
||||
new_py_sql_error(py, message, request_id, *grpc_code, metadata)?,
|
||||
request_id.as_str(),
|
||||
metadata.job_request_id.as_deref(),
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
let error = cls.call1((
|
||||
err.to_string(),
|
||||
job_id.clone(),
|
||||
failure.sql_job_id.clone(),
|
||||
sql_source.as_ref().map(|(_, request_id, _)| *request_id),
|
||||
sql_source
|
||||
.as_ref()
|
||||
.and_then(|(_, _, request_id)| *request_id),
|
||||
))?;
|
||||
if let Some((cause, _, _)) = sql_source {
|
||||
error.setattr(intern!(py, "__cause__"), cause)?;
|
||||
}
|
||||
Err(PyErr::from_value(error))
|
||||
}),
|
||||
LanceError::JobCancelled { .. } => Python::attach(|py| {
|
||||
let cls = py
|
||||
@@ -143,13 +263,24 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
|
||||
|
||||
fn http_from_rust_error(
|
||||
py: Python<'_>,
|
||||
err: &dyn std::error::Error,
|
||||
err: &(dyn std::error::Error + 'static),
|
||||
request_id: &str,
|
||||
status_code: Option<u16>,
|
||||
) -> PyResult<PyErr> {
|
||||
let message = err.to_string();
|
||||
let http_err_cls = py.import("lancedb.remote.errors")?.getattr("HttpError")?;
|
||||
let py_err = http_err_cls.call1((message, request_id, status_code))?;
|
||||
let details = err
|
||||
.downcast_ref::<LanceError>()
|
||||
.and_then(LanceError::http_error_details);
|
||||
let py_err = new_py_http_error(
|
||||
py,
|
||||
message,
|
||||
request_id,
|
||||
status_code,
|
||||
details,
|
||||
err.downcast_ref::<LanceError>()
|
||||
.and_then(LanceError::remote_error_metadata),
|
||||
is_transport_error(err),
|
||||
)?;
|
||||
|
||||
// Reset the traceback since it doesn't provide additional information.
|
||||
let py_err = py_err.call_method1(intern!(py, "with_traceback"), (PyNone::get(py),))?;
|
||||
@@ -161,3 +292,356 @@ fn http_from_rust_error(
|
||||
|
||||
Ok(PyErr::from_value(py_err))
|
||||
}
|
||||
|
||||
fn new_py_http_error<'py>(
|
||||
py: Python<'py>,
|
||||
message: String,
|
||||
request_id: &str,
|
||||
status_code: Option<u16>,
|
||||
details: Option<&HttpErrorDetails>,
|
||||
metadata: Option<&RemoteErrorMetadata>,
|
||||
is_transport_error: bool,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let error_code = metadata
|
||||
.and_then(|metadata| metadata.error_code.as_deref())
|
||||
.or_else(|| details.map(|details| details.error_code.as_str()));
|
||||
let resource_kind = details.map(|details| details.resource_kind.as_str());
|
||||
let resource_name = details.map(|details| details.resource_name.as_str());
|
||||
let namespace_path = details.map(|details| details.namespace_path.clone());
|
||||
|
||||
py.import("lancedb.remote.errors")?
|
||||
.getattr("HttpError")?
|
||||
.call1((
|
||||
message,
|
||||
request_id,
|
||||
status_code,
|
||||
error_code,
|
||||
resource_kind,
|
||||
resource_name,
|
||||
namespace_path,
|
||||
is_transport_error,
|
||||
metadata.and_then(|metadata| metadata.job_id.as_deref()),
|
||||
metadata.and_then(|metadata| metadata.job_request_id.as_deref()),
|
||||
))
|
||||
}
|
||||
|
||||
fn new_py_sql_error<'py>(
|
||||
py: Python<'py>,
|
||||
message: &str,
|
||||
request_id: &str,
|
||||
grpc_code: i32,
|
||||
metadata: &RemoteErrorMetadata,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
if sql_has_resource_error(metadata, grpc_code) {
|
||||
return new_py_sql_resource_error(py, message, request_id, grpc_code, metadata);
|
||||
}
|
||||
py.import("lancedb.remote.errors")?
|
||||
.getattr("SqlError")?
|
||||
.call1((
|
||||
message,
|
||||
request_id,
|
||||
grpc_code,
|
||||
metadata.error_code.as_deref(),
|
||||
metadata.job_id.as_deref(),
|
||||
metadata.job_request_id.as_deref(),
|
||||
))
|
||||
}
|
||||
|
||||
fn new_py_sql_resource_error<'py>(
|
||||
py: Python<'py>,
|
||||
message: &str,
|
||||
request_id: &str,
|
||||
grpc_code: i32,
|
||||
metadata: &RemoteErrorMetadata,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let resource = metadata.resource.as_ref().unwrap();
|
||||
py.import("lancedb.remote.errors")?
|
||||
.getattr("HttpError")?
|
||||
.call1((
|
||||
message,
|
||||
request_id,
|
||||
grpc_code_to_http_status(grpc_code),
|
||||
metadata.error_code.as_deref(),
|
||||
resource.kind.as_str(),
|
||||
resource.name.as_str(),
|
||||
resource.namespace_path.clone(),
|
||||
false,
|
||||
metadata.job_id.as_deref(),
|
||||
metadata.job_request_id.as_deref(),
|
||||
))
|
||||
}
|
||||
|
||||
fn sql_has_resource_error(metadata: &RemoteErrorMetadata, grpc_code: i32) -> bool {
|
||||
metadata.resource.is_some()
|
||||
&& matches!(
|
||||
(metadata.error_code.as_deref(), grpc_code),
|
||||
// These are gRPC status codes, not HTTP status codes.
|
||||
(Some("not_found"), 5) | (Some("already_exists"), 6)
|
||||
)
|
||||
}
|
||||
|
||||
fn grpc_code_to_http_status(grpc_code: i32) -> Option<u16> {
|
||||
match grpc_code {
|
||||
3 => Some(400),
|
||||
5 => Some(404),
|
||||
6 => Some(409),
|
||||
7 => Some(403),
|
||||
9 => Some(400),
|
||||
12 => Some(501),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve the typed transport classification across the Python boundary.
|
||||
// A missing status code alone also covers malformed job responses, which
|
||||
// waiting longer cannot repair.
|
||||
fn is_transport_error(err: &(dyn std::error::Error + 'static)) -> bool {
|
||||
if let Some(error) = err.downcast_ref::<reqwest::Error>() {
|
||||
return error.is_connect()
|
||||
|| error.is_timeout()
|
||||
|| error.is_request()
|
||||
|| error.is_body()
|
||||
|| error.is_decode();
|
||||
}
|
||||
err.source().is_some_and(is_transport_error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::ffi::CString;
|
||||
use std::sync::{Arc, Once};
|
||||
|
||||
use lancedb::error::{JobFailure, RemoteResourceIdentity};
|
||||
use pyo3::types::{PyAnyMethods, PyModule};
|
||||
|
||||
use super::*;
|
||||
|
||||
static INSTALL_PYTHON_ERROR_MODULES: Once = Once::new();
|
||||
|
||||
fn install_python_error_modules(py: Python<'_>) -> PyResult<()> {
|
||||
// Load the checked-in error classes without requiring an installed wheel.
|
||||
// The namespace exception is only a base for an unrelated remote class.
|
||||
PyModule::from_code(
|
||||
py,
|
||||
c"import sys\n\nimport types\n\n\
|
||||
lancedb = types.ModuleType('lancedb')\n\
|
||||
lancedb.__path__ = []\n\
|
||||
lancedb_remote = types.ModuleType('lancedb.remote')\n\
|
||||
lancedb_remote.__path__ = []\n\
|
||||
lancedb.remote = lancedb_remote\n\
|
||||
namespace = types.ModuleType('lance_namespace')\n\
|
||||
namespace_errors = types.ModuleType('lance_namespace.errors')\n\
|
||||
namespace_errors.TableNotFoundError = RuntimeError\n\
|
||||
namespace.errors = namespace_errors\n\
|
||||
sys.modules['lancedb'] = lancedb\n\
|
||||
sys.modules['lancedb.remote'] = lancedb_remote\n\
|
||||
sys.modules['lance_namespace'] = namespace\n\
|
||||
sys.modules['lance_namespace.errors'] = namespace_errors",
|
||||
c"error_test_bootstrap.py",
|
||||
c"lancedb_error_test_bootstrap",
|
||||
)?;
|
||||
|
||||
let exceptions_code =
|
||||
CString::new(include_str!("../../python/python/lancedb/exceptions.py")).unwrap();
|
||||
let exceptions = PyModule::from_code(
|
||||
py,
|
||||
&exceptions_code,
|
||||
c"exceptions.py",
|
||||
c"lancedb.exceptions",
|
||||
)?;
|
||||
let lancedb = py.import("lancedb")?;
|
||||
lancedb.setattr("exceptions", &exceptions)?;
|
||||
py.import("sys")?
|
||||
.getattr("modules")?
|
||||
.set_item("lancedb.exceptions", &exceptions)?;
|
||||
|
||||
let remote_errors_code =
|
||||
CString::new(include_str!("../../python/python/lancedb/remote/errors.py")).unwrap();
|
||||
let remote_errors = PyModule::from_code(
|
||||
py,
|
||||
&remote_errors_code,
|
||||
c"remote/errors.py",
|
||||
c"lancedb.remote.errors",
|
||||
)?;
|
||||
lancedb
|
||||
.getattr("remote")?
|
||||
.setattr("errors", &remote_errors)?;
|
||||
py.import("sys")?
|
||||
.getattr("modules")?
|
||||
.set_item("lancedb.remote.errors", &remote_errors)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_python_error_modules() {
|
||||
Python::initialize();
|
||||
// Once waits without holding the GIL; only its one-time closure attaches.
|
||||
INSTALL_PYTHON_ERROR_MODULES.call_once(|| {
|
||||
Python::attach(install_python_error_modules).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_job_failure_retains_the_named_resource_as_its_cause() {
|
||||
ensure_python_error_modules();
|
||||
let source = LanceError::Sql {
|
||||
message: "Function 'missing' was not found".into(),
|
||||
request_id: "current-request".into(),
|
||||
grpc_code: 5,
|
||||
metadata: Box::new({
|
||||
let mut metadata = RemoteErrorMetadata::default();
|
||||
metadata.error_code = Some("not_found".into());
|
||||
metadata.job_id = Some("outer-job".into());
|
||||
metadata.job_request_id = Some("worker-request".into());
|
||||
metadata.resource = Some(RemoteResourceIdentity::new(
|
||||
"function",
|
||||
"missing",
|
||||
vec!["ns".into()],
|
||||
));
|
||||
metadata
|
||||
}),
|
||||
};
|
||||
let error = LanceError::JobFailed {
|
||||
job_id: Some("outer-job".into()),
|
||||
failure: Box::new(JobFailure {
|
||||
message: Some("Function 'missing' was not found".into()),
|
||||
traceback: None,
|
||||
sql_job_id: Some("outer-job".into()),
|
||||
source: Some(Arc::new(source)),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
|
||||
let py_err = Python::attach(|_| {
|
||||
let result: std::result::Result<(), LanceError> = Err(error);
|
||||
result.infer_error().unwrap_err()
|
||||
});
|
||||
Python::attach(|py| {
|
||||
let value = py_err.value(py);
|
||||
let job_failed = py
|
||||
.import("lancedb.exceptions")
|
||||
.unwrap()
|
||||
.getattr("JobFailedError")
|
||||
.unwrap();
|
||||
assert!(value.is_instance(&job_failed).unwrap(), "{py_err:?}");
|
||||
let cause = value.getattr("__cause__").unwrap();
|
||||
let function_not_found = py
|
||||
.import("lancedb.remote.errors")
|
||||
.unwrap()
|
||||
.getattr("FunctionNotFoundError")
|
||||
.unwrap();
|
||||
assert!(
|
||||
cause.is_instance(&function_not_found).unwrap(),
|
||||
"{py_err:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("error_code")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"not_found"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("resource_kind")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"function"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("resource_name")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"missing"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("namespace_path")
|
||||
.unwrap()
|
||||
.extract::<Vec<String>>()
|
||||
.unwrap(),
|
||||
["ns"]
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("status_code")
|
||||
.unwrap()
|
||||
.extract::<u16>()
|
||||
.unwrap(),
|
||||
404
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("request_id")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"current-request"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("job_id")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"outer-job"
|
||||
);
|
||||
assert_eq!(
|
||||
cause
|
||||
.getattr("job_request_id")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
"worker-request"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_catalog_lookup_is_raised_as_the_named_resource_error() {
|
||||
ensure_python_error_modules();
|
||||
for (kind, name, namespace_path, exception) in [
|
||||
(
|
||||
"function",
|
||||
"missing",
|
||||
vec!["ns".into()],
|
||||
"FunctionNotFoundError",
|
||||
),
|
||||
("namespace", "ns", Vec::new(), "NamespaceNotFoundError"),
|
||||
] {
|
||||
let mut metadata = RemoteErrorMetadata::default();
|
||||
metadata.error_code = Some("not_found".into());
|
||||
metadata.resource = Some(RemoteResourceIdentity::new(kind, name, namespace_path));
|
||||
let error = LanceError::Sql {
|
||||
message: format!("{kind} '{name}' was not found"),
|
||||
request_id: "current-request".into(),
|
||||
grpc_code: 5,
|
||||
metadata: Box::new(metadata),
|
||||
};
|
||||
let py_err = Python::attach(|_| {
|
||||
let result: std::result::Result<(), LanceError> = Err(error);
|
||||
result.infer_error().unwrap_err()
|
||||
});
|
||||
Python::attach(|py| {
|
||||
let value = py_err.value(py);
|
||||
let class = py
|
||||
.import("lancedb.remote.errors")
|
||||
.unwrap()
|
||||
.getattr(exception)
|
||||
.unwrap();
|
||||
assert!(value.is_instance(&class).unwrap(), "{py_err:?}");
|
||||
assert_eq!(
|
||||
value
|
||||
.getattr("resource_name")
|
||||
.unwrap()
|
||||
.extract::<String>()
|
||||
.unwrap(),
|
||||
name
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+99
-3
@@ -8,7 +8,9 @@ use lancedb::index::vector::{
|
||||
};
|
||||
use lancedb::index::{
|
||||
Index as LanceDbIndex,
|
||||
scalar::{BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder},
|
||||
scalar::{
|
||||
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
|
||||
},
|
||||
};
|
||||
use pyo3::IntoPyObject;
|
||||
use pyo3::types::PyStringMethods;
|
||||
@@ -33,6 +35,80 @@ pub fn class_name(ob: &'_ Bound<'_, PyAny>) -> PyResult<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Code-analyzer options shared by `FTS` and `tokenize`.
|
||||
#[derive(Default)]
|
||||
pub struct CodeAnalyzerOptions {
|
||||
pub analyzer: Option<String>,
|
||||
pub split_identifiers: Option<bool>,
|
||||
pub split_on_numerics: Option<bool>,
|
||||
pub preserve_original: Option<bool>,
|
||||
pub index_operators: Option<bool>,
|
||||
}
|
||||
|
||||
impl CodeAnalyzerOptions {
|
||||
/// Check the options against the requested base tokenizer and return the
|
||||
/// base tokenizer to use. `analyzer="code"` selects the code tokenizer when
|
||||
/// `base_tokenizer` is left at its default of `"simple"`.
|
||||
pub fn resolve_base_tokenizer(&self, base_tokenizer: String) -> PyResult<String> {
|
||||
let uses_code = match self.analyzer.as_deref() {
|
||||
None | Some("text") => base_tokenizer == "code",
|
||||
Some("code") => true,
|
||||
Some(other) => {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"analyzer must be 'text' or 'code', got '{other}'"
|
||||
)));
|
||||
}
|
||||
};
|
||||
match self.analyzer.as_deref() {
|
||||
Some("text") if base_tokenizer == "code" => {
|
||||
return Err(PyValueError::new_err(
|
||||
"base_tokenizer='code' requires analyzer='code'",
|
||||
));
|
||||
}
|
||||
Some("code") if base_tokenizer != "code" && base_tokenizer != "simple" => {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"analyzer='code' requires base_tokenizer='code', got '{base_tokenizer}'"
|
||||
)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let flags = [
|
||||
self.split_identifiers,
|
||||
self.split_on_numerics,
|
||||
self.preserve_original,
|
||||
self.index_operators,
|
||||
];
|
||||
if !uses_code && flags.into_iter().flatten().any(|value| value) {
|
||||
return Err(PyValueError::new_err(
|
||||
"split_identifiers, split_on_numerics, preserve_original and \
|
||||
index_operators require analyzer='code'",
|
||||
));
|
||||
}
|
||||
Ok(if uses_code {
|
||||
"code".to_string()
|
||||
} else {
|
||||
base_tokenizer
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply the explicit flags on top of the tokenizer defaults.
|
||||
pub fn apply(&self, mut params: FtsIndexBuilder) -> FtsIndexBuilder {
|
||||
if let Some(value) = self.split_identifiers {
|
||||
params = params.split_identifiers(value);
|
||||
}
|
||||
if let Some(value) = self.split_on_numerics {
|
||||
params = params.split_on_numerics(value);
|
||||
}
|
||||
if let Some(value) = self.preserve_original {
|
||||
params = params.preserve_original(value);
|
||||
}
|
||||
if let Some(value) = self.index_operators {
|
||||
params = params.index_operators(value);
|
||||
}
|
||||
params
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<LanceDbIndex> {
|
||||
if let Some(source) = source {
|
||||
match class_name(source)?.as_str() {
|
||||
@@ -40,10 +116,19 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
"Bitmap" => Ok(LanceDbIndex::Bitmap(Default::default())),
|
||||
"LabelList" => Ok(LanceDbIndex::LabelList(Default::default())),
|
||||
"Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
|
||||
"NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
|
||||
"FTS" => {
|
||||
let params = source.extract::<FtsParams>()?;
|
||||
let code_options = CodeAnalyzerOptions {
|
||||
analyzer: params.analyzer,
|
||||
split_identifiers: params.split_identifiers,
|
||||
split_on_numerics: params.split_on_numerics,
|
||||
preserve_original: params.preserve_original,
|
||||
index_operators: params.index_operators,
|
||||
};
|
||||
let base_tokenizer = code_options.resolve_base_tokenizer(params.base_tokenizer)?;
|
||||
let mut inner_opts = FtsIndexBuilder::default()
|
||||
.base_tokenizer(params.base_tokenizer)
|
||||
.base_tokenizer(base_tokenizer)
|
||||
.language(¶ms.language)
|
||||
.map_err(|_| {
|
||||
PyValueError::new_err(format!(
|
||||
@@ -75,6 +160,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
if let Some(num_workers) = params.num_workers {
|
||||
inner_opts = inner_opts.num_workers(num_workers);
|
||||
}
|
||||
let inner_opts = code_options.apply(inner_opts);
|
||||
let inner_opts = inner_opts
|
||||
.block_size(params.block_size)
|
||||
.map_err(|err| PyValueError::new_err(err.to_string()))?;
|
||||
@@ -205,7 +291,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
|
||||
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
|
||||
}
|
||||
not_supported => Err(PyValueError::new_err(format!(
|
||||
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
|
||||
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
|
||||
not_supported
|
||||
))),
|
||||
}
|
||||
@@ -232,6 +318,11 @@ struct FtsParams {
|
||||
memory_limit: Option<u64>,
|
||||
num_workers: Option<usize>,
|
||||
document_granularity: String,
|
||||
analyzer: Option<String>,
|
||||
split_identifiers: Option<bool>,
|
||||
split_on_numerics: Option<bool>,
|
||||
preserve_original: Option<bool>,
|
||||
index_operators: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(FromPyObject)]
|
||||
@@ -493,6 +584,11 @@ mod tests {
|
||||
memory_limit = 2048
|
||||
num_workers = 7
|
||||
document_granularity = 'row'
|
||||
analyzer = None
|
||||
split_identifiers = None
|
||||
split_on_numerics = None
|
||||
preserve_original = None
|
||||
index_operators = None
|
||||
|
||||
config = FTS()",
|
||||
None,
|
||||
|
||||
+75
-5
@@ -10,7 +10,7 @@ use arrow::{
|
||||
};
|
||||
use lancedb::job::JobEventsRequest;
|
||||
use pyo3::{
|
||||
Bound, PyAny, PyRef, PyResult, Python,
|
||||
Bound, Py, PyAny, PyRef, PyResult, Python,
|
||||
exceptions::PyValueError,
|
||||
pyclass, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods},
|
||||
@@ -94,10 +94,30 @@ impl Job {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn wait(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
#[pyo3(signature = (progress=None))]
|
||||
pub fn wait(self_: PyRef<'_, Self>, progress: Option<Py<PyAny>>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let result = inner.wait().await.infer_error()?;
|
||||
let result = if let Some(progress) = progress {
|
||||
let observer = move |description: &lancedb::database::JobDescription| {
|
||||
Python::attach(|py| {
|
||||
let snapshot = description.progress_snapshot();
|
||||
let callback_result: PyResult<()> = (|| {
|
||||
let raw = snapshot.to_string();
|
||||
let parsed = parse_json_payload(py, Some(&raw))?
|
||||
.ok_or_else(|| PyValueError::new_err("missing progress"))?;
|
||||
progress.bind(py).call1((parsed,))?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = callback_result {
|
||||
log::warn!("job progress callback error: {error}");
|
||||
}
|
||||
});
|
||||
};
|
||||
inner.wait_with_progress(observer).await.infer_error()?
|
||||
} else {
|
||||
inner.wait().await.infer_error()?
|
||||
};
|
||||
result
|
||||
.map_err(|message| lancedb::Error::Runtime { message })
|
||||
.infer_error()
|
||||
@@ -164,6 +184,8 @@ pub struct JobInfo {
|
||||
job_type: String,
|
||||
state: String,
|
||||
created_at_millis: i64,
|
||||
_progress_json: Option<String>,
|
||||
paused: bool,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
@@ -174,16 +196,32 @@ impl JobInfo {
|
||||
self.job_id, self.table, self.job_type, self.state, self.created_at_millis
|
||||
)
|
||||
}
|
||||
|
||||
/// Structured progress for job types that report it. Missing fields are
|
||||
/// unknown, not zero.
|
||||
#[getter]
|
||||
fn progress<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
|
||||
parse_json_payload(py, self._progress_json.as_deref())
|
||||
}
|
||||
|
||||
/// Whether an operator has parked this job.
|
||||
#[getter]
|
||||
fn paused(&self) -> bool {
|
||||
self.paused
|
||||
}
|
||||
}
|
||||
|
||||
impl From<lancedb::database::JobInfo> for JobInfo {
|
||||
fn from(info: lancedb::database::JobInfo) -> Self {
|
||||
let progress = info.progress_snapshot().to_string();
|
||||
Self {
|
||||
job_id: info.job_id,
|
||||
table: info.table,
|
||||
job_type: info.job_type,
|
||||
state: info.state,
|
||||
created_at_millis: info.created_at_millis,
|
||||
_progress_json: Some(progress),
|
||||
paused: info.paused,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,15 +232,35 @@ impl From<lancedb::database::JobInfo> for JobInfo {
|
||||
pub struct JobFailureInfo {
|
||||
phase: Option<String>,
|
||||
message: Option<String>,
|
||||
/// User-code traceback, possibly truncated by the server.
|
||||
traceback: Option<String>,
|
||||
retryable: Option<bool>,
|
||||
sql_job_id: Option<String>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl JobFailureInfo {
|
||||
fn __repr__(&self) -> String {
|
||||
let phase = self
|
||||
.phase
|
||||
.as_ref()
|
||||
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
|
||||
let message = self
|
||||
.message
|
||||
.as_ref()
|
||||
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
|
||||
let retryable = match self.retryable {
|
||||
Some(true) => "True",
|
||||
Some(false) => "False",
|
||||
None => "None",
|
||||
};
|
||||
let sql_job_id = self
|
||||
.sql_job_id
|
||||
.as_ref()
|
||||
.map_or_else(|| "None".to_string(), |value| format!("{value:?}"));
|
||||
format!(
|
||||
"JobFailureInfo(phase={:?}, message={:?}, retryable={:?})",
|
||||
self.phase, self.message, self.retryable
|
||||
"JobFailureInfo(phase={phase}, message={message}, retryable={retryable}, \
|
||||
sql_job_id={sql_job_id})"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -219,6 +277,7 @@ pub struct JobDescription {
|
||||
_spec_json: Option<String>,
|
||||
/// Internal: the wire form behind the `result` property.
|
||||
_result_json: Option<String>,
|
||||
_progress_json: Option<String>,
|
||||
failure: Option<JobFailureInfo>,
|
||||
}
|
||||
|
||||
@@ -236,6 +295,13 @@ impl JobDescription {
|
||||
parse_json_payload(py, self._result_json.as_deref())
|
||||
}
|
||||
|
||||
/// Structured progress snapshot. Lifecycle and queue fields are present
|
||||
/// even when a job type or older server supplies no counters.
|
||||
#[getter]
|
||||
fn progress<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
|
||||
parse_json_payload(py, self._progress_json.as_deref())
|
||||
}
|
||||
|
||||
fn __repr__(&self, py: Python<'_>) -> PyResult<String> {
|
||||
let mut fields = vec![
|
||||
format!("job_id={:?}", self.job_id),
|
||||
@@ -263,6 +329,7 @@ impl JobDescription {
|
||||
|
||||
impl From<lancedb::database::JobDescription> for JobDescription {
|
||||
fn from(description: lancedb::database::JobDescription) -> Self {
|
||||
let progress_json = description.progress_snapshot().to_string();
|
||||
Self {
|
||||
job_id: description.job_id,
|
||||
job_type: description.job_type,
|
||||
@@ -273,10 +340,13 @@ impl From<lancedb::database::JobDescription> for JobDescription {
|
||||
.result
|
||||
.filter(|result| !result.is_null())
|
||||
.map(|result| result.to_string()),
|
||||
_progress_json: Some(progress_json),
|
||||
failure: description.failure.map(|failure| JobFailureInfo {
|
||||
phase: failure.phase,
|
||||
message: failure.message,
|
||||
traceback: failure.traceback,
|
||||
retryable: failure.retryable,
|
||||
sql_job_id: failure.sql_job_id,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,13 +58,31 @@ fn shutdown_runtime(py: Python<'_>) {
|
||||
py.detach(|| runtime::shutdown(std::time::Duration::from_secs(5)));
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _doc_url(campaign: &str) -> PyResult<String> {
|
||||
let link = lancedb::docs::DocLink::from_campaign(campaign).ok_or_else(|| {
|
||||
pyo3::exceptions::PyValueError::new_err(format!("unknown doc link campaign: {campaign}"))
|
||||
})?;
|
||||
Ok(link.url())
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _append_doc_url(message: &str, campaign: &str) -> PyResult<String> {
|
||||
let link = lancedb::docs::DocLink::from_campaign(campaign).ok_or_else(|| {
|
||||
pyo3::exceptions::PyValueError::new_err(format!("unknown doc link campaign: {campaign}"))
|
||||
})?;
|
||||
Ok(link.append_to(message))
|
||||
}
|
||||
|
||||
#[pymodule]
|
||||
pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
lancedb::docs::set_sdk_ident("python", env!("CARGO_PKG_VERSION"));
|
||||
let env = Env::new()
|
||||
.filter_or("LANCEDB_LOG", "warn")
|
||||
.write_style("LANCEDB_LOG_STYLE");
|
||||
env_logger::init_from_env(env);
|
||||
m.add_class::<Connection>()?;
|
||||
m.add_class::<connection::GpuClass>()?;
|
||||
m.add_class::<catalog::Catalog>()?;
|
||||
m.add_class::<catalog::DatabaseNames>()?;
|
||||
m.add_class::<listing::NameListing>()?;
|
||||
@@ -127,10 +145,14 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(table::tokenize, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(expr_col, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(expr_lit, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(expr_func, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(_doc_url, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(_append_doc_url, m)?)?;
|
||||
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
|
||||
m.add(
|
||||
"_experimental_functions_enabled",
|
||||
|
||||
@@ -70,7 +70,11 @@ fn get_dict_with_model_dump_class(py: Python<'_>) -> PyResult<Bound<'_, PyAny>>
|
||||
py.run(
|
||||
c"class DictWithModelDump(dict):
|
||||
def model_dump(self):
|
||||
return dict(self)",
|
||||
return dict(self)
|
||||
def __getattr__(self, name):
|
||||
if name.startswith('__'):
|
||||
raise AttributeError(name)
|
||||
return self.get(name)",
|
||||
None,
|
||||
Some(&locals),
|
||||
)?;
|
||||
|
||||
+2
-2
@@ -67,7 +67,7 @@ impl TryFrom<PyOAuthConfig> for OAuthConfig {
|
||||
}
|
||||
OAuthFlow::AuthorizationCode(options)
|
||||
}
|
||||
"device_code" => OAuthFlow::DeviceCode,
|
||||
"device_code" => OAuthFlow::DeviceCode(Default::default()),
|
||||
"azure_managed_identity" => OAuthFlow::AzureManagedIdentity {
|
||||
client_id: py.managed_identity_client_id,
|
||||
},
|
||||
@@ -327,7 +327,7 @@ mod tests {
|
||||
fn test_device_code_conversion() {
|
||||
let config = base_config();
|
||||
let converted = OAuthConfig::try_from(config).unwrap();
|
||||
assert!(matches!(converted.flow, OAuthFlow::DeviceCode));
|
||||
assert!(matches!(converted.flow, OAuthFlow::DeviceCode(options) if !options.use_pkce));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -16,6 +16,7 @@ use arrow::array::make_array;
|
||||
use arrow::pyarrow::FromPyArrow;
|
||||
use arrow::pyarrow::IntoPyArrow;
|
||||
use arrow::pyarrow::ToPyArrow;
|
||||
use lancedb::ApproxMode;
|
||||
use lancedb::index::scalar::{
|
||||
BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery,
|
||||
FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery,
|
||||
@@ -354,6 +355,7 @@ pub struct PyQueryRequest {
|
||||
pub limit: Option<usize>,
|
||||
pub offset: Option<usize>,
|
||||
pub take_offsets: Option<Vec<u64>>,
|
||||
pub take_row_ids: Option<Vec<u64>>,
|
||||
pub filter: Option<PyQueryFilter>,
|
||||
pub full_text_search: Option<PyLanceDB<FtsQuery>>,
|
||||
pub select: PySelect,
|
||||
@@ -370,6 +372,7 @@ pub struct PyQueryRequest {
|
||||
pub lower_bound: Option<f32>,
|
||||
pub upper_bound: Option<f32>,
|
||||
pub ef: Option<usize>,
|
||||
pub approx_mode: Option<String>,
|
||||
pub refine_factor: Option<u32>,
|
||||
pub distance_type: Option<String>,
|
||||
pub bypass_vector_index: Option<bool>,
|
||||
@@ -385,6 +388,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
limit: query_request.limit,
|
||||
offset: query_request.offset,
|
||||
take_offsets: query_request.take_offsets,
|
||||
take_row_ids: query_request.take_row_ids,
|
||||
filter: query_request.filter.map(PyQueryFilter),
|
||||
full_text_search: query_request
|
||||
.full_text_search
|
||||
@@ -403,6 +407,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
lower_bound: None,
|
||||
upper_bound: None,
|
||||
ef: None,
|
||||
approx_mode: None,
|
||||
refine_factor: None,
|
||||
distance_type: None,
|
||||
bypass_vector_index: None,
|
||||
@@ -416,6 +421,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
limit: vector_query.base.limit,
|
||||
offset: vector_query.base.offset,
|
||||
take_offsets: vector_query.base.take_offsets,
|
||||
take_row_ids: vector_query.base.take_row_ids,
|
||||
filter: vector_query.base.filter.map(PyQueryFilter),
|
||||
full_text_search: None,
|
||||
select_source_columns: PySelect::source_columns(&vector_query.base.select),
|
||||
@@ -432,6 +438,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
lower_bound: vector_query.lower_bound,
|
||||
upper_bound: vector_query.upper_bound,
|
||||
ef: vector_query.ef,
|
||||
approx_mode: vector_query.approx_mode.map(|m| m.to_string()),
|
||||
refine_factor: vector_query.refine_factor,
|
||||
distance_type: vector_query.distance_type.map(|d| d.to_string()),
|
||||
bypass_vector_index: Some(!vector_query.use_index),
|
||||
@@ -1069,6 +1076,12 @@ impl VectorQuery {
|
||||
self.inner = self.inner.clone().ef(ef as usize);
|
||||
}
|
||||
|
||||
pub fn approx_mode(&mut self, approx_mode: String) -> PyResult<()> {
|
||||
let approx_mode = ApproxMode::try_from(approx_mode.as_str()).infer_error()?;
|
||||
self.inner = self.inner.clone().approx_mode(approx_mode);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn bypass_vector_index(&mut self) {
|
||||
self.inner = self.inner.clone().bypass_vector_index()
|
||||
}
|
||||
@@ -1246,6 +1259,10 @@ impl HybridQuery {
|
||||
self.inner_vec.ef(ef);
|
||||
}
|
||||
|
||||
pub fn approx_mode(&mut self, approx_mode: String) -> PyResult<()> {
|
||||
self.inner_vec.approx_mode(approx_mode)
|
||||
}
|
||||
|
||||
pub fn bypass_vector_index(&mut self) {
|
||||
self.inner_vec.bypass_vector_index();
|
||||
}
|
||||
@@ -1291,6 +1308,7 @@ impl HybridQuery {
|
||||
req.maximum_nprobes = vec_req.maximum_nprobes;
|
||||
req.search_effort = vec_req.search_effort;
|
||||
req.ef = vec_req.ef;
|
||||
req.approx_mode = vec_req.approx_mode;
|
||||
req.refine_factor = vec_req.refine_factor;
|
||||
req.lower_bound = vec_req.lower_bound;
|
||||
req.upper_bound = vec_req.upper_bound;
|
||||
|
||||
+323
-40
@@ -14,13 +14,14 @@ use crate::{
|
||||
connection::Connection,
|
||||
error::PythonErrorExt,
|
||||
expr::PyExpr,
|
||||
index::{IndexConfig, extract_index_params},
|
||||
index::{CodeAnalyzerOptions, IndexConfig, extract_index_params},
|
||||
query::{Query, TakeQuery},
|
||||
table::scannable::PyScannable,
|
||||
};
|
||||
use arrow::{
|
||||
array::{Array, LargeBinaryArray},
|
||||
array::{Array, LargeBinaryArray, RecordBatchIterator, RecordBatchReader},
|
||||
datatypes::{DataType, Schema},
|
||||
ffi_stream::ArrowArrayStreamReader,
|
||||
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
|
||||
};
|
||||
use lancedb::blob::{BlobDescriptor, BlobFile, BlobRangeRequest};
|
||||
@@ -28,8 +29,8 @@ use lancedb::connection::LanceFileVersion;
|
||||
use lancedb::index::scalar::FtsIndexBuilder;
|
||||
use lancedb::table::{
|
||||
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
|
||||
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform,
|
||||
OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable,
|
||||
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref,
|
||||
RefreshColumnOptions, Table as LanceDbTable,
|
||||
};
|
||||
use lancedb::tokenize as lancedb_tokenize;
|
||||
use pyo3::{
|
||||
@@ -41,6 +42,95 @@ use pyo3::{
|
||||
|
||||
mod scannable;
|
||||
|
||||
/// Keyword arguments shared by `refresh_column` and `refresh_column_async`.
|
||||
struct RefreshColumnArgs {
|
||||
where_clause: Option<String>,
|
||||
batch_size: Option<i64>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<i64>,
|
||||
retry_policy: Option<String>,
|
||||
error_policy: Option<String>,
|
||||
max_failed_fraction: Option<f64>,
|
||||
max_failed_rows: Option<i64>,
|
||||
row_timeout_seconds: Option<f64>,
|
||||
init_timeout_seconds: Option<f64>,
|
||||
num_workers: Option<i64>,
|
||||
max_executor_processes_per_worker: Option<i64>,
|
||||
}
|
||||
|
||||
fn positive_count<T: TryFrom<i64>>(value: Option<i64>, name: &str) -> PyResult<Option<T>> {
|
||||
value
|
||||
.map(|v| {
|
||||
T::try_from(v)
|
||||
.ok()
|
||||
.filter(|_| v > 0)
|
||||
.ok_or_else(|| PyValueError::new_err(format!("{name} must be greater than zero")))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOptions> {
|
||||
let RefreshColumnArgs {
|
||||
where_clause,
|
||||
batch_size,
|
||||
gpu_class,
|
||||
gpu_count,
|
||||
retry_policy,
|
||||
error_policy,
|
||||
max_failed_fraction,
|
||||
max_failed_rows,
|
||||
row_timeout_seconds,
|
||||
init_timeout_seconds,
|
||||
num_workers,
|
||||
max_executor_processes_per_worker,
|
||||
} = args;
|
||||
let mut options = RefreshColumnOptions::default();
|
||||
options.where_clause = where_clause;
|
||||
options.max_failed_fraction = max_failed_fraction;
|
||||
options.max_failed_rows = max_failed_rows
|
||||
.map(u64::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| PyValueError::new_err("max_failed_rows must be a non-negative integer"))?;
|
||||
options.row_timeout_seconds = row_timeout_seconds;
|
||||
options.init_timeout_seconds = init_timeout_seconds;
|
||||
options.num_workers = positive_count(num_workers, "num_workers")?;
|
||||
options.max_executor_processes_per_worker = positive_count(
|
||||
max_executor_processes_per_worker,
|
||||
"max_executor_processes_per_worker",
|
||||
)?;
|
||||
options.retry_policy = retry_policy
|
||||
.map(|json| {
|
||||
serde_json::from_str(&json)
|
||||
.map_err(|error| PyValueError::new_err(format!("invalid retry_policy: {error}")))
|
||||
})
|
||||
.transpose()?;
|
||||
options.error_policy = error_policy
|
||||
.map(|value| {
|
||||
serde_json::from_value(serde_json::Value::String(value))
|
||||
.map_err(|error| PyValueError::new_err(format!("invalid error_policy: {error}")))
|
||||
})
|
||||
.transpose()?;
|
||||
options.batch_size = batch_size
|
||||
.map(usize::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?;
|
||||
options.gpu_class = gpu_class;
|
||||
options.gpu_count = gpu_count
|
||||
.map(|count| {
|
||||
u32::try_from(count)
|
||||
.ok()
|
||||
.filter(|count| *count > 0)
|
||||
.ok_or_else(|| {
|
||||
PyValueError::new_err(
|
||||
"gpu_count must be a positive integer no greater than u32::MAX",
|
||||
)
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
options.validate().infer_error()?;
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// Convert `RTEStats` to a Python dict, preserving the per-table-shard list.
|
||||
///
|
||||
/// Deliberately not flattened to a table-level summary: a table is N
|
||||
@@ -583,27 +673,39 @@ impl From<lancedb::table::RefreshColumnResult> for RefreshColumnResult {
|
||||
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FunctionErrorRecord {
|
||||
pub attempts: Option<u32>,
|
||||
pub job_id: String,
|
||||
pub fragment_id: u64,
|
||||
pub row_offset: Option<u32>,
|
||||
pub row_id: Option<u64>,
|
||||
pub row_address: Option<u64>,
|
||||
pub column: String,
|
||||
pub function: String,
|
||||
pub function_version: String,
|
||||
pub table_version: u64,
|
||||
pub error_type: String,
|
||||
pub error_message: String,
|
||||
/// User-code traceback, possibly truncated by the server.
|
||||
pub traceback: Option<String>,
|
||||
pub created_at_millis: i64,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl FunctionErrorRecord {
|
||||
pub fn __repr__(&self) -> String {
|
||||
let row_offset = self
|
||||
.row_offset
|
||||
.map_or_else(|| "None".to_string(), |value| value.to_string());
|
||||
let row_address = self
|
||||
.row_address
|
||||
.map_or_else(|| "None".to_string(), |value| value.to_string());
|
||||
format!(
|
||||
"FunctionErrorRecord(job_id={:?}, fragment_id={}, row_offset={:?}, column={:?}, \
|
||||
error_type={:?}, error_message={:?})",
|
||||
"FunctionErrorRecord(job_id={:?}, fragment_id={}, row_offset={}, row_address={}, \
|
||||
column={:?}, error_type={:?}, error_message={:?})",
|
||||
self.job_id,
|
||||
self.fragment_id,
|
||||
self.row_offset,
|
||||
row_offset,
|
||||
row_address,
|
||||
self.column,
|
||||
self.error_type,
|
||||
self.error_message
|
||||
@@ -614,15 +716,19 @@ impl FunctionErrorRecord {
|
||||
impl From<lancedb::function::FunctionErrorRecord> for FunctionErrorRecord {
|
||||
fn from(record: lancedb::function::FunctionErrorRecord) -> Self {
|
||||
Self {
|
||||
attempts: record.attempts,
|
||||
job_id: record.job_id,
|
||||
fragment_id: record.fragment_id,
|
||||
row_offset: record.row_offset,
|
||||
row_id: record.row_id,
|
||||
row_address: record.row_address,
|
||||
column: record.column,
|
||||
function: record.function,
|
||||
function_version: record.function_version,
|
||||
table_version: record.table_version,
|
||||
error_type: record.error_type,
|
||||
error_message: record.error_message,
|
||||
traceback: record.traceback,
|
||||
created_at_millis: record.created_at_millis,
|
||||
}
|
||||
}
|
||||
@@ -993,7 +1099,12 @@ impl From<LanceDbFtsToken> for FtsToken {
|
||||
ascii_folding = true,
|
||||
ngram_min_length = 3,
|
||||
ngram_max_length = 3,
|
||||
prefix_only = false
|
||||
prefix_only = false,
|
||||
analyzer = None,
|
||||
split_identifiers = None,
|
||||
split_on_numerics = None,
|
||||
preserve_original = None,
|
||||
index_operators = None
|
||||
))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn tokenize(
|
||||
@@ -1009,7 +1120,20 @@ pub fn tokenize(
|
||||
ngram_min_length: u32,
|
||||
ngram_max_length: u32,
|
||||
prefix_only: bool,
|
||||
analyzer: Option<String>,
|
||||
split_identifiers: Option<bool>,
|
||||
split_on_numerics: Option<bool>,
|
||||
preserve_original: Option<bool>,
|
||||
index_operators: Option<bool>,
|
||||
) -> PyResult<Vec<FtsToken>> {
|
||||
let code_options = CodeAnalyzerOptions {
|
||||
analyzer,
|
||||
split_identifiers,
|
||||
split_on_numerics,
|
||||
preserve_original,
|
||||
index_operators,
|
||||
};
|
||||
let base_tokenizer = code_options.resolve_base_tokenizer(base_tokenizer)?;
|
||||
let mut params = FtsIndexBuilder::default()
|
||||
.base_tokenizer(base_tokenizer)
|
||||
.language(&language)
|
||||
@@ -1032,6 +1156,7 @@ pub fn tokenize(
|
||||
if let Some(remove_stop_words) = remove_stop_words {
|
||||
params = params.remove_stop_words(remove_stop_words);
|
||||
}
|
||||
let params = code_options.apply(params);
|
||||
let tokens = lancedb_tokenize(&query, ¶ms).infer_error()?;
|
||||
Ok(tokens.into_iter().map(FtsToken::from).collect())
|
||||
}
|
||||
@@ -1713,6 +1838,10 @@ impl Table {
|
||||
compaction_options: Option<&Bound<'py, PyDict>>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let target_specified = compaction_options
|
||||
.map(|options| options.contains("target_rows_per_fragment"))
|
||||
.transpose()?
|
||||
.unwrap_or(false);
|
||||
let compaction_options = parse_compaction_options(compaction_options)?;
|
||||
let older_than = if let Some(ms) = cleanup_since_ms {
|
||||
if ms > i64::MAX as u64 {
|
||||
@@ -1727,31 +1856,24 @@ impl Table {
|
||||
None
|
||||
};
|
||||
future_into_py(self_.py(), async move {
|
||||
let compaction_stats = inner
|
||||
.optimize(OptimizeAction::Compact {
|
||||
options: compaction_options,
|
||||
remap_options: None,
|
||||
})
|
||||
.await
|
||||
.infer_error()?
|
||||
.compaction
|
||||
.unwrap();
|
||||
let prune_stats = inner
|
||||
.optimize(OptimizeAction::Prune {
|
||||
older_than,
|
||||
delete_unverified,
|
||||
error_if_tagged_old_versions: None,
|
||||
})
|
||||
.await
|
||||
.infer_error()?
|
||||
.prune
|
||||
.unwrap();
|
||||
inner
|
||||
.optimize(lancedb::table::OptimizeAction::Index(
|
||||
OptimizeOptions::default(),
|
||||
))
|
||||
.await
|
||||
.infer_error()?;
|
||||
let stats = if inner.as_native().is_some() {
|
||||
inner
|
||||
.optimize_full(compaction_options, older_than, None, delete_unverified)
|
||||
.await
|
||||
} else {
|
||||
let mut overrides =
|
||||
lancedb::table::optimize::CompactionOverrides::try_from(compaction_options)
|
||||
.infer_error()?;
|
||||
if !target_specified {
|
||||
overrides.target_rows_per_fragment = None;
|
||||
}
|
||||
inner
|
||||
.optimize_full_with_overrides(overrides, older_than, None, delete_unverified)
|
||||
.await
|
||||
}
|
||||
.infer_error()?;
|
||||
let compaction_stats = stats.compaction.unwrap();
|
||||
let prune_stats = stats.prune.unwrap();
|
||||
Ok(OptimizeStats {
|
||||
compaction: CompactionStats {
|
||||
files_added: compaction_stats.files_added as u64,
|
||||
@@ -1850,6 +1972,45 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_table_overrides(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let overrides = inner.get_table_overrides().await.infer_error()?;
|
||||
serde_json::to_string(&overrides).map_err(|err| {
|
||||
PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}"))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update_table_overrides<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
overrides_json: String,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let overrides = serde_json::from_str(&overrides_json).map_err(|err| {
|
||||
PyValueError::new_err(format!("Invalid table overrides JSON: {err}"))
|
||||
})?;
|
||||
let overrides = inner
|
||||
.update_table_overrides(overrides)
|
||||
.await
|
||||
.infer_error()?;
|
||||
serde_json::to_string(&overrides).map_err(|err| {
|
||||
PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}"))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn reset_table_overrides(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let overrides = inner.reset_table_overrides().await.infer_error()?;
|
||||
serde_json::to_string(&overrides).map_err(|err| {
|
||||
PyRuntimeError::new_err(format!("Failed to serialize table overrides: {err}"))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a hybrid query on this table has already been refused `_rowid`.
|
||||
/// Learned from a previous refusal, never probed, so this is free.
|
||||
///
|
||||
@@ -1923,7 +2084,7 @@ impl Table {
|
||||
inner
|
||||
.as_native()
|
||||
.ok_or_else(|| lancedb::Error::NotSupported {
|
||||
message: "uses_v2_manifest_paths is not supported in LanceDB Distributed."
|
||||
message: "uses_v2_manifest_paths is not supported in LanceDB Enterprise."
|
||||
.into(),
|
||||
})
|
||||
.infer_error()?
|
||||
@@ -1939,7 +2100,7 @@ impl Table {
|
||||
inner
|
||||
.as_native()
|
||||
.ok_or_else(|| lancedb::Error::NotSupported {
|
||||
message: "migrate_manifest_paths_v2 is not supported in LanceDB Distributed."
|
||||
message: "migrate_manifest_paths_v2 is not supported in LanceDB Enterprise."
|
||||
.into(),
|
||||
})
|
||||
.infer_error()?
|
||||
@@ -1967,6 +2128,29 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_columns_from_reader<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
data: Bound<'a, PyAny>,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let reader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?;
|
||||
let schema = reader.schema();
|
||||
// Lance's surplus-row check treats trailing empty batches as extra data.
|
||||
let reader = RecordBatchIterator::new(
|
||||
reader.filter(|batch| !batch.as_ref().is_ok_and(|batch| batch.num_rows() == 0)),
|
||||
schema,
|
||||
);
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let result = inner
|
||||
.add_columns()
|
||||
.transform(NewColumnTransform::Reader(Box::new(reader)))
|
||||
.execute()
|
||||
.await
|
||||
.infer_error()?;
|
||||
Ok(AddColumnsResult::from(result))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
|
||||
pub fn add_computed_columns(
|
||||
self_: PyRef<'_, Self>,
|
||||
@@ -2024,21 +2208,86 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn refresh_column(self_: PyRef<'_, Self>, column: String) -> PyResult<Bound<'_, PyAny>> {
|
||||
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_column(
|
||||
self_: PyRef<'_, Self>,
|
||||
column: String,
|
||||
r#where: Option<String>,
|
||||
batch_size: Option<i64>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<i64>,
|
||||
retry_policy: Option<String>,
|
||||
error_policy: Option<String>,
|
||||
max_failed_fraction: Option<f64>,
|
||||
max_failed_rows: Option<i64>,
|
||||
row_timeout_seconds: Option<f64>,
|
||||
init_timeout_seconds: Option<f64>,
|
||||
num_workers: Option<i64>,
|
||||
max_executor_processes_per_worker: Option<i64>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let options = refresh_column_options(RefreshColumnArgs {
|
||||
where_clause: r#where,
|
||||
batch_size,
|
||||
gpu_class,
|
||||
gpu_count,
|
||||
retry_policy,
|
||||
error_policy,
|
||||
max_failed_fraction,
|
||||
max_failed_rows,
|
||||
row_timeout_seconds,
|
||||
init_timeout_seconds,
|
||||
num_workers,
|
||||
max_executor_processes_per_worker,
|
||||
})?;
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let result = inner.refresh_column(column).await.infer_error()?;
|
||||
let result = inner
|
||||
.refresh_column_with_options(column, options)
|
||||
.await
|
||||
.infer_error()?;
|
||||
Ok(RefreshColumnResult::from(result))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_column_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
column: String,
|
||||
r#where: Option<String>,
|
||||
batch_size: Option<i64>,
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<i64>,
|
||||
retry_policy: Option<String>,
|
||||
error_policy: Option<String>,
|
||||
max_failed_fraction: Option<f64>,
|
||||
max_failed_rows: Option<i64>,
|
||||
row_timeout_seconds: Option<f64>,
|
||||
init_timeout_seconds: Option<f64>,
|
||||
num_workers: Option<i64>,
|
||||
max_executor_processes_per_worker: Option<i64>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let options = refresh_column_options(RefreshColumnArgs {
|
||||
where_clause: r#where,
|
||||
batch_size,
|
||||
gpu_class,
|
||||
gpu_count,
|
||||
retry_policy,
|
||||
error_policy,
|
||||
max_failed_fraction,
|
||||
max_failed_rows,
|
||||
row_timeout_seconds,
|
||||
init_timeout_seconds,
|
||||
num_workers,
|
||||
max_executor_processes_per_worker,
|
||||
})?;
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let job = inner.refresh_column_async(column).await.infer_error()?;
|
||||
let job = inner
|
||||
.refresh_column_async_with_options(column, options)
|
||||
.await
|
||||
.infer_error()?;
|
||||
Ok(crate::job::Job::new_typed(job))
|
||||
})
|
||||
}
|
||||
@@ -2062,11 +2311,16 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (source_version=None, *, full=false))]
|
||||
#[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_materialized_view(
|
||||
self_: PyRef<'_, Self>,
|
||||
source_version: Option<u64>,
|
||||
full: bool,
|
||||
cpu_millis: Option<u64>,
|
||||
memory_bytes: Option<u64>,
|
||||
gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -2074,6 +2328,18 @@ impl Table {
|
||||
.await
|
||||
.infer_error()?;
|
||||
let mut builder = view.refresh().full(full);
|
||||
if let Some(value) = cpu_millis {
|
||||
builder = builder.cpu_millis(value);
|
||||
}
|
||||
if let Some(value) = memory_bytes {
|
||||
builder = builder.memory_bytes(value);
|
||||
}
|
||||
if let Some(value) = gpu_count {
|
||||
builder = builder.gpu_count(value);
|
||||
}
|
||||
if let Some(value) = gpu_class {
|
||||
builder = builder.gpu_class(value);
|
||||
}
|
||||
if let Some(version) = source_version {
|
||||
builder = builder.source_version(version);
|
||||
}
|
||||
@@ -2082,11 +2348,16 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (source_version=None, *, full=false))]
|
||||
#[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_materialized_view_async(
|
||||
self_: PyRef<'_, Self>,
|
||||
source_version: Option<u64>,
|
||||
full: bool,
|
||||
cpu_millis: Option<u64>,
|
||||
memory_bytes: Option<u64>,
|
||||
gpu_count: Option<u32>,
|
||||
gpu_class: Option<String>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -2094,6 +2365,18 @@ impl Table {
|
||||
.await
|
||||
.infer_error()?;
|
||||
let mut builder = view.refresh().full(full);
|
||||
if let Some(value) = cpu_millis {
|
||||
builder = builder.cpu_millis(value);
|
||||
}
|
||||
if let Some(value) = memory_bytes {
|
||||
builder = builder.memory_bytes(value);
|
||||
}
|
||||
if let Some(value) = gpu_count {
|
||||
builder = builder.gpu_count(value);
|
||||
}
|
||||
if let Some(value) = gpu_class {
|
||||
builder = builder.gpu_class(value);
|
||||
}
|
||||
if let Some(version) = source_version {
|
||||
builder = builder.source_version(version);
|
||||
}
|
||||
|
||||
@@ -61,6 +61,23 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> {
|
||||
.map_err(|e| PyValueError::new_err(e.to_string()))
|
||||
}
|
||||
|
||||
/// Parse field references with the same identifier syntax as Lance writes.
|
||||
#[pyfunction(name = "_parse_field_path")]
|
||||
pub fn parse_field_path(path: &str) -> PyResult<Vec<String>> {
|
||||
lance_core::datatypes::parse_field_path(path).map_err(|e| PyValueError::new_err(e.to_string()))
|
||||
}
|
||||
|
||||
/// A wrapper around a LanceDB type to allow it to be used in Python
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PyLanceDB<T>(pub T);
|
||||
/// Validate the Function retry wire contract using the same rules as Rust APIs.
|
||||
#[pyo3::pyfunction]
|
||||
pub fn validate_function_retry_policy(json: &str) -> pyo3::PyResult<()> {
|
||||
let policy: lancedb::function::FunctionRetryPolicy =
|
||||
serde_json::from_str(json).map_err(|error| {
|
||||
pyo3::exceptions::PyValueError::new_err(format!("invalid retry_policy: {error}"))
|
||||
})?;
|
||||
policy
|
||||
.validate()
|
||||
.map_err(|error| pyo3::exceptions::PyValueError::new_err(error.to_string()))
|
||||
}
|
||||
|
||||
Generated
+605
-161
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user