Merge main updates into gatekeeper/fix-4911-1

This commit is contained in:
Gatefixer
2026-11-15 14:57:14 +00:00
82 changed files with 4573 additions and 964 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.13"
version = "0.42.0-beta.15"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b21",
"pylance==15.0.0b22",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+4
View File
@@ -51,11 +51,15 @@ from .functions import (
FunctionApplication as FunctionApplication,
FunctionBinding as FunctionBinding,
FunctionDefinition as FunctionDefinition,
FunctionEnvironment as FunctionEnvironment,
FunctionRegistrationRequest as FunctionRegistrationRequest,
FunctionRetryPolicy as FunctionRetryPolicy,
FunctionVersion as FunctionVersion,
HuggingFaceModel as HuggingFaceModel,
PythonRuntimeSpec as PythonRuntimeSpec,
ResolvedEnvironment as ResolvedEnvironment,
ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance,
ResolvedPackage as ResolvedPackage,
RefreshColumnResult as RefreshColumnResult,
function as function,
udf as udf,
+20 -1
View File
@@ -300,7 +300,19 @@ class Connection(object):
page_limit: Optional[int] = None,
) -> NameListing: ...
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> JobListing: ...
async def cancel_job(self, job_id: str) -> bool: ...
async def pause_job(self, job_id: str) -> str: ...
@@ -565,6 +577,12 @@ class Table:
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult: ...
async def execute_merge_insert(
self,
data: pa.RecordBatchReader,
parameters: Dict[str, Any],
retries: Optional[int] = None,
) -> MergeResult: ...
async def update(
self, updates: Dict[str, str], where: Optional[str]
) -> UpdateResult: ...
@@ -925,6 +943,7 @@ class FTSQuery:
def add_query_vector(self, query_vec: pa.Array) -> None: ...
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
async def count_rows(self) -> int: ...
async def output_schema(self) -> pa.Schema: ...
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
+182 -21
View File
@@ -154,6 +154,38 @@ def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[
raise TypeError("version must be an int, str, or None")
def _function_registration_decoder():
"""Parse a registration result and emit its server warnings once.
The warnings come from the scalar environment or, for a multiarchitecture
image, each measured platform entry. They are part of the registration job
result, not a new client-side package policy. Catalog get/list readbacks
use ``FunctionVersion.from_json`` directly and therefore do not replay
them.
"""
warned = False
def decode(payload: str) -> FunctionVersion:
nonlocal warned
version = FunctionVersion.from_json(payload)
if not warned:
environments = [
environment
for environment in (
version.resolved_environment,
*version.resolved_environments.values(),
)
if environment is not None
]
for environment in environments:
for message in environment.warnings:
warnings.warn(message, UserWarning, stacklevel=3)
warned = True
return version
return decode
class DBConnection(EnforceOverrides):
"""An active LanceDB connection interface.
@@ -1018,6 +1050,8 @@ class DBConnection(EnforceOverrides):
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
refresh_lock: bool = False,
progress: Any = False,
) -> FunctionVersion:
"""Build and register a scalar Python function, then return its version.
@@ -1040,6 +1074,16 @@ class DBConnection(EnforceOverrides):
namespace_path : list of str, optional
The namespace holding the Function. None or an empty list is the
root namespace.
refresh_lock : bool, default False
Ask the server to resolve a fresh environment lock instead of
reusing the published version's lock.
progress : bool, callable, or tqdm-like object, default False
Display lifecycle state and elapsed time, or receive structured
snapshots through a callback. See [Job.wait][lancedb.job.Job.wait].
When the registration job resolves, each resolved-environment warning
reported by the server is emitted as a Python ``UserWarning``. Catalog
reads do not replay those registration warnings.
Examples
--------
@@ -1055,12 +1099,16 @@ class DBConnection(EnforceOverrides):
)
```
"""
return self.create_function_async(
job = self.create_function_async(
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
).wait()
refresh_lock=refresh_lock,
)
if progress is False or progress is None:
return job.wait()
return job.wait(progress=progress)
def create_function_async(
self,
@@ -1069,6 +1117,7 @@ class DBConnection(EnforceOverrides):
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
refresh_lock: bool = False,
) -> Job[FunctionVersion]:
"""Submit a scalar Python function for building and registration.
@@ -1079,6 +1128,11 @@ class DBConnection(EnforceOverrides):
artifact. The returned job has type ``query`` and the SQL query UUID as
its ID. Waiting on it returns the immutable Function version.
LanceDB Embedded connections raise ``NotImplementedError``.
``refresh_lock`` asks the server to resolve a fresh environment lock
instead of reusing the published version's lock. Waiting on the job
emits the server's resolved-environment warnings as Python warnings;
reading the same version later does not repeat them.
"""
raise NotImplementedError(
_append_doc_url(
@@ -1555,13 +1609,39 @@ class DBConnection(EnforceOverrides):
)
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> Listing[JobInfo]:
"""List server-side jobs across the database's tables.
"""List server-side jobs, optionally filtered before pagination.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
``page_token`` resumes from a saved token. Requests and errors occur during
iteration. See [pagination state][lancedb.listing.AsyncListing].
``table`` names a table in ``namespace_path`` (the root by default).
Listings include all branches of the table. A namespace filter requires
``table``.
``state`` uses registry states such as ``in_progress``, ``succeeded``,
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
Creation-time bounds are Unix milliseconds, inclusive at
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
Resume a ``page_token`` with the same filters. Requests and errors occur
during iteration. See [pagination state][lancedb.listing.AsyncListing].
For example, to inspect up to five jobs without fetching all history::
jobs = db.list_jobs(table="events", page_limit=5)
first_five = jobs[:5]
"""
raise NotImplementedError(
_append_doc_url(
@@ -2432,6 +2512,7 @@ class LanceDBConnection(DBConnection):
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
refresh_lock: bool = False,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
@@ -2439,6 +2520,7 @@ class LanceDBConnection(DBConnection):
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
refresh_lock=refresh_lock,
)
)
return Job(job)
@@ -2750,16 +2832,52 @@ class LanceDBConnection(DBConnection):
@override
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> Listing[JobInfo]:
"""List server-side jobs across the database's tables.
"""List server-side jobs, optionally filtered before pagination.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
``page_token`` resumes from a saved token. Requests and errors occur during
iteration. See [pagination state][lancedb.listing.AsyncListing].
``table`` names a table in ``namespace_path`` (the root by default).
Listings include all branches of the table. A namespace filter requires
``table``.
``state`` uses registry states such as ``in_progress``, ``succeeded``,
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
Creation-time bounds are Unix milliseconds, inclusive at
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
Resume a ``page_token`` with the same filters. Requests and errors occur
during iteration. See [pagination state][lancedb.listing.AsyncListing].
For example, to inspect up to five jobs without fetching all history::
jobs = db.list_jobs(table="events", page_limit=5)
first_five = jobs[:5]
"""
return Listing(
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
self._conn.list_jobs(
page_token=page_token,
page_limit=page_limit,
table=table,
namespace_path=namespace_path,
state=state,
job_type=job_type,
job_types=job_types,
created_at_gte_millis=created_at_gte_millis,
created_at_lt_millis=created_at_lt_millis,
)
)
@override
@@ -3788,6 +3906,7 @@ class AsyncConnection(object):
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
refresh_lock: bool = False,
) -> AsyncJob[FunctionVersion]:
"""Submit a scalar Python function for building and registration.
@@ -3802,14 +3921,16 @@ class AsyncConnection(object):
the environment variable its value arrives in. ``namespace_path`` is
the namespace the Function is registered in; None or an empty list is
the root. LanceDB Embedded connections raise ``NotImplementedError``.
``refresh_lock`` asks the server to resolve a fresh environment lock
instead of reusing the published version's lock.
"""
if not isinstance(definition, FunctionDefinition):
raise TypeError("create_function_async requires a @function definition")
request = definition.bind_secrets(secrets)
request = definition.bind_secrets(secrets).with_refresh_lock(refresh_lock)
inner = await self._inner.create_function_async(
request.to_canonical_json(), namespace_path, exist_ok=exist_ok
)
return _typed_job(inner, FunctionVersion.from_json)
return _typed_job(inner, _function_registration_decoder())
async def get_function(
self,
@@ -4323,16 +4444,56 @@ class AsyncConnection(object):
)
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> AsyncListing[JobInfo]:
"""List server-side jobs across the database's tables.
"""List server-side jobs, optionally filtered before pagination.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
``page_token`` resumes from a saved token. Requests and errors occur during
iteration. See [pagination state][lancedb.listing.AsyncListing].
``table`` names a table in ``namespace_path`` (the root by default).
Listings include all branches of the table. A namespace filter requires
``table``.
``state`` uses registry states such as ``in_progress``, ``succeeded``,
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
Creation-time bounds are Unix milliseconds, inclusive at
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
Resume a ``page_token`` with the same filters. Requests and errors occur
during iteration. See [pagination state][lancedb.listing.AsyncListing].
For example, to inspect up to five jobs without fetching all history::
jobs = db.list_jobs(table="events", page_limit=5)
first_five = []
async for job in jobs:
first_five.append(job)
if len(first_five) == 5:
break
"""
return AsyncListing(
self._inner.list_jobs(page_token=page_token, page_limit=page_limit)
self._inner.list_jobs(
page_token=page_token,
page_limit=page_limit,
table=table,
namespace_path=namespace_path,
state=state,
job_type=job_type,
job_types=job_types,
created_at_gte_millis=created_at_gte_millis,
created_at_lt_millis=created_at_lt_millis,
)
)
async def cancel_job(self, job_id: str) -> bool:
+287 -9
View File
@@ -29,13 +29,15 @@ import textwrap
import types
import warnings
from collections.abc import Mapping, Sequence
from datetime import date, datetime
from datetime import date, datetime, timedelta
from decimal import Decimal
from pathlib import Path
from typing import (
Annotated,
Any,
Callable,
Literal,
NamedTuple,
Optional,
TYPE_CHECKING,
Union,
@@ -101,6 +103,12 @@ def _validate_batch_size(value: Any) -> Optional[int]:
return value
def _validate_refresh_lock(value: Any) -> bool:
if not isinstance(value, bool):
raise ValueError("refresh_lock must be a boolean")
return value
def _validate_max_concurrency(value: Any) -> Optional[int]:
if value is None:
return None
@@ -536,13 +544,131 @@ class PythonRuntimeSpec(_RemoteValue):
class FunctionImage(_RemoteValue):
"""A complete OCI Function image identified by its exact manifest digest."""
"""A complete OCI Function image identified by its exact manifest digest.
``describe()`` and the concise representation inspect the descriptor without
walking Pydantic model internals. Missing metadata is ``None`` (unknown).
The current service does not report image platforms, base image or byte size;
these cannot be inferred from the client's platform or the manifest digest.
The full descriptor remains available through ``descriptor``.
"""
manifest_digest: str
descriptor: Mapping[str, Any]
source: bool
models: tuple[HuggingFaceModel, ...] = ()
def describe(self) -> dict[str, Any]:
"""Return concise image details without fetching registry content.
``requires_gpu`` reflects a ``lance.cuda`` requirement in a v1
descriptor, rather than promising compatibility with every GPU.
``platforms``, ``base_image`` and ``size_bytes`` are unavailable from
the current wire contract and return ``None``.
Examples
--------
>>> print(fn.image.describe()) # doctest: +SKIP
"""
python = self.descriptor.get("python")
requires = self.descriptor.get("requires")
capabilities = (
requires.get("capabilities") if isinstance(requires, Mapping) else None
)
known_capabilities = (
self.descriptor.get("format_version") == 1
and isinstance(capabilities, (list, tuple))
and all(isinstance(item, Mapping) for item in capabilities)
)
cuda = (
next(
(item for item in capabilities if item.get("type") == "lance.cuda"),
None,
)
if known_capabilities
else None
)
python_version = python.get("version") if isinstance(python, Mapping) else None
cuda_toolkit = cuda.get("cuda_toolkit") if cuda is not None else None
return {
"manifest_digest": self.manifest_digest,
"python_version": python_version
if isinstance(python_version, str)
else None,
"requires_gpu": cuda is not None if known_capabilities else None,
"cuda_toolkit": cuda_toolkit if isinstance(cuda_toolkit, str) else None,
"platforms": None,
"base_image": None,
"size_bytes": None,
}
def __repr_args__(self):
for name, value in self.describe().items():
if isinstance(value, str) and len(value) > 80:
value = value[:77] + "..."
yield name, value
class ResolvedPackage(_RemoteValue):
"""One installed Python distribution measured from a baked environment.
``version`` is the complete version reported by package metadata,
including local labels such as ``+cu130``. ``source`` is present only when
the submitted lock retained a per-package source; absent means unknown, not
an inferred index.
"""
name: str
version: str
source: Optional[str] = None
class ResolvedEnvironmentProvenance(_RemoteValue):
"""Sanitized source and accelerator provenance for a resolved environment.
``configured_index_urls`` and ``configured_find_links`` record build
inputs. ``resolved_indexes`` records indexes visible in the submitted lock,
so a configured source is not by itself evidence that a package came from
it. Empty lists and absent fields remain absent; the client does not
synthesize them.
"""
configured_index_urls: tuple[str, ...] = ()
configured_find_links: tuple[str, ...] = ()
resolved_indexes: tuple[str, ...] = ()
cuda_toolkit: Optional[str] = None
torch_version: Optional[str] = None
class ResolvedEnvironment(_RemoteValue):
"""Actual installed distributions and registration warnings for one platform.
A missing value means its measurement is unknown, not an empty
installed-package list. Versions are retained verbatim, including local
labels; package ``source`` is retained only when the producer recorded it.
"""
packages: tuple[ResolvedPackage, ...]
provenance: Optional[ResolvedEnvironmentProvenance] = None
warnings: tuple[str, ...] = ()
class FunctionEnvironment(NamedTuple):
"""Requested and measured environment view for a Function version.
This is a view over
[FunctionVersion.runtime][lancedb.functions.FunctionVersion.runtime]
and
[FunctionVersion.resolved_environment][lancedb.functions.FunctionVersion.resolved_environment].
It adds no wire field and performs no second parse. ``requested`` is the
runtime specification supplied at registration; ``resolved`` is measured
data and is ``None`` when unknown. For per-platform multiarchitecture
measurements, use ``FunctionVersion.environment_report``.
"""
requested: Optional[PythonRuntimeSpec]
resolved: Optional[ResolvedEnvironment]
def _validate_object_version(value: str) -> str:
if int(value) > 2**64 - 1:
@@ -593,6 +719,17 @@ class FunctionVersion(_RemoteValue):
``result_stability`` retain the execution controls reported by the
catalog. They are ``None`` for versions registered before the
corresponding declaration.
``runtime`` is the runtime specification requested at registration. It is
not evidence of what was installed. ``resolved_environment`` is measured
data for a single-platform image: actual package names and complete
versions, optional per-package source, provenance, and registration
warnings. ``resolved_environments`` is the corresponding map for a
multiarchitecture image, keyed by OCI ``os/architecture``. It is never
flattened into an aggregate package list. ``None`` or an empty map means
unknown data, not an empty installed environment. ``environment`` is a
convenience view with ``requested`` and ``resolved`` members over the same
fields.
"""
name: str
@@ -613,6 +750,11 @@ class FunctionVersion(_RemoteValue):
max_concurrency: Optional[int] = None
row_timeout_seconds: Optional[float] = None
result_stability: Optional[str] = None
runtime: Optional[PythonRuntimeSpec] = None
resolved_environment: Optional[ResolvedEnvironment] = None
resolved_environments: Mapping[str, ResolvedEnvironment] = Field(
default_factory=dict
)
@field_validator("batch_size", mode="before")
@classmethod
@@ -629,6 +771,24 @@ class FunctionVersion(_RemoteValue):
def _validate_row_timeout(cls, value):
return _validate_row_timeout(value)
@property
def environment(self) -> FunctionEnvironment:
"""Requested and measured environment without adding a second parser."""
return FunctionEnvironment(
requested=self.runtime,
resolved=self.resolved_environment,
)
@property
def environment_report(self) -> Mapping[str, ResolvedEnvironment]:
"""Per-platform measured reports, keyed by OCI ``os/architecture``.
This is the same map as ``resolved_environments`` and is never
flattened. Single-platform images use ``resolved_environment`` instead;
an absent platform means its measurement is unknown.
"""
return self.resolved_environments
def __call__(self, **arguments: Any) -> FunctionApplication:
"""Bind this exact version to named table columns and constant inputs.
@@ -769,6 +929,9 @@ class FunctionRegistrationRequest(_RemoteValue):
Credential values deliberately have no field here. The only secret-shaped
thing a client sends is ``secret_bindings``: the name of a Secret the
database already holds, which the remote service resolves at execution.
``refresh_lock`` is a per-registration action, not part of the Function's
source or runtime identity; its false default is omitted from canonical
JSON.
"""
name: str
@@ -781,6 +944,7 @@ class FunctionRegistrationRequest(_RemoteValue):
retry_policy: Optional[FunctionRetryPolicy] = None
secret_bindings: tuple[SecretBinding, ...] = ()
models: tuple[HuggingFaceModel, ...] = ()
refresh_lock: bool = False
@field_validator("batch_size", mode="before")
@classmethod
@@ -797,6 +961,18 @@ class FunctionRegistrationRequest(_RemoteValue):
def _validate_row_timeout(cls, value):
return _validate_row_timeout(value)
@field_validator("refresh_lock", mode="before")
@classmethod
def _validate_refresh_lock(cls, value):
return _validate_refresh_lock(value)
def with_refresh_lock(self, refresh_lock: bool) -> FunctionRegistrationRequest:
"""Return this request with the registration-time refresh action set."""
refresh_lock = _validate_refresh_lock(refresh_lock)
if self.refresh_lock == refresh_lock:
return self
return self._copy(update={"refresh_lock": refresh_lock})
class FunctionVersionRef(_OpenRemoteValue):
name: str
@@ -1043,6 +1219,7 @@ _GRAMMAR_PRIMITIVES = (
(pa.date32(), "date32"),
(pa.date64(), "date64"),
)
_FUNCTION_TIMEUNITS = ("s", "ms", "us", "ns")
def _canonical_arrow_type(
@@ -1259,6 +1436,33 @@ def _exact_arrow_type(
for candidate, name in _GRAMMAR_PRIMITIVES:
if data_type == candidate:
return {"type": name}
if pa.types.is_decimal128(data_type) or pa.types.is_decimal256(data_type):
return {
"type": (
"decimal128" if pa.types.is_decimal128(data_type) else "decimal256"
),
"length": data_type.precision * 1000 + data_type.scale,
}
if pa.types.is_timestamp(data_type):
unit = data_type.unit
if unit not in _FUNCTION_TIMEUNITS:
raise TypeError(f"unsupported Function timestamp unit: {unit!r}")
timezone = data_type.tz
if timezone == "-":
raise TypeError(
"unsupported Function timestamp timezone: '-' is reserved for "
"no timezone"
)
if unit == "us" and timezone is None:
return {"type": "timestamp"}
return {"type": f"timestamp:{unit}:{timezone if timezone is not None else '-'}"}
if pa.types.is_duration(data_type):
unit = data_type.unit
if unit not in _FUNCTION_TIMEUNITS:
raise TypeError(f"unsupported Function duration unit: {unit!r}")
if unit == "us":
return {"type": "duration"}
return {"type": f"duration:{unit}"}
if pa.types.is_struct(data_type):
fields = list(data_type)
names = [field.name for field in fields]
@@ -1314,8 +1518,29 @@ def _exact_arrow_type(
if pa.types.is_fixed_size_list(data_type):
value["length"] = data_type.list_size
return value
if pa.types.is_map(data_type) and _data_type_has_blob_v2(data_type):
raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
if pa.types.is_map(data_type):
if data_type.keys_sorted:
raise TypeError(
"unsupported Arrow type for Function signature: map keys_sorted=true "
"is not supported"
)
key_field = data_type.key_field
if key_field.nullable or key_field.type != pa.string():
raise TypeError(
"unsupported Arrow type for Function signature: map keys must be "
"non-nullable utf8"
)
if _data_type_has_blob_v2(data_type):
raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
return {
"type": "map",
"fields": [
_exact_arrow_field(
data_type.field(0),
inside_collection=True,
)
],
}
raise TypeError(f"unsupported Arrow type for Function signature: {data_type}")
@@ -1344,9 +1569,15 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
raise TypeError(
"Annotated Function types require exactly one PyArrow DataType"
)
# A struct value is written as a dict, which has no Arrow type of its
# own; the Annotated metadata supplies it.
if base is dict or get_origin(base) is dict:
# A struct value is written as a dict, while Decimal and timedelta
# carry no precision or unit of their own; the Annotated metadata
# supplies those types.
if (
base is dict
or get_origin(base) is dict
or base is Decimal
or base is timedelta
):
base_nullable = False
else:
_, base_nullable = _annotation_type(base)
@@ -1372,7 +1603,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
if annotation is date:
return pa.date32(), nullable
if annotation is datetime:
# Existing default: microsecond precision, no timezone. Other units
# and timezones require Annotated or an explicit schema.
return pa.timestamp("us"), nullable
if annotation is Decimal:
raise TypeError(
"Decimal Function annotations require precision and scale; use "
"Annotated[Decimal, pyarrow.decimal128(precision, scale)], "
"Annotated[Decimal, pyarrow.decimal256(precision, scale)], or an "
"explicit schema"
)
if annotation is timedelta:
raise TypeError(
"timedelta Function annotations require an explicit unit; use "
"Annotated[timedelta, pyarrow.duration(unit)] or an explicit schema"
)
if get_origin(annotation) is list:
arguments = get_args(annotation)
if len(arguments) != 1:
@@ -1381,6 +1626,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
if value_nullable:
raise TypeError("nullable Function list elements are not supported")
return _list_of(value_type), nullable
if get_origin(annotation) is dict:
arguments = get_args(annotation)
if len(arguments) != 2:
raise TypeError(f"unsupported dict annotation: {annotation!r}")
key_type, value_annotation = arguments
if key_type is not str:
raise TypeError("Function map keys must be str")
value_type, value_nullable = _annotation_type(value_annotation)
return (
pa.map_(
pa.string(),
pa.field("value", value_type, nullable=value_nullable),
),
nullable,
)
raise TypeError(f"unsupported Function annotation: {annotation!r}")
@@ -2702,6 +2962,16 @@ def function(
the registration. Every named-struct field may be nullable; Enterprise
preserves the struct's validity when the result is expanded into sibling
columns.
``dict[str, T]`` declares an Arrow map with a non-nullable utf8 key; the
value is non-nullable for ``T`` and nullable for ``Optional[T]``. A bare
``Decimal`` has no precision or scale; use
``Annotated[Decimal, pyarrow.decimal128(precision, scale)]``,
``Annotated[Decimal, pyarrow.decimal256(precision, scale)]``, or an
explicit schema. Bare ``datetime`` keeps its existing ``timestamp[us]`` default
without a timezone; other units and timezones require
``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit
schema. A bare ``timedelta`` has no unit and is rejected; use
``Annotated[timedelta, pyarrow.duration(unit)]`` or an explicit schema.
**Large values.** A ``bytes`` parameter receives the whole value, which
is held in memory with its row and counts against the server's per-row
@@ -2808,8 +3078,12 @@ def function(
output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional
Explicit scalar or named-struct output. A scalar field's ``nullable``
flag is preserved; a top-level named-struct field and a Blob v2 output
must be non-nullable. Required for batch annotations. When omitted, the
output is inferred from the return annotation.
must be non-nullable. Map and decimal fields use canonical Arrow JSON;
a map key must be non-nullable utf8 and its value field keeps the
declared nullability. Temporal fields use canonical Arrow JSON; the
microsecond/no-timezone case keeps the legacy timestamp/duration shape.
Required for batch annotations. When omitted, the output is inferred
from the return annotation.
pip : sequence of str, optional
Pip requirements for the remote environment. Syntax is validated at
decoration time, including extras and environment markers. Named direct
@@ -3009,6 +3283,7 @@ __all__ = [
"FunctionArtifactContent",
"FunctionArtifactRequest",
"FunctionBinding",
"FunctionEnvironment",
"FunctionOutput",
"FunctionParameter",
"FunctionRegistrationRequest",
@@ -3025,6 +3300,9 @@ __all__ = [
"PythonEnvironmentSpec",
"PythonAdapterSpec",
"PythonRuntimeSpec",
"ResolvedEnvironment",
"ResolvedEnvironmentProvenance",
"ResolvedPackage",
"RefreshColumnResult",
"FunctionDefinition",
]
+68 -7
View File
@@ -4,8 +4,10 @@
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
import asyncio
import logging
import reprlib
import time
from contextlib import suppress
from datetime import timedelta
from os import PathLike
from pathlib import Path
@@ -53,11 +55,13 @@ def _timeout_message(
)
def _normalize_job_progress(progress):
def _normalize_job_progress(progress, *, query=False):
"""Normalize ``wait(progress=...)`` using the same convention as writes."""
if progress is True:
from tqdm.auto import tqdm
if query:
return tqdm(bar_format="Query{postfix} [{elapsed}]"), True
return tqdm(unit=" rows"), True
if progress is False or progress is None:
return None, False
@@ -65,6 +69,7 @@ def _normalize_job_progress(progress):
_ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000
_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0
def _progress_eta(previous, current):
@@ -203,6 +208,7 @@ class AsyncJob(Generic[T]):
self._inner = inner
self._result_decoder = result_decoder
self._last_progress_snapshot = None
self._created_at = time.monotonic()
def _enrich_progress(self, snapshot):
enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
@@ -235,17 +241,29 @@ class AsyncJob(Generic[T]):
async def progress(self) -> Optional[dict[str, Any]]:
"""Fetch a structured progress snapshot.
Registry jobs always report lifecycle fields. Queue metadata and
counters are included when supplied by the server. Older servers may
Registry jobs always report lifecycle fields. SQL query handles report
lifecycle state and ``client_elapsed_time_millis``, measured since this
handle was created. They do not expose server build phases or logs.
Queue metadata and counters are included when supplied by the server.
Older servers may
omit counters, and in-process operations return ``None``. A missing
counter is unknown rather than zero. This is additive to :meth:`status`,
whose string contract is unchanged.
"""
if self._inner is None:
return None
await self._inner.status()
state = await self._inner.status()
description = getattr(self._inner, "_description", None)
if description is None or description.progress is None:
if self.job_type == "query":
return {
"job_id": self.id,
"job_type": "query",
"state": state,
"client_elapsed_time_millis": int(
(time.monotonic() - self._created_at) * 1_000
),
}
return None
return self._enrich_progress(description.progress)
@@ -270,6 +288,13 @@ class AsyncJob(Generic[T]):
new execution epoch or smaller plan resets the bar to that plan.
``False`` preserves the original wait behavior.
For SQL-backed Function registration, progress shows the query's
lifecycle state and client elapsed time. It observes the existing
query handle while its original waiter runs; it does not resubmit or
cancel the registration. Detailed bake phases and build logs are not
available from the current query handle. Failure exceptions retain the
server's cause and request identifiers.
Raises `JobFailedError` if the operation failed, `JobCancelledError`
if it was cancelled, and `TimeoutError` if `timeout` elapses first.
Transient connection and read errors are retried with capped exponential
@@ -285,7 +310,10 @@ class AsyncJob(Generic[T]):
"""
if self._inner is None:
return cast(T, None)
progress_obj, owns = _normalize_job_progress(progress)
query_progress = (
progress is not False and progress is not None and self.job_type == "query"
)
progress_obj, owns = _normalize_job_progress(progress, query=query_progress)
progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
last_error = None
@@ -311,13 +339,46 @@ class AsyncJob(Generic[T]):
await asyncio.sleep(delay)
delay = min(delay * 2, 30.0)
async def observe_query():
async def report():
try:
snapshot = await self.progress()
if snapshot is not None:
progress_callback(snapshot)
except Exception:
logging.getLogger(__name__).warning(
"job progress observer failed", exc_info=True
)
waiter = asyncio.create_task(wait_with_retries())
try:
while not waiter.done():
await report()
await asyncio.wait(
{waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS
)
try:
return await waiter
finally:
await report()
finally:
if not waiter.done():
waiter.cancel()
with suppress(asyncio.CancelledError):
await waiter
wait_for_result = (
observe_query
if query_progress and progress_callback is not None
else wait_with_retries
)
try:
try:
if timeout is None:
result = await wait_with_retries()
result = await wait_for_result()
else:
result = await asyncio.wait_for(
wait_with_retries(), timeout.total_seconds()
wait_for_result(), timeout.total_seconds()
)
except asyncio.TimeoutError as error:
if last_error is None:
+70 -2
View File
@@ -6,7 +6,19 @@
from __future__ import annotations
import asyncio
from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
from collections import deque
from itertools import islice
from operator import index
from typing import (
Any,
AsyncIterator,
Callable,
Generic,
Iterator,
Optional,
TypeVar,
overload,
)
from .background_loop import LOOP
@@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]):
print(name)
Use ``list(connection.list_views())`` to collect all results.
Indexes and slices refer to the remaining items and do not consume them.
A bounded forward slice, such as ``listing[:5]``, fetches only enough pages
to reach its stop. ``len(listing)``, negative indexes, and open-ended or
reverse slices fetch and cache all remaining results. Iteration then drains
that cache. These operations may perform requests and raise request errors.
"""
def __init__(self, inner: AsyncListing[T]):
self._inner = inner
self._buffer: deque[T] = deque()
def __iter__(self) -> Listing[T]:
return self
def __next__(self) -> T:
if self._buffer:
return self._buffer.popleft()
try:
return LOOP.run(self._inner.__anext__())
except StopAsyncIteration:
raise StopIteration from None
def _fill(self, count: Optional[int]) -> None:
while count is None or len(self._buffer) < count:
try:
item = LOOP.run(self._inner.__anext__())
except StopAsyncIteration:
return
self._buffer.append(item)
def __len__(self) -> int:
"""Fetch and cache every remaining item, returning the remaining count."""
self._fill(None)
return len(self._buffer)
def __bool__(self) -> bool:
self._fill(1)
return bool(self._buffer)
@overload
def __getitem__(self, key: int) -> T: ...
@overload
def __getitem__(self, key: slice) -> list[T]: ...
def __getitem__(self, key: int | slice) -> T | list[T]:
"""Read remaining items without consuming them; bounded slices stay lazy."""
if isinstance(key, slice):
start = 0 if key.start is None else index(key.start)
stop = None if key.stop is None else index(key.stop)
step = 1 if key.step is None else index(key.step)
if step == 0:
raise ValueError("slice step cannot be zero")
if start >= 0 and stop is not None and stop >= 0 and step > 0:
if start >= stop:
return []
self._fill(stop)
start, stop, step = key.indices(len(self._buffer))
return list(
islice(self._buffer, start, stop, min(step, len(self._buffer) + 1))
)
self._fill(None)
return list(self._buffer)[key]
position = index(key)
self._fill(None if position < 0 else position + 1)
return self._buffer[position]
def num_page_results(self) -> int:
"""Return the number of cached items available without another request."""
return self._inner.num_page_results()
return len(self._buffer) + self._inner.num_page_results()
def page_token(self) -> Optional[str]:
"""Return the next request's token.
See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token]
for initial, cached, final-page, and error behavior.
Indexing, slicing, and counting can also advance this token; drain all
``num_page_results()`` cached items before resuming from it.
"""
return self._inner.page_token()
+21 -2
View File
@@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object):
on_bad_vectors: str = "error",
fill_value: float = 0.0,
timeout: Optional[timedelta] = None,
*,
retries: Optional[int] = None,
) -> MergeInsertResult:
"""
Executes the merge insert operation
@@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object):
first attempt will not be cancelled.
When this is set, the timeout is enforced on all attempts, including
the first.
the first. For remote tables it is sent as a server execution timeout;
it does not extend HTTP read or proxy idle timeouts, or prove that a
failed request did not commit.
retries: int, optional
Override the remote retry budget for this execution only (0 to 255).
Use ``execute(new_data, retries=0)`` to disable even retries after
precommit conflicts (409) or rate limits (429). This does not change
connection-wide/read budgets or local transaction conflict retries.
By default, remote calls use the connection's
[RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set
through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within
the retry budget; it never permits replay of ambiguous merge outcomes.
In particular, 502, ordinary 503, and 504 are never replayed, even if
configured. Reconcile table contents before manually repeating a merge
whose commit outcome is unknown.
Returns
-------
@@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object):
"""
if timeout is not None:
self._timeout = timeout
return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
return self._table._do_merge(
self, new_data, on_bad_vectors, fill_value, retries=retries
)
+25
View File
@@ -10,6 +10,7 @@ through a namespace abstraction.
from __future__ import annotations
import json
import sys
import warnings
from typing import Any, Dict, Iterable, List, Optional, Union
@@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import (
QueryTableRequestVector,
)
from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery
from lance_namespace_urllib3_client.models.structured_fts_query import (
StructuredFtsQuery,
)
from lance_namespace.errors import (
NamespaceNotEmptyError,
NamespaceNotFoundError,
@@ -78,6 +82,7 @@ from lancedb.materialized_view import (
SelectArg,
)
from lancedb.table import AsyncTable, LanceTable, Table
from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery
from lancedb.util import validate_table_name
from lancedb.common import DATA
from lancedb.pydantic import LanceModel
@@ -178,6 +183,26 @@ def _query_to_namespace_request(
full_text_query_request = QueryTableRequestFullTextQuery(
string_query=StringFtsQuery(query=fts_query)
)
elif getattr(fts_query, "operator", None) is not None:
columns = fts_query.columns or []
text = fts_query.query
if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
if len(columns) > 1:
raise ValueError(
"Phrase queries cannot be used with multiple columns."
)
structured = PhraseQuery(text[1:-1], columns[0] if columns else None)
elif len(columns) > 1:
structured = MultiMatchQuery(text, columns, operator=fts_query.operator)
else:
structured = MatchQuery(
text, columns[0] if columns else None, operator=fts_query.operator
)
full_text_query_request = QueryTableRequestFullTextQuery(
structured_query=StructuredFtsQuery.from_dict(
{"query": json.loads(structured.to_json())}
)
)
elif hasattr(fts_query, "query"):
full_text_query_request = QueryTableRequestFullTextQuery(
string_query=StringFtsQuery(
+116 -11
View File
@@ -42,7 +42,7 @@ from .rerankers.base import Reranker
from .rerankers.rrf import RRFReranker
from .rerankers.util import check_reranker_result
from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
from .util import _validate_query_vector, flatten_columns, get_uri_scheme
from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme
from . import _wal_hybrid # WAL-PK-FUSION: delete.
from ._blob import (
BLOB_MODE_TO_HANDLING,
@@ -873,10 +873,29 @@ class FullTextSearchQuery(pydantic.BaseModel):
query: str | FullTextQuery
If a string, it is treated as a MatchQuery.
If a FullTextQuery object, it is used directly.
operator: FullTextOperator, optional
Combine terms in a string query using AND or OR (the default).
Quoted strings keep phrase semantics regardless of the operator.
"""
columns: Optional[List[str]] = None
query: Union[str, FullTextQuery]
operator: Optional[FullTextOperator] = None
@pydantic.model_validator(mode="after")
def _validate_operator(self) -> Self:
if self.operator is not None and not isinstance(self.query, str):
raise ValueError("operator requires a string full-text query")
return self
def _add_fts_position_error_note(error: Exception) -> None:
if "position is not found but required for phrase queries" in str(error):
add_note(
error,
"Phrase queries require an index built with positions. Rebuild it with "
"table.create_index(column, config=FTS(with_position=True), replace=True).",
)
class Query(pydantic.BaseModel):
@@ -1147,6 +1166,7 @@ class LanceQueryBuilder(ABC):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: bool = None,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> Self:
"""
Create a query builder based on the given query and query type.
@@ -1171,6 +1191,10 @@ class LanceQueryBuilder(ABC):
fast_search: bool
Skip flat search of unindexed data.
"""
if operator is not None:
operator = FullTextOperator(operator)
if not isinstance(query, str) or query_type not in ("auto", "fts"):
raise ValueError("operator requires a string full-text query")
if query_type != "fts":
_validate_query_vector(query)
@@ -1201,6 +1225,9 @@ class LanceQueryBuilder(ABC):
table, query, query_type, vector_column_name
)
if operator is not None and query_type != "fts":
raise ValueError("operator requires a string full-text query")
if query_type == "hybrid":
return LanceHybridQueryBuilder(
table, query, vector_column_name, fts_columns=fts_columns
@@ -1214,7 +1241,7 @@ class LanceQueryBuilder(ABC):
ordering_field_name=ordering_field_name,
fts_columns=fts_columns,
fast_search=fast_search,
)
).operator(operator)
if isinstance(query, (list, tuple)):
query = np.array(query, dtype=np.float32)
@@ -2563,6 +2590,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
super().__init__(table)
self._query = query
self._phrase_query = False
self._operator: Optional[FullTextOperator] = None
# Deprecated compatibility parameter. Native FTS ordering is now
# configured through order_by(); LanceQueryBuilder.create emits the warning.
_ = ordering_field_name
@@ -2572,6 +2600,36 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
fts_columns = [fts_columns]
self._fts_columns = fts_columns
def operator(
self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]]
) -> LanceFtsQueryBuilder:
"""Combine terms in a string query with ``"AND"`` or ``"OR"``.
The default is OR. AND requires every term to match. For example,
``table.search("gripper closed", query_type="fts").operator("AND")``.
Structured queries specify their own operators. Quoted strings and
``phrase_query()`` retain their phrase semantics.
"""
if operator is not None and not isinstance(self._query, str):
raise ValueError("operator requires a string full-text query")
self._operator = FullTextOperator(operator) if operator is not None else None
return self
def count_rows(self) -> int:
"""Count all full-text matches satisfying the query's filter.
Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
still restricts the count to indexed data. This streams matching scores
without loading document columns and may scan every match.
For example, ``table.search("gripper closed", query_type="fts",``
``operator="AND").where("active = true").count_rows()``.
"""
self._table._ensure_no_legacy_fts_index()
query = self._table._table._sync_query_to_async(self.to_query_object())
assert isinstance(query, AsyncFTSQuery)
return LOOP.run(query.count_rows())
def phrase_query(self, phrase_query: bool = True) -> LanceFtsQueryBuilder:
"""Set whether to use phrase query.
@@ -2628,7 +2686,9 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
fragment_ids=self._fragment_ids,
use_rte=self._use_rte,
full_text_query=FullTextSearchQuery(
query=self._query_with_phrase_semantics(), columns=self._fts_columns
query=self._query_with_phrase_semantics(),
columns=self._fts_columns,
operator=self._operator,
),
offset=self._offset,
fast_search=self._fast_search,
@@ -4443,7 +4503,11 @@ class AsyncQuery(AsyncStandardQuery):
)
def nearest_to_text(
self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
self,
query: str | FullTextQuery,
columns: Union[str, List[str], None] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncFTSQuery:
"""
Find the documents that are most relevant to the given text query.
@@ -4464,7 +4528,11 @@ class AsyncQuery(AsyncStandardQuery):
columns: str or list of str, default None
The columns to search in. If None, all indexed columns are searched.
For now only one column can be searched at a time.
operator: "AND" or "OR", optional
Combine terms in a string query. Defaults to OR. Quoted strings use
phrase semantics and require an index built with positions.
"""
fts_query = FullTextSearchQuery(query=query, operator=operator)
if isinstance(columns, str):
columns = [columns]
if columns is None:
@@ -4472,7 +4540,13 @@ class AsyncQuery(AsyncStandardQuery):
if isinstance(query, str):
return AsyncFTSQuery(
self._inner.nearest_to_text({"query": query, "columns": columns}),
self._inner.nearest_to_text(
{
"query": query,
"columns": columns,
"operator": fts_query.operator,
}
),
self._table,
)
# FullTextQuery object
@@ -4487,6 +4561,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
self._inner = inner
self._reranker = None
async def count_rows(self) -> int:
"""Count all full-text matches satisfying the query's filter.
Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
still restricts the count to indexed data. Matching scores are streamed
without loading document columns, so counting may scan every match.
For example, ``await table.query().nearest_to_text("gripper closed",``
``operator="AND").where("active = true").count_rows()``.
"""
try:
return await self._inner.count_rows()
except Exception as error:
_add_fts_position_error_note(error)
raise
def get_query(self) -> str:
return self._inner.get_query()
@@ -4580,10 +4670,16 @@ class AsyncFTSQuery(AsyncStandardQuery):
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
try:
reader = await super()._execute_batches(
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
except Exception as error:
_add_fts_position_error_note(error)
raise
if self._reranker:
source = results
results = self._reranker.rerank_fts(self.get_query(), results)
@@ -4861,7 +4957,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return self
def nearest_to_text(
self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
self,
query: str | FullTextQuery,
columns: Union[str, List[str], None] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncHybridQuery:
"""
Find the documents that are most relevant to the given text query,
@@ -4886,7 +4986,10 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
columns: str or list of str, default None
The columns to search in. If None, all indexed columns are searched.
For now only one column can be searched at a time.
operator: "AND" or "OR", optional
Combine terms in a string query. Defaults to OR.
"""
fts_query = FullTextSearchQuery(query=query, operator=operator)
if isinstance(columns, str):
columns = [columns]
if columns is None:
@@ -4894,7 +4997,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
if isinstance(query, str):
return AsyncHybridQuery(
self._inner.nearest_to_text({"query": query, "columns": columns}),
self._inner.nearest_to_text(
{"query": query, "columns": columns, "operator": fts_query.operator}
),
self._table,
)
# FullTextQuery object
+44 -6
View File
@@ -1002,6 +1002,7 @@ class RemoteDBConnection(DBConnection):
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
refresh_lock: bool = False,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
@@ -1009,6 +1010,7 @@ class RemoteDBConnection(DBConnection):
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
refresh_lock=refresh_lock,
)
)
return Job(job)
@@ -1322,16 +1324,52 @@ class RemoteDBConnection(DBConnection):
@override
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> Listing[JobInfo]:
"""List server-side jobs across the database's tables.
"""List server-side jobs, optionally filtered before pagination.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
``page_token`` resumes from a saved token. Requests and errors occur during
iteration. See [pagination state][lancedb.listing.AsyncListing].
``table`` names a table in ``namespace_path`` (the root by default).
Listings include all branches of the table. A namespace filter requires
``table``.
``state`` uses registry states such as ``in_progress``, ``succeeded``,
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
Creation-time bounds are Unix milliseconds, inclusive at
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
Resume a ``page_token`` with the same filters. Requests and errors occur
during iteration. See [pagination state][lancedb.listing.AsyncListing].
For example, to inspect up to five jobs without fetching all history::
jobs = db.list_jobs(table="events", page_limit=5)
first_five = jobs[:5]
"""
return Listing(
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
self._conn.list_jobs(
page_token=page_token,
page_limit=page_limit,
table=table,
namespace_path=namespace_path,
state=state,
job_type=job_type,
job_types=job_types,
created_at_gte_millis=created_at_gte_millis,
created_at_lt_millis=created_at_lt_millis,
)
)
@override
+10 -1
View File
@@ -65,6 +65,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry
from lancedb.table import _normalize_progress
from ..query import (
FullTextOperator,
AnalyzePlanDistributedMetrics,
DocumentGranularity,
FullTextQuery,
@@ -799,6 +800,8 @@ class RemoteTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceQueryBuilder:
"""Create a search query to find the nearest neighbors
of the given query vector. We currently support
@@ -857,6 +860,10 @@ class RemoteTable(Table):
- *default None*, which leaves fast search disabled.
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
LanceQueryBuilder
@@ -893,6 +900,7 @@ class RemoteTable(Table):
ordering_field_name=ordering_field_name,
fts_columns=fts_columns or [],
fast_search=fast_search,
operator=operator,
)
def _execute_query(
@@ -945,9 +953,10 @@ class RemoteTable(Table):
new_data: DATA,
on_bad_vectors: str,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult:
return LOOP.run(
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
)
@_deprecated_keyword("predicate", "where")
+62 -3
View File
@@ -91,6 +91,7 @@ from .functions import (
from .merge import LanceMergeInsertBuilder
from .pydantic import LanceModel, model_to_dict
from .query import (
FullTextOperator,
AnalyzePlanDistributedMetrics,
AsyncFTSQuery,
AsyncHybridQuery,
@@ -138,6 +139,11 @@ def _requires_local_namespace_execution(query: Query) -> bool:
or query.take_row_ids is not None
or query.search_effort is not None
or query.approx_mode is not None
or (
query.full_text_query is not None
and query.fast_search is True
and query.vector is None
)
)
@@ -2443,6 +2449,8 @@ class Table(ABC):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceQueryBuilder:
"""Create a search query to find the nearest neighbors
of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
@@ -2506,6 +2514,10 @@ class Table(ABC):
- If `query` is a string, then the query type is "vector" if the
table has embedding functions else the query type is "fts"
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
LanceQueryBuilder
@@ -2810,6 +2822,7 @@ class Table(ABC):
new_data: DATA,
on_bad_vectors: OnBadVectorsType,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult: ...
@abstractmethod
@@ -5060,6 +5073,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceVectorQueryBuilder: ...
@overload
@@ -5071,6 +5086,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceFtsQueryBuilder: ...
@overload
@@ -5084,6 +5101,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceHybridQueryBuilder: ...
@overload
@@ -5095,6 +5114,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceEmptyQueryBuilder: ...
def search(
@@ -5107,6 +5128,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceQueryBuilder:
"""Create a search query to find the nearest neighbors
of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
@@ -5167,6 +5190,10 @@ class LanceTable(Table):
If None then the search is performed on all indexed columns.
For now, only one column can be searched at a time.
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
LanceQueryBuilder
@@ -5192,6 +5219,7 @@ class LanceTable(Table):
ordering_field_name=ordering_field_name,
fts_columns=fts_columns or [],
fast_search=fast_search,
operator=operator,
)
@classmethod
@@ -5443,9 +5471,10 @@ class LanceTable(Table):
new_data: DATA,
on_bad_vectors: OnBadVectorsType,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult:
return LOOP.run(
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
)
@property
@@ -7374,6 +7403,8 @@ class AsyncTable:
query_type: QueryType = "auto",
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncQuery: ...
@overload
@@ -7384,6 +7415,8 @@ class AsyncTable:
query_type: Literal["auto"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> Union[AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: ...
@overload
@@ -7394,6 +7427,8 @@ class AsyncTable:
query_type: Literal["hybrid"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncHybridQuery: ...
@overload
@@ -7404,6 +7439,8 @@ class AsyncTable:
query_type: Literal["auto"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncVectorQuery: ...
@overload
@@ -7414,6 +7451,8 @@ class AsyncTable:
query_type: Literal["fts"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncFTSQuery: ...
@overload
@@ -7424,6 +7463,8 @@ class AsyncTable:
query_type: Literal["vector"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncVectorQuery: ...
async def search(
@@ -7435,6 +7476,8 @@ class AsyncTable:
query_type: QueryType = "auto",
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> Union[AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]:
"""Create a search query to find the nearest neighbors
of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
@@ -7478,12 +7521,20 @@ class AsyncTable:
- If `query` is a string, then the query type is "vector" if the
table has embedding functions else the query type is "fts"
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, or AsyncVectorQuery
A query builder object representing the query.
"""
if operator is not None:
operator = FullTextOperator(operator)
if not isinstance(query, str) or query_type not in ("auto", "fts"):
raise ValueError("operator requires a string full-text query")
if query is None:
return self.query()
@@ -7602,13 +7653,17 @@ class AsyncTable:
)
vector_query = await make_embedding(embedding_conf, query)
if operator is not None and query_type != "fts":
raise ValueError("operator requires a string full-text query")
if query_type == "vector":
builder = self.query().nearest_to(vector_query)
if vector_column_name:
builder = builder.column(vector_column_name)
return builder
elif query_type == "fts":
return self.query().nearest_to_text(query, columns=fts_columns)
return self.query().nearest_to_text(
query, columns=fts_columns, operator=operator
)
elif query_type == "hybrid":
builder = self.query().nearest_to(vector_query)
if vector_column_name:
@@ -7718,7 +7773,9 @@ class AsyncTable:
if query.full_text_query:
async_query = async_query.nearest_to_text(
query.full_text_query.query, query.full_text_query.columns
query.full_text_query.query,
query.full_text_query.columns,
operator=query.full_text_query.operator,
)
return async_query
@@ -7777,6 +7834,7 @@ class AsyncTable:
new_data: DATA,
on_bad_vectors: OnBadVectorsType,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult:
schema = await self.schema()
if on_bad_vectors is None:
@@ -7808,6 +7866,7 @@ class AsyncTable:
use_rte=merge._use_rte,
validate_single_shard=merge._validate_single_shard,
),
retries=retries,
)
async def delete(self, where: Union[str, Expr]) -> DeleteResult:
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import warnings
from collections import UserDict
from pathlib import Path
from types import MappingProxyType
@@ -13,6 +14,7 @@ import lancedb.functions as functions
from lancedb.functions import (
FunctionApplication,
FunctionBinding,
FunctionImage,
FunctionVersion,
PythonRuntimeSpec,
SecretBinding,
@@ -149,6 +151,59 @@ def test_function_version_identity_is_immutable_and_exact():
FunctionVersion(**{**value, "version": invalid})
@pytest.mark.parametrize("gpu", [False, True])
def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
value = job_result("remote_function_job.json")["image"]
value["descriptor"]["future_metadata"] = "x" * 100_000
if gpu:
value["descriptor"]["requires"]["capabilities"] = [
{
"type": "lance.cuda",
"version": 1,
"device_count": 1,
"cuda_toolkit": "12.4",
}
]
image = FunctionImage(**value)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
details = image.describe()
rendered = repr(image)
assert "manifest_digest=" in str(image)
encoded = json.loads(image.to_canonical_json())
assert details == {
"manifest_digest": value["manifest_digest"],
"python_version": "3.12.14",
"requires_gpu": gpu,
"cuda_toolkit": "12.4" if gpu else None,
"platforms": None,
"base_image": None,
"size_bytes": None,
}
assert len(rendered) < 350
assert f"requires_gpu={gpu}" in rendered
assert "future_metadata" not in rendered
assert encoded == value
@pytest.mark.parametrize(
"descriptor",
[
{},
{"format_version": 2, "requires": {"capabilities": []}},
{"format_version": 1, "requires": {"capabilities": [None]}},
{"python": {"version": {"future": "x" * 100_000}}},
],
)
def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
image = FunctionImage(
manifest_digest="sha256:example", descriptor=descriptor, source=True
)
assert image.describe()["requires_gpu"] is None
assert image.describe()["python_version"] is None
assert len(repr(image)) < 350
@pytest.mark.parametrize(
"case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
)
@@ -9,7 +9,7 @@ import functools
import importlib.util
import inspect
import types
from datetime import date
from datetime import date, datetime, timedelta
import http.server
import json
import os
@@ -19,15 +19,17 @@ import sys
import typing
import urllib.parse
import warnings
from typing import Optional
from decimal import Decimal
from typing import Annotated, Optional
import pyarrow as pa
import pytest
import lancedb
from lancedb import BlobReader
from lancedb.db import AsyncConnection
from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection
from lancedb.functions import (
FunctionRegistrationRequest,
FunctionSignature,
FunctionVersion,
HuggingFaceModel,
@@ -82,6 +84,63 @@ def analyze_caption(caption: str) -> str:
return caption.strip()
def _function_version_with_resolved_environment():
version = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
version["runtime"] = json.loads(
normalize_score.registration_request.runtime.to_canonical_json()
)
version["resolved_environment"] = {
"packages": [
{
"name": "torch",
"version": "2.9.0+cu130",
"source": "https://packages.example/simple",
},
{"name": "transformers", "version": "4.57.1"},
],
"provenance": {
"configured_index_urls": ["https://packages.example/simple"],
"configured_find_links": ["https://downloads.example/wheels"],
"resolved_indexes": ["https://packages.example/simple"],
"cuda_toolkit": "12.8",
"torch_version": "torch==2.9.0+cu130",
},
"warnings": [
"transformers resolved to transformers==4.57.1 but is not pinned "
"exactly; add transformers==4.57.1 to pin it."
],
}
return version
def _function_version_with_resolved_environments():
version = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
version["runtime"] = json.loads(
normalize_score.registration_request.runtime.to_canonical_json()
)
version["resolved_environments"] = {
"linux/amd64": {
"packages": [
{
"name": "torch",
"version": "2.9.0+cu130",
"source": "https://packages.example/simple",
}
],
"warnings": ["amd64 environment warning"],
},
"linux/arm64": {
"packages": [],
"warnings": ["arm64 environment warning"],
},
}
return version
def test_scalar_function_matches_shared_registration_golden_and_remains_callable():
assert isinstance(normalize_score, FunctionDefinition)
assert normalize_score(25.0) == 0.25
@@ -98,6 +157,118 @@ def test_scalar_function_matches_shared_registration_golden_and_remains_callable
}
def test_refresh_lock_is_a_registration_option_not_part_of_identity():
default = normalize_score.registration_request
old_json = default.to_canonical_json()
assert "refresh_lock" not in json.loads(old_json)
refreshed = default.with_refresh_lock(True)
payload = json.loads(refreshed.to_canonical_json())
assert payload["refresh_lock"] is True
assert (
FunctionRegistrationRequest.from_json(
refreshed.to_canonical_json()
).refresh_lock
is True
)
assert refreshed.artifact.digest == default.artifact.digest
assert refreshed.runtime.digest == default.runtime.digest
assert default.with_refresh_lock(False).to_canonical_json() == old_json
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
default.with_refresh_lock(1)
@pytest.mark.asyncio
@pytest.mark.parametrize("exist_ok", [False, True])
async def test_async_create_function_forwards_refresh_lock(exist_ok):
calls = []
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
calls.append((json.loads(request_json), namespace_path, exist_ok))
return object()
connection = object.__new__(AsyncConnection)
connection._inner = Inner()
await connection.create_function_async(normalize_score)
await connection.create_function_async(
normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"]
)
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
await connection.create_function_async(normalize_score, refresh_lock=1)
assert len(calls) == 2
assert "refresh_lock" not in calls[0][0]
assert calls[0][1:] == (None, False)
assert calls[1][0]["refresh_lock"] is True
assert calls[1][1:] == (["team"], exist_ok)
@pytest.mark.parametrize("exist_ok", [False, True])
def test_sync_create_function_paths_forward_refresh_lock(exist_ok):
calls = []
class AsyncInner:
async def create_function_async(
self,
definition,
*,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=False,
):
calls.append(("wrapped", refresh_lock, namespace_path, exist_ok))
return object()
for connection_type in (LanceDBConnection, RemoteDBConnection):
connection = object.__new__(connection_type)
connection._conn = AsyncInner()
connection.create_function_async(
normalize_score,
refresh_lock=True,
exist_ok=exist_ok,
namespace_path=["team"],
)
class BlockingConnection:
def create_function_async(
self,
definition,
*,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=False,
):
calls.append(("blocking", refresh_lock, namespace_path, exist_ok))
class ImmediateJob:
def wait(self):
return "version"
return ImmediateJob()
blocking = BlockingConnection()
assert (
DBConnection.create_function(
blocking,
normalize_score,
refresh_lock=True,
exist_ok=exist_ok,
namespace_path=["team"],
)
== "version"
)
assert calls == [
("wrapped", True, ["team"], exist_ok),
("wrapped", True, ["team"], exist_ok),
("blocking", True, ["team"], exist_ok),
]
def test_function_declares_pinned_hugging_face_models():
model = HuggingFaceModel(
repo="sentence-transformers/all-MiniLM-L6-v2",
@@ -884,12 +1055,10 @@ def test_canonical_arrow_type_prefers_the_compact_grammar():
== "large_list<float32>"
)
for outside in [
pa.timestamp("us"),
pa.decimal128(10, 2),
pa.binary(4),
pa.duration("s"),
pa.time32("s"),
pa.time64("us"),
pa.list_(pa.float32(), 0),
pa.list_(pa.timestamp("us")),
]:
with pytest.raises(TypeError, match="unsupported Arrow type"):
_canonical_arrow_type(outside)
@@ -1215,6 +1384,304 @@ def test_explicit_arrow_schema_is_deterministic():
assert signature.output.nullable is False
def test_timestamp_annotation_and_explicit_schema_serialization():
for unit in ("s", "ms", "us", "ns"):
for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"):
encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone)))
if unit == "us" and timezone is None:
assert encoded == {"type": "timestamp"}
else:
suffix = timezone if timezone is not None else "-"
assert encoded == {"type": f"timestamp:{unit}:{suffix}"}
with pytest.raises(TypeError, match="reserved for no timezone"):
_canonical_arrow_type(pa.timestamp("us", tz="-"))
@function
def normalize(
ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
return ts
signature = normalize.registration_request.signature
assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"}
assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"}
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
@function
def optional_timestamp(
ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]],
) -> int:
return 0
optional_input = optional_timestamp.registration_request.signature.inputs[0]
assert optional_input.nullable is True
assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"}
@function
def legacy(ts: datetime) -> datetime:
return ts
legacy_signature = legacy.registration_request.signature
assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"}
assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"}
legacy_round_trip = FunctionSignature.from_json(
legacy_signature.to_canonical_json()
)
assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}'
input_schema = pa.schema(
[pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)]
)
output_schema = pa.schema(
[
pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True),
pa.field("elapsed", pa.duration("ms"), nullable=False),
]
)
@function(input_schema=input_schema, output_schema=output_schema)
def nested(ts):
return {"ts": ts, "elapsed": None}
nested_signature = nested.registration_request.signature
assert nested_signature.inputs[0].nullable is True
assert json.loads(nested_signature.inputs[0].arrow_type) == {
"type": "timestamp:ms:America/New_York"
}
assert nested_signature.output.kind == "named_struct"
assert nested_signature.output.fields[0].nullable is True
assert json.loads(nested_signature.output.fields[0].arrow_type) == {
"type": "timestamp:ns:+08:00"
}
assert json.loads(nested_signature.output.fields[1].arrow_type) == {
"type": "duration:ms"
}
list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False))
assert json.loads(_canonical_arrow_type(list_type)) == {
"type": "list",
"fields": [
{
"name": "item",
"nullable": False,
"type": {"type": "timestamp:ms:UTC"},
}
],
}
def test_duration_annotation_and_explicit_schema_serialization():
for unit in ("s", "ms", "us", "ns"):
encoded = json.loads(_canonical_arrow_type(pa.duration(unit)))
expected = (
{"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"}
)
assert encoded == expected
@function
def elapsed(
value: Annotated[timedelta, pa.duration("s")],
) -> Annotated[timedelta, pa.duration("ns")]:
return value
signature = elapsed.registration_request.signature
assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"}
assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"}
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
@function
def optional_elapsed(
value: Optional[Annotated[timedelta, pa.duration("ms")]],
) -> int:
return 0
optional_input = optional_elapsed.registration_request.signature.inputs[0]
assert optional_input.nullable is True
assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"}
with pytest.raises(
TypeError, match="timedelta Function annotations require an explicit unit"
):
@function
def missing(value: timedelta) -> timedelta:
return value
input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)])
output_schema = pa.field("result", pa.duration("us"), nullable=False)
@function(input_schema=input_schema, output_schema=output_schema)
def explicit(elapsed: timedelta) -> timedelta:
return elapsed
explicit_signature = explicit.registration_request.signature
assert explicit_signature.inputs[0].nullable is True
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
"type": "duration:ms"
}
assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"}
explicit_round_trip = FunctionSignature.from_json(
explicit_signature.to_canonical_json()
)
assert explicit_round_trip.output.arrow_type == '{"type":"duration"}'
def test_map_annotation_and_explicit_schema_serialization():
@function
def map_round_trip(values: dict[str, int]) -> dict[str, int]:
return values
signature = map_round_trip.registration_request.signature
expected = {
"type": "map",
"fields": [
{
"name": "entries",
"nullable": False,
"type": {
"type": "struct",
"fields": [
{
"name": "key",
"nullable": False,
"type": {"type": "utf8"},
},
{
"name": "value",
"nullable": False,
"type": {"type": "int64"},
},
],
},
}
],
}
assert json.loads(signature.inputs[0].arrow_type) == expected
assert json.loads(signature.output.arrow_type) == expected
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
@function
def nullable_values(
values: dict[str, Optional[int]],
) -> dict[str, Optional[int]]:
return values
nullable_signature = nullable_values.registration_request.signature
nullable_map = json.loads(nullable_signature.inputs[0].arrow_type)
assert nullable_map["fields"][0]["type"]["fields"][1] == {
"name": "value",
"nullable": True,
"type": {"type": "int64"},
}
input_schema = pa.schema(
[
pa.field(
"values",
pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)),
nullable=False,
)
]
)
output_schema = pa.field(
"result",
pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)),
nullable=False,
)
@function(input_schema=input_schema, output_schema=output_schema)
def explicit(values):
return {}
explicit_signature = explicit.registration_request.signature
explicit_input = json.loads(explicit_signature.inputs[0].arrow_type)
assert explicit_input["fields"][0]["type"]["fields"][1] == {
"name": "custom",
"nullable": True,
"type": {"type": "int64"},
}
explicit_output = json.loads(explicit_signature.output.arrow_type)
assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False
def test_map_rejects_unsupported_boundaries():
with pytest.raises(TypeError, match="map keys_sorted=true"):
_canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True))
with pytest.raises(TypeError, match="map keys must be non-nullable utf8"):
_canonical_arrow_type(pa.map_(pa.int64(), pa.int64()))
with pytest.raises(TypeError, match="Blob v2 fields nested under"):
_canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type))
with pytest.raises(TypeError, match="map keys must be str"):
@function
def invalid_keys(values: dict[int, int]) -> int:
return 0
def test_decimal_annotation_and_explicit_schema_serialization():
@function
def price(
amount: Annotated[Decimal, pa.decimal128(10, 2)],
) -> Annotated[Decimal, pa.decimal256(50, 4)]:
return Decimal("1.0000")
signature = price.registration_request.signature
assert json.loads(signature.inputs[0].arrow_type) == {
"type": "decimal128",
"length": 10002,
}
assert json.loads(signature.output.arrow_type) == {
"type": "decimal256",
"length": 50004,
}
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == {
"type": "decimal128",
"length": 9998,
}
decimal_map = json.loads(
_canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2)))
)
assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == {
"type": "decimal128",
"length": 10002,
}
input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)])
output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False)
@function(input_schema=input_schema, output_schema=output_schema)
def explicit(amount: Decimal) -> Decimal:
return amount
explicit_signature = explicit.registration_request.signature
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
"type": "decimal128",
"length": 12002,
}
assert json.loads(explicit_signature.output.arrow_type) == {
"type": "decimal256",
"length": 60006,
}
with pytest.raises(
TypeError, match="Decimal Function annotations require precision and scale"
):
@function
def missing(amount: Decimal) -> Decimal:
return amount
def test_nullable_scalar_output_annotation_and_explicit_schema():
input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
@@ -2059,6 +2526,205 @@ class _RawFunctionCatalog:
return None
def test_function_version_reads_requested_and_resolved_environments():
legacy = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
assert legacy_version.runtime is None
assert legacy_version.resolved_environment is None
assert legacy_version.environment.requested is None
assert legacy_version.environment.resolved is None
payload = _function_version_with_resolved_environment()
version = FunctionVersion.from_json(json.dumps(payload))
assert version.environment.requested is version.runtime
assert version.environment.resolved is version.resolved_environment
assert version.runtime.kind == "python"
resolved = version.resolved_environment
assert resolved.packages[0].version == "2.9.0+cu130"
assert resolved.packages[0].source == "https://packages.example/simple"
assert resolved.packages[1].source is None
assert resolved.provenance.torch_version == "torch==2.9.0+cu130"
assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"])
encoded = json.loads(version.to_canonical_json())
assert encoded["runtime"]["kind"] == "python"
assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130"
assert "source" not in encoded["resolved_environment"]["packages"][1]
assert (
encoded["resolved_environment"]["provenance"]["torch_version"]
== "torch==2.9.0+cu130"
)
assert FunctionVersion.from_json(version.to_canonical_json()) == version
invalid = json.loads(json.dumps(payload))
del invalid["resolved_environment"]["packages"]
with pytest.raises(ValueError):
FunctionVersion.from_json(json.dumps(invalid))
def test_function_version_reads_resolved_environments_by_platform():
legacy = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
assert legacy_version.resolved_environment is None
assert legacy_version.resolved_environments == {}
assert legacy_version.environment_report == {}
payload = _function_version_with_resolved_environments()
version = FunctionVersion.from_json(json.dumps(payload))
assert version.resolved_environment is None
assert version.resolved_environments == version.environment_report
assert set(version.environment_report) == {"linux/amd64", "linux/arm64"}
assert (
version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130"
)
assert version.environment_report["linux/arm64"].packages == ()
assert version.environment_report["linux/arm64"].warnings == (
"arm64 environment warning",
)
encoded = json.loads(version.to_canonical_json())
assert "resolved_environment" not in encoded
assert (
encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"]
== "2.9.0+cu130"
)
assert encoded["resolved_environments"]["linux/arm64"]["packages"] == []
assert FunctionVersion.from_json(version.to_canonical_json()) == version
missing_platform = json.loads(json.dumps(payload))
del missing_platform["resolved_environments"]["linux/arm64"]
missing_version = FunctionVersion.from_json(json.dumps(missing_platform))
assert "linux/arm64" not in missing_version.environment_report
assert "linux/amd64" in missing_version.environment_report
empty_map = json.loads(json.dumps(payload))
empty_map["resolved_environments"] = {}
empty_version = FunctionVersion.from_json(json.dumps(empty_map))
assert empty_version.resolved_environments == {}
assert "resolved_environments" not in json.loads(empty_version.to_canonical_json())
invalid = json.loads(json.dumps(payload))
del invalid["resolved_environments"]["linux/amd64"]["packages"]
with pytest.raises(ValueError):
FunctionVersion.from_json(json.dumps(invalid))
@pytest.mark.asyncio
async def test_registration_job_emits_server_environment_warnings_once():
payload = _function_version_with_resolved_environment()
class InnerJob:
async def wait(self):
return json.dumps(payload)
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
assert "refresh_lock" not in json.loads(request_json)
return InnerJob()
connection = object.__new__(AsyncConnection)
connection._inner = Inner()
job = await connection.create_function_async(normalize_score)
with pytest.warns(UserWarning) as recorded:
version = await job.wait()
assert [str(w.message) for w in recorded] == list(
payload["resolved_environment"]["warnings"]
)
assert version.environment.resolved.warnings == tuple(
payload["resolved_environment"]["warnings"]
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert await job.wait() is not None
assert caught == []
@pytest.mark.asyncio
async def test_registration_job_emits_per_platform_environment_warnings():
payload = _function_version_with_resolved_environments()
class InnerJob:
async def wait(self):
return json.dumps(payload)
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
return InnerJob()
connection = object.__new__(AsyncConnection)
connection._inner = Inner()
job = await connection.create_function_async(normalize_score)
with pytest.warns(UserWarning) as recorded:
version = await job.wait()
assert [str(w.message) for w in recorded] == [
"amd64 environment warning",
"arm64 environment warning",
]
assert version.environment_report["linux/arm64"].warnings == (
"arm64 environment warning",
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert await job.wait() is not None
assert caught == []
def test_blocking_create_function_emits_server_environment_warnings():
payload = _function_version_with_resolved_environment()
class InnerJob:
async def wait(self):
return json.dumps(payload)
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
return InnerJob()
connection = object.__new__(RemoteDBConnection)
connection._conn = AsyncConnection(Inner())
with pytest.warns(UserWarning) as recorded:
version = DBConnection.create_function(connection, normalize_score)
assert [str(w.message) for w in recorded] == list(
payload["resolved_environment"]["warnings"]
)
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
@pytest.mark.asyncio
async def test_catalog_readback_does_not_replay_registration_warnings():
payload = _function_version_with_resolved_environment()
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
version = await connection.get_function("embed")
listed = [item async for item in connection.list_functions()]
assert caught == []
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
assert listed[0].environment.resolved == version.resolved_environment
@pytest.mark.asyncio
async def test_catalog_readback_does_not_replay_per_platform_warnings():
payload = _function_version_with_resolved_environments()
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
version = await connection.get_function("embed")
listed = [item async for item in connection.list_functions()]
assert caught == []
assert version.environment_report == listed[0].environment_report
def _assert_execution_control_encoding(version):
encoded = json.loads(version.to_canonical_json())
assert type(encoded["batch_size"]) is int
+172 -12
View File
@@ -29,6 +29,7 @@ from lancedb.query import (
CombinedFieldsQuery,
DocumentGranularity,
FullTextOperator,
FullTextSearchQuery,
MatchQuery,
MultiMatchQuery,
PhraseQuery,
@@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
def test_search_fts_phrase_query(table):
table.create_fts_index("text", with_position=False)
try:
phrase_results = table.search('"puppy runs"').limit(100).to_list()
assert False
except Exception:
pass
with pytest.raises(Exception) as error:
table.search('"puppy runs"').limit(100).to_list()
assert "FTS(with_position=True)" in exception_output(error)
table.create_fts_index("text", with_position=True, replace=True)
results = table.search("puppy").limit(100).to_list()
@@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
@pytest.mark.asyncio
async def test_search_fts_phrase_query_async(async_table):
await async_table.create_index("text", config=FTS(with_position=False))
try:
phrase_results = (
await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
)
assert False
except Exception:
pass
with pytest.raises(Exception) as error:
await async_table.query().nearest_to_text('"puppy runs"').to_list()
assert "FTS(with_position=True)" in exception_output(error)
await async_table.create_index("text", config=FTS(with_position=True))
results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
phrase_results = (
@@ -1948,3 +1943,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
rows = await table.query().nearest_to_text("http").to_list()
assert len(rows) == 1
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
db = ldb.connect(tmp_path)
table = db.create_table(
"matches",
pa.table(
{
"id": list(range(30)),
"text": ["gripper closed"] * 15
+ ["gripper open"] * 10
+ ["camera ready"] * 5,
}
),
)
if indexed:
table.create_index("text", config=FTS())
kwargs = {"fts_columns": "text"}
if operator is not None:
kwargs["operator"] = operator
query = table.search("gripper closed", query_type="fts", **kwargs)
assert query.count_rows() == expected
assert len(query.limit(100).to_list()) == expected
assert (
table.search("gripper closed", query_type="fts", fts_columns="text")
.operator("AND")
.count_rows()
== 15
)
if operator is not None:
assert query.to_query_object().full_text_query.operator == operator
query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
before = query.to_query_object()
assert query.count_rows() == expected - 5
assert query.to_query_object() == before
assert len(query.to_list()) <= 2
assert (
table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
)
assert (
table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
== 15
)
@pytest.mark.asyncio
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
async def test_simple_fts_operator_and_count_async(
tmp_path, indexed, operator, expected
):
db = await ldb.connect_async(tmp_path)
table = await db.create_table(
"matches",
pa.table(
{
"id": list(range(30)),
"text": ["gripper closed"] * 15
+ ["gripper open"] * 10
+ ["camera ready"] * 5,
}
),
)
if indexed:
await table.create_index("text", config=FTS())
query = await table.search(
"gripper closed", query_type="fts", fts_columns="text", operator=operator
)
assert await query.count_rows() == expected
assert len(await query.limit(100).to_list()) == expected
query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
before = query.to_query_object()
assert await query.count_rows() == expected - 5
assert query.to_query_object() == before
direct = table.query().nearest_to_text(
"gripper closed", columns="text", operator="AND"
)
assert await direct.count_rows() == 15
assert direct.to_query_object().full_text_query.query.operator == "AND"
assert (
await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
)
@pytest.mark.parametrize("with_position", [False, True])
@pytest.mark.parametrize(
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
)
def test_fts_phrase_count_positions(tmp_path, with_position, query):
table = ldb.connect(tmp_path).create_table(
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
)
table.create_index("text", config=FTS(with_position=with_position))
search = table.search(query, query_type="fts")
if with_position:
assert search.count_rows() == 1
assert len(search.to_list()) == 1
assert (
table.search("gripper closed", query_type="fts", operator="AND")
.phrase_query()
.count_rows()
== 1
)
else:
with pytest.raises(Exception) as error:
search.count_rows()
assert "FTS(with_position=True)" in exception_output(error)
@pytest.mark.asyncio
@pytest.mark.parametrize("with_position", [False, True])
@pytest.mark.parametrize(
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
)
async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
db = await ldb.connect_async(tmp_path)
table = await db.create_table(
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
)
await table.create_index("text", config=FTS(with_position=with_position))
search = table.query().nearest_to_text(query)
if with_position:
assert await search.count_rows() == 1
assert len(await search.to_list()) == 1
else:
with pytest.raises(Exception) as error:
await search.count_rows()
assert "FTS(with_position=True)" in exception_output(error)
def test_fts_operator_rejects_invalid_queries(table):
with pytest.raises(ValueError):
table.search("gripper", query_type="fts", operator="XOR")
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
with pytest.raises(
ValueError, match="operator requires a string full-text query"
):
table.search(query, operator="AND")
with pytest.raises(ValueError, match="operator requires a string full-text query"):
FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
@pytest.mark.asyncio
async def test_fts_operator_rejects_invalid_queries_async(async_table):
with pytest.raises(ValueError):
await async_table.search("gripper", query_type="fts", operator="XOR")
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
with pytest.raises(
ValueError, match="operator requires a string full-text query"
):
await async_table.search(query, operator="AND")
with pytest.raises(ValueError):
async_table.query().nearest_to_text(query, operator="AND")
def test_fts_count_fast_search(tmp_path):
table = ldb.connect(tmp_path).create_table(
"matches", pa.table({"text": ["gripper closed"] * 15})
)
table.create_index("text", config=FTS())
table.add(pa.table({"text": ["gripper closed"] * 5}))
assert table.search("gripper", query_type="fts").count_rows() == 20
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
+187 -3
View File
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from lancedb.exceptions import JobCancelledError, JobFailedError
from lancedb.db import DBConnection
from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@@ -729,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
@pytest.mark.asyncio
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
@pytest.mark.parametrize("progress", [False, None])
async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
class NoProgressArgument:
id = "job-legacy"
job_type = None
@property
def job_type(self):
raise AssertionError("quiet waits must not inspect progress metadata")
async def wait(self):
return None
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
class _RegistrationQuery:
id = "registration-query"
job_type = "query"
_description = None
def __init__(self, error=None):
self.ready = asyncio.Event()
self.error = error
self.state = "running"
self.wait_calls = 0
self.cancel_calls = 0
async def status(self):
return self.state
async def wait(self, progress=None):
self.wait_calls += 1
await self.ready.wait()
if self.error is not None:
self.state = (
"cancelled" if isinstance(self.error, JobCancelledError) else "failed"
)
raise self.error
self.state = "finished"
return '{"version": "1"}'
async def cancel(self):
self.cancel_calls += 1
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
inner = _RegistrationQuery()
job = AsyncJob(inner, json.loads)
updates = []
def observe(snapshot):
updates.append(snapshot)
if len(updates) == 2:
inner.ready.set()
if sync:
result = await asyncio.to_thread(Job(job).wait, progress=observe)
else:
result = await job.wait(progress=observe)
assert result == {"version": "1"}
assert inner.wait_calls == 1
assert inner.cancel_calls == 0
assert updates[0]["state"] == "running"
assert updates[-1]["state"] == "finished"
assert all(snapshot["job_id"] == inner.id for snapshot in updates)
elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
assert elapsed == sorted(elapsed)
assert elapsed[0] >= 0
assert all("phase" not in snapshot for snapshot in updates)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"error",
[
JobFailedError("bake failed", job_id="registration-query"),
JobCancelledError("cancelled"),
],
)
async def test_query_progress_preserves_terminal_exceptions(error):
inner = _RegistrationQuery(error)
inner.ready.set()
updates = []
with pytest.raises(type(error)) as raised:
await AsyncJob(inner).wait(progress=updates.append)
assert raised.value is error
assert updates[-1]["state"] == inner.state
assert inner.wait_calls == 1
@pytest.mark.asyncio
async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
monkeypatch,
):
tqdm_module = pytest.importorskip("tqdm.auto")
bar = SimpleNamespace(
n=0,
total=None,
update=MagicMock(),
set_postfix_str=MagicMock(),
close=MagicMock(),
)
constructor = MagicMock(return_value=bar)
monkeypatch.setattr(tqdm_module, "tqdm", constructor)
inner = _RegistrationQuery(JobFailedError("bake failed"))
inner.ready.set()
with pytest.raises(JobFailedError, match="bake failed"):
await AsyncJob(inner).wait(progress=True)
assert "elapsed" in constructor.call_args.kwargs["bar_format"]
assert "rows" not in str(constructor.call_args)
assert bar.set_postfix_str.call_args.args == ("failed",)
bar.close.assert_called_once_with()
@pytest.mark.asyncio
@pytest.mark.parametrize("failed", [False, True])
@pytest.mark.parametrize("observer_error", ["status", "callback"])
async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
failed, observer_error, caplog
):
error = (
JobFailedError("bake failed", job_id="registration-query") if failed else None
)
inner = _RegistrationQuery(error)
inner.ready.set()
if observer_error == "status":
inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
def observe(snapshot):
if observer_error == "callback":
raise RuntimeError("observer failed")
job = AsyncJob(inner, json.loads)
if failed:
with pytest.raises(JobFailedError) as raised:
await job.wait(progress=observe)
assert raised.value is error
else:
assert await job.wait(progress=observe) == {"version": "1"}
assert inner.wait_calls == 1
assert inner.cancel_calls == 0
assert "job progress observer failed" in caplog.text
@pytest.mark.asyncio
async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
inner = _RegistrationQuery()
job = AsyncJob(inner, json.loads)
updates = []
with pytest.raises(TimeoutError, match="keep this handle"):
await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
assert inner.state == "running"
assert inner.cancel_calls == 0
inner.ready.set()
assert await job.wait(progress=updates.append) == {"version": "1"}
assert inner.wait_calls == 2
assert updates[-1]["state"] == "finished"
@pytest.mark.parametrize("refresh_lock", [False, True])
def test_blocking_create_function_forwards_progress_to_registration_handle(
refresh_lock,
):
connection = MagicMock()
definition = object()
progress = object()
result = DBConnection.create_function(
connection, definition, refresh_lock=refresh_lock, progress=progress
)
connection.create_function_async.assert_called_once_with(
definition,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=refresh_lock,
)
connection.create_function_async.return_value.wait.assert_called_once_with(
progress=progress
)
assert result is connection.create_function_async.return_value.wait.return_value
@pytest.mark.parametrize("progress", [False, None])
def test_blocking_create_function_preserves_quiet_wait_call(progress):
connection = MagicMock()
result = DBConnection.create_function(connection, object(), progress=progress)
connection.create_function_async.return_value.wait.assert_called_once_with()
assert result is connection.create_function_async.return_value.wait.return_value
@pytest.mark.asyncio
+177 -1
View File
@@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
if kind == "jobs":
assert verb == "POST"
assert path.path == "/v1/jobs/list"
assert body == {"page_token": token, "limit": 2}
assert body == {"database": "dev", "page_token": token, "limit": 2}
else:
namespace = "team"
resource = kind.removesuffix("s")
@@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l
with pytest.raises(ValueError, match="limit"):
await items.__anext__()
assert requests == []
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("namespace", [[], ["team", "project"]])
@pytest.mark.parametrize("multiple_types", [False, True])
async def test_job_filters_persist_across_pages_and_resume(
listing_server, asynchronous, namespace, multiple_types
):
endpoint, requests, responses = listing_server
responses.extend(
(200, response_page("jobs", names, token))
for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)]
)
db = await connection(endpoint, asynchronous)
types = ["column_refresh", "materialized_view_refresh"]
filters = dict(
table="events",
namespace_path=namespace,
state="in_progress",
created_at_gte_millis=100,
created_at_lt_millis=200,
**({"job_types": types} if multiple_types else {"job_type": types[0]}),
)
items = db.list_jobs(page_limit=1, **filters)
assert requests == []
assert (await advance(items, asynchronous)).job_id == "a"
assert len(requests) == 1
resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters)
assert (await advance(resumed, asynchronous)).job_id == "b"
assert resumed.page_token() is None
assert len(requests) == 3
expected = dict(
database="dev",
limit=1,
table_ref={
"db_name": "dev",
"table_id": {"namespace_path": namespace, "table_name": "events"},
},
state="in_progress",
job_types=types if multiple_types else types[:1],
created_at_gte_millis=100,
created_at_lt_millis=200,
)
for (_, path, body), token in zip(requests, [None, "empty", "last"]):
assert path == "/v1/jobs/list"
assert body == {**expected, **({"page_token": token} if token else {})}
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"filters",
[
{},
{"state": "failed"},
{"job_types": ["column_refresh"]},
{"created_at_lt_millis": 200},
],
)
async def test_job_listing_without_table_stays_in_connected_database(
listing_server, asynchronous, filters
):
endpoint, requests, responses = listing_server
responses.append((200, response_page("jobs", ["a"], None)))
db = await connection(endpoint, asynchronous)
items = db.list_jobs(**filters)
assert (await advance(items, asynchronous)).job_id == "a"
assert requests[0][2] == {"database": "dev", **filters}
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"filters, message",
[
({"namespace_path": ["team"]}, "requires a table"),
({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"),
({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"),
({"job_type": "column_refresh", "job_types": []}, "only one"),
({"state": "unknown"}, "state must be"),
],
)
async def test_invalid_job_filters_do_not_fetch(
listing_server, asynchronous, filters, message
):
endpoint, requests, _ = listing_server
db = await connection(endpoint, asynchronous)
with pytest.raises(ValueError, match=message):
items = db.list_jobs(**filters)
await advance(items, asynchronous)
assert requests == []
@pytest.mark.asyncio
async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server):
endpoint, requests, responses = listing_server
responses.extend(
(200, response_page("jobs", names, token))
for names, token in [(["a", "b"], "second"), (["c", "d"], "last")]
)
db = await connection(endpoint, False)
items = db.list_jobs(table="events", page_limit=2)
assert items[:0] == []
assert items[5:2] == []
assert requests == []
assert [job.job_id for job in items[:2]] == ["a", "b"]
assert len(requests) == 1
assert items.num_page_results() == 2
assert items.page_token() == "second"
assert items[1].job_id == "b"
assert next(items).job_id == "a"
assert [job.job_id for job in items[:2]] == ["b", "c"]
assert len(requests) == 2
assert items.num_page_results() == 3
assert items.page_token() == "last"
assert [job.job_id for job in items[0:3:2][:1]] == ["b"]
assert len(requests) == 2
@pytest.mark.asyncio
async def test_listing_length_and_slices_preserve_remaining_items(listing_server):
endpoint, requests, responses = listing_server
responses.extend(
(200, response_page("jobs", names, token))
for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)]
)
db = await connection(endpoint, False)
items = db.list_jobs(page_limit=2)
assert bool(items)
assert len(requests) == 1
assert next(items).job_id == "a"
assert len(items) == 3
assert len(requests) == 3
assert items.num_page_results() == 3
assert items.page_token() is None
assert items[-1].job_id == "d"
assert [job.job_id for job in items[::-1]] == ["d", "c", "b"]
assert [job.job_id for job in items[1:]] == ["c", "d"]
assert [job.job_id for job in items[:100:2]] == ["b", "d"]
assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"]
with pytest.raises(IndexError):
_ = items[3]
assert [job.job_id for job in items] == ["b", "c", "d"]
assert len(items) == 0
assert not items
assert len(requests) == 3
@pytest.mark.asyncio
async def test_listing_invalid_slice_does_not_fetch(listing_server):
endpoint, requests, _ = listing_server
db = await connection(endpoint, False)
items = db.list_jobs()
with pytest.raises(ValueError, match="step"):
_ = items[::0]
with pytest.raises(TypeError):
_ = items["invalid"]
with pytest.raises(TypeError):
_ = items[:1.5]
assert requests == []
@pytest.mark.asyncio
async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server):
endpoint, requests, responses = listing_server
responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})])
db = await connection(endpoint, False)
items = db.list_jobs(page_limit=2)
with pytest.raises(HttpError):
_ = items[:3]
assert items.page_token() == "retry"
assert items.num_page_results() == 2
assert [job.job_id for job in items[:2]] == ["a", "b"]
assert [job.job_id for job in items] == ["a", "b"]
assert len(requests) == 2
+41 -1
View File
@@ -18,6 +18,7 @@ import lancedb
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
from utils import start_server_thread
from lancedb.listing import AsyncListing, Listing
from lancedb.index import FTS
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
from lancedb.namespace import (
_MAX_QUERY_K,
@@ -25,7 +26,7 @@ from lancedb.namespace import (
LanceNamespaceDBConnection,
_query_to_namespace_request,
)
from lancedb.query import Query
from lancedb.query import FullTextSearchQuery, Query
from lancedb.table import AsyncTable, LanceTable
@@ -1524,3 +1525,42 @@ def test_python_namespace_attribute_access(tmp_path):
# Missing dunder lookups still raise, so copy/hasattr probes work.
assert not hasattr(request, "__missing_dunder__")
assert copy.deepcopy(request) == request
@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
def test_namespace_fts_operator_is_preserved(columns):
request = _query_to_namespace_request(
["matches"],
Query(
full_text_query=FullTextSearchQuery(
query="gripper closed", columns=columns, operator="AND"
)
),
)
structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
if columns and len(columns) > 1:
assert all(
query["operator"] == "And"
for query in structured["multi_match"]["match_queries"]
)
else:
assert structured["match"]["operator"] == "And"
assert structured["match"].get("column") == (columns[0] if columns else None)
def test_namespace_fts_count_fast_search(tmp_path):
properties = {"root": str(tmp_path)}
db = lancedb.connect_namespace("dir", properties)
table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
table.create_index("text", config=FTS())
table.add(pa.table({"text": ["gripper"] * 5}))
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
pushed = lancedb.connect_namespace(
"dir", properties, namespace_client_pushdown_operations=["QueryTable"]
).open_table("matches")
assert pushed.search("gripper", query_type="fts").count_rows() == 20
query = pushed.search("gripper", query_type="fts").fast_search()
assert query.use_rte(False).count_rows() == 15
query = pushed.search("gripper", query_type="fts").fast_search()
assert query.count_rows() == 15
assert len(query.limit(100).to_list()) == 15
+201
View File
@@ -310,6 +310,164 @@ async def test_add_retry_override(sync_api, retries, status):
assert attempts == (2 if expected_success else 1)
@pytest.mark.parametrize("sync_api", [False, True])
@pytest.mark.parametrize("namespace_path", [[], ["analytics", "features"]])
@pytest.mark.parametrize("retries", [None, 0, 2])
@pytest.mark.parametrize("status", [409, 429, 502, 503, 504])
@pytest.mark.asyncio
async def test_merge_retry_override(sync_api, namespace_path, retries, status, capfd):
attempts = 0
identifier = "$".join(namespace_path + ["test"])
def handler(request):
nonlocal attempts
if request.path == f"/v1/table/{identifier}/describe/":
send_json(
request,
{
"version": 1,
"schema": {
"fields": [
{"name": "id", "type": {"type": "int64"}, "nullable": True}
]
},
},
)
return
assert urlparse(request.path).path == f"/v1/table/{identifier}/merge_insert/"
query = parse_qs(urlparse(request.path).query)
assert query["use_index"] == ["false"]
assert request.headers["x-request-timeout-ms"] == "10000"
body = bytearray()
if request.headers.get("Transfer-Encoding") == "chunked":
while True:
size = int(request.rfile.readline().strip(), 16)
if size == 0:
request.rfile.readline()
break
body.extend(request.rfile.read(size))
request.rfile.read(2)
else:
body.extend(
request.rfile.read(int(request.headers.get("Content-Length", 0)))
)
assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}]
attempts += 1
send_json(request, {"version": 2}, status if attempts == 1 else 200)
config = {
"retry_config": {
"retries": 3,
"statuses": [409, 429, 502, 503, 504],
"backoff_factor": 0,
"backoff_jitter": 0,
}
}
expected_success = status in (409, 429) and retries != 0
async def check(table):
merge = table.merge_insert("id").when_not_matched_insert_all().use_index(False)
options = {"timeout": timedelta(seconds=10)}
if retries is not None:
options["retries"] = retries
if expected_success:
result = merge.execute([{"id": 1}], **options)
if not sync_api:
result = await result
assert result.version == 2
else:
with pytest.raises((HttpError, RetryError)):
result = merge.execute([{"id": 1}], **options)
if not sync_api:
await result
if sync_api:
with mock_lancedb_connection(handler, **config) as db:
await check(db.open_table("test", namespace_path=namespace_path))
else:
async with mock_lancedb_connection_async(handler, **config) as db:
await check(await db.open_table("test", namespace_path=namespace_path))
assert attempts == (2 if expected_success else 1)
warnings = [
line
for line in capfd.readouterr().err.splitlines()
if "Retrying merge insert" in line
]
assert len(warnings) == (1 if expected_success else 0)
if expected_success:
assert "WARN" in warnings[0]
assert f"status Some({status}); attempt 2" in warnings[0]
@pytest.mark.parametrize("sync_api", [False, True])
@pytest.mark.asyncio
async def test_merge_retry_override_isolation(sync_api):
attempts = 0
read_attempts = 0
def handler(request):
nonlocal attempts, read_attempts
if request.path.endswith("/describe/"):
send_json(
request,
{
"version": 1,
"schema": {
"fields": [
{"name": "id", "type": {"type": "int64"}, "nullable": True}
]
},
},
)
elif request.path.endswith("/count_rows/"):
read_attempts += 1
send_json(request, 1, 429 if read_attempts % 2 else 200)
else:
assert urlparse(request.path).path.endswith("/merge_insert/")
attempts += 1
send_json(request, {"version": 2}, 429 if attempts in (1, 2, 4, 6) else 200)
async def check(table):
merge = table.merge_insert("id").when_not_matched_insert_all()
for retries in [-1, 256, 1.5, "1"]:
with pytest.raises((OverflowError, TypeError, ValueError)):
result = merge.execute([{"id": 1}], retries=retries)
if not sync_api:
await result
assert attempts == 0
with pytest.raises((HttpError, RetryError)):
result = merge.execute([{"id": 1}], retries=0)
if not sync_api:
await result
assert attempts == 1
for options in ({}, {"retries": 255}):
result = merge.execute([{"id": 1}], **options)
if not sync_api:
result = await result
assert result.version == 2
assert attempts == 5
result = table.count_rows()
if not sync_api:
result = await result
assert result == 1
assert read_attempts == 2
result = (
table.merge_insert("id").when_not_matched_insert_all().execute([{"id": 1}])
)
if not sync_api:
result = await result
assert result.version == 2
assert attempts == 7
config = {"retry_config": {"retries": 3, "backoff_factor": 0, "backoff_jitter": 0}}
if sync_api:
with mock_lancedb_connection(handler, **config) as db:
await check(db.open_table("test"))
else:
async with mock_lancedb_connection_async(handler, **config) as db:
await check(await db.open_table("test"))
@pytest.fixture
def missing_table_handler(cached, namespace_path):
request_ids = []
@@ -7644,3 +7802,46 @@ async def test_remote_index_exist_ok_wire(is_async, background, kwargs):
assert body["replace"] is False
else:
assert "replace" not in body
@pytest.mark.parametrize("operator", ["AND", "OR"])
def test_remote_fts_operator_and_count(operator):
def handler(body):
query = body["full_text_query"]["query"]["match"]
assert query["terms"] == "gripper closed"
assert query["operator"] == operator.title()
assert query["column"] == "text"
assert body["k"] == 2**63 - 1
assert "offset" not in body
assert body["columns"] == ["_score"]
assert body["filter"] == "text IS NOT NULL"
assert body["prefilter"] is False
return pa.table({"_score": [1.0] * 25})
with query_test_table(
handler, server_version=Version("0.6.0"), vector_columns={}
) as table:
query = (
table.search(
"gripper closed",
query_type="fts",
fts_columns="text",
operator=operator,
)
.where("text IS NOT NULL", prefilter=False)
.select(["text"])
.limit(1)
.offset(3)
)
assert query.count_rows() == 25
assert query.to_query_object().limit == 1
assert query.to_query_object().offset == 3
def test_remote_fts_and_rejects_legacy_server():
def handler(body):
pytest.fail("AND must not silently become OR on a legacy server")
with query_test_table(handler, vector_columns={}) as table:
with pytest.raises(NotImplementedError, match="server version 0.3.0"):
table.search("gripper closed", query_type="fts", operator="AND").to_list()
@@ -3,6 +3,7 @@
import contextlib
import json
import re
from pathlib import Path
import pytest
@@ -39,7 +40,30 @@ def remote_server(text_type=pa.string()):
command = ticket.ticket
calls.append(command)
if b"SHOW STORAGE INTEGRATIONS" in command:
result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
match = re.search(
rb'SHOW STORAGE INTEGRATIONS IN "public" '
rb"LIMIT (\d+)(?: FROM '([^']+)')?",
command,
)
assert match is not None, command
limit = int(match.group(1))
names = [NAME, "zeta"]
if match.group(2) is not None:
assert match.group(2) == b"server-storage-page", command
names = names[1:]
page = names[:limit]
result = pa.table(
{
"namespace_path": pa.array(
["[]"] * len(page), type=pa.string()
),
"name": pa.array(page, type=text_type),
}
)
if len(names) > limit:
result = result.replace_schema_metadata(
{b"lancedb.next_page_token": b"server-storage-page"}
)
elif b"DROP STORAGE INTEGRATION" in command:
result = pa.table({"dropped": [True]})
else:
@@ -195,6 +219,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0]
assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0]
assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1]
listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call]
assert len(listings) == 2
assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0]
assert b"FROM 'server-storage-page'" in listings[1]
@pytest.mark.asyncio
+3 -2
View File
@@ -3448,7 +3448,8 @@ def test_merge_insert(mem_db: DBConnection):
table.merge_insert("a")
.when_matched_update_all()
.when_not_matched_insert_all()
.execute(new_data, timeout=timedelta(seconds=10))
.use_index(False)
.execute(new_data, timeout=timedelta(seconds=10), retries=0)
)
assert merge_insert_res.version == 2
assert merge_insert_res.num_inserted_rows == 1
@@ -3527,7 +3528,7 @@ def test_merge_insert(mem_db: DBConnection):
# timeout
with pytest.raises(Exception, match="merge insert timed out"):
table.merge_insert("a").when_matched_update_all().execute(
new_data, timeout=timedelta(0)
new_data, timeout=timedelta(0), retries=255
)
+35 -3
View File
@@ -23,7 +23,7 @@ use lancedb::{
connection::Connection as LanceConnection,
connection::NamespaceClientPushdownOperation,
database::namespace::LanceNamespaceDatabase,
database::{CreateTableMode, Database, ReadConsistency},
database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency},
function::{GpuClass as LanceGpuClass, RefreshColumnResult},
graph::PropertyGraphDefinition,
materialized_view::CreateMaterializedViewBuilder,
@@ -1319,15 +1319,47 @@ impl Connection {
))
}
#[pyo3(signature = (*, page_token=None, page_limit=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))]
pub fn list_jobs(
&self,
page_token: Option<String>,
page_limit: Option<u32>,
table: Option<String>,
namespace_path: Option<Vec<String>>,
state: Option<String>,
job_type: Option<String>,
job_types: Option<Vec<String>>,
created_at_gte_millis: Option<i64>,
created_at_lt_millis: Option<i64>,
) -> PyResult<crate::listing::JobListing> {
if job_type.is_some() && job_types.is_some() {
return Err(PyValueError::new_err(
"set only one of job_type and job_types",
));
}
let mut filter = JobListFilter::default();
filter.table = table;
filter.namespace_path = namespace_path.unwrap_or_default();
filter.state = state
.as_deref()
.map(|state| match state {
"in_progress" => Ok(JobListState::InProgress),
"succeeded" => Ok(JobListState::Succeeded),
"failed" => Ok(JobListState::Failed),
"canceled" => Ok(JobListState::Canceled),
"timed_out" => Ok(JobListState::TimedOut),
_ => Err(PyValueError::new_err(
"state must be one of: in_progress, succeeded, failed, canceled, timed_out",
)),
})
.transpose()?;
filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect());
filter.created_at_gte_millis = created_at_gte_millis;
filter.created_at_lt_millis = created_at_lt_millis;
Ok(crate::listing::JobListing::new(
self.get_inner()?
.list_jobs(crate::listing::options(page_token, page_limit)),
.list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)),
))
}
+35 -2
View File
@@ -16,19 +16,20 @@ use arrow::array::make_array;
use arrow::pyarrow::FromPyArrow;
use arrow::pyarrow::IntoPyArrow;
use arrow::pyarrow::ToPyArrow;
use futures::TryStreamExt;
use lancedb::ApproxMode;
use lancedb::index::scalar::{
BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery,
FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery,
};
use lancedb::query::AnalyzePlanDistributedMetrics;
use lancedb::query::QueryBase;
use lancedb::query::QueryExecutionOptions;
use lancedb::query::QueryFilter;
use lancedb::query::{
ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery,
VectorQuery as LanceDbVectorQuery,
};
use lancedb::query::{HasQuery, QueryBase};
use lancedb::table::AnyQuery;
use pyo3::Bound;
use pyo3::IntoPyObject;
@@ -616,8 +617,18 @@ impl Query {
query_text = query_text[1..query_text.len() - 1].to_string();
}
let operator = query
.get_item("operator")?
.filter(|operator| !operator.is_none())
.map(|operator| {
let operator = operator.extract::<String>()?;
Operator::try_from(operator.as_str())
.map_err(|err| PyValueError::new_err(err.to_string()))
})
.transpose()?
.unwrap_or(Operator::Or);
let query: FtsQuery = match (is_phrase, is_multi_match) {
(false, _) => MatchQuery::new(query_text).into(),
(false, _) => MatchQuery::new(query_text).with_operator(operator).into(),
(true, false) => PhraseQuery::new(query_text).into(),
(true, true) => {
return Err(PyValueError::new_err(
@@ -898,6 +909,28 @@ impl FTSQuery {
})
}
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let mut inner = self_
.inner
.clone()
.full_text_search(self_.fts_query.clone());
let request = inner.mut_query();
request.limit = None;
request.offset = None;
request.select = Select::columns(&["_score"]);
request.order_by = None;
request.with_row_id = false;
request.reranker = None;
future_into_py(self_.py(), async move {
let mut stream = inner.execute().await.infer_error()?;
let mut count = 0_u64;
while let Some(batch) = stream.try_next().await.infer_error()? {
count += batch.num_rows() as u64;
}
Ok(count)
})
}
pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult<HybridQuery> {
let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?;
Ok(HybridQuery {
+5
View File
@@ -2269,10 +2269,12 @@ impl Table {
})
}
#[pyo3(signature = (data, parameters, retries=None))]
pub fn execute_merge_insert<'a>(
self_: PyRef<'a, Self>,
data: Bound<'a, PyAny>,
parameters: MergeInsertParams,
retries: Option<u8>,
) -> PyResult<Bound<'a, PyAny>> {
let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?;
let on = parameters.on.iter().map(|s| s.as_str()).collect::<Vec<_>>();
@@ -2295,6 +2297,9 @@ impl Table {
if let Some(timeout) = parameters.timeout {
builder.timeout(timeout);
}
if let Some(retries) = retries {
builder.retries(retries);
}
if let Some(use_index) = parameters.use_index {
builder.use_index(use_index);
}
+9 -9
View File
@@ -2147,7 +2147,7 @@ requires-dist = [
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b22" },
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
@@ -4301,7 +4301,7 @@ crypto = [
[[package]]
name = "pylance"
version = "15.0.0b21"
version = "15.0.0b22"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
@@ -4312,13 +4312,13 @@ dependencies = [
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" },
{ url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" },
{ url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" },
{ url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" },
{ url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" },
{ url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" },
]
[[package]]