From ea59f8acb61a6ac93fc940d055efe3c8f823991c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 21:49:45 +0800 Subject: [PATCH 01/11] feat(python): preserve Function timestamp and duration types (#5032) Function declarations currently reject exact timestamp and duration types. Preserve their Arrow units and timezones in canonical signature JSON, including fixed-offset timezones and nested fields. Bare `datetime` and microsecond/no-timezone declarations keep their existing representation; `timedelta` requires an explicit unit. Compound temporal signatures require the Lance Namespace decoder in https://github.com/lance-format/lance/pull/11059 and corresponding server validation support. Older readers reject these signatures; this change does not upgrade server support or dependency pins. Validation: 128 Python signature tests and 30 documentation tests passed (one skipped), using the changed Python source with an existing native extension. No Rust rebuild or end-to-end Function registration/refresh was performed. --- docs/web/management/function.mdx | 35 ++++ python/python/lancedb/functions.py | 48 +++++- .../tests/test_first_class_function_slice2.py | 156 +++++++++++++++++- 3 files changed, 227 insertions(+), 12 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 41e64d482..f6264edbf 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -104,6 +104,41 @@ at all is the struct's own validity, which Enterprise keeps in a separate internal column when it expands the result into sibling columns, so a null field is a value rather than a missing row. +### Timestamps and durations {#timestamps-durations} + +Bare `datetime` keeps its existing `timestamp[us]` default without a timezone. +For any other unit or a timezone, declare the Arrow type explicitly: + +```python +from datetime import datetime +from typing import Annotated + +import pyarrow as pa + + +@function +def normalize( + ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")], +) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]: + ... +``` + +`pa.timestamp` accepts `s`, `ms`, `us`, and `ns`, and a timezone such as +`UTC`, `America/New_York`, or `+08:00`. The canonical signature uses +`{"type":"timestamp::"}`, with `-` for no timezone; the +microsecond/no-timezone case keeps the legacy `{"type":"timestamp"}` shape. +A timezone string of `-` is reserved for "no timezone" and is rejected. + +`pa.duration` accepts the same four units and uses +`{"type":"duration:"}`; the microsecond case keeps the legacy +`{"type":"duration"}` shape. A bare `timedelta` has no unit and is rejected; +use `Annotated[timedelta, pa.duration("s")]` or an explicit schema. + +Other units are never downgraded to microseconds. A reader that predates the +compound temporal representation cannot read those signatures. A deployment +must include the corresponding Lance Namespace and Sophon support; this +client-side declaration does not add server support. + ## Connect and create a table {#table} The remaining steps run against your Enterprise deployment. Replace the database diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 471fc2437..18c504a8f 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -29,7 +29,7 @@ import textwrap import types import warnings from collections.abc import Mapping, Sequence -from datetime import date, datetime +from datetime import date, datetime, timedelta from pathlib import Path from typing import ( Annotated, @@ -1043,6 +1043,7 @@ _GRAMMAR_PRIMITIVES = ( (pa.date32(), "date32"), (pa.date64(), "date64"), ) +_FUNCTION_TIMEUNITS = ("s", "ms", "us", "ns") def _canonical_arrow_type( @@ -1259,6 +1260,26 @@ def _exact_arrow_type( for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return {"type": name} + 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] @@ -1344,9 +1365,9 @@ 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, and timedelta has no unit of + # its own; the Annotated metadata supplies those types. + if base is dict or get_origin(base) is dict or base is timedelta: base_nullable = False else: _, base_nullable = _annotation_type(base) @@ -1372,7 +1393,14 @@ 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 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: @@ -2701,7 +2729,11 @@ def function( deployment must accept nullable scalar outputs; an older server rejects the registration. Every named-struct field may be nullable; Enterprise preserves the struct's validity when the result is expanded into sibling - columns. + columns. 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 +2840,10 @@ 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. 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 diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 7e089a96d..1e896f780 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -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,7 +19,7 @@ import sys import typing import urllib.parse import warnings -from typing import Optional +from typing import Annotated, Optional import pyarrow as pa import pytest @@ -884,12 +884,11 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): == "large_list" ) 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 +1214,153 @@ 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_nullable_scalar_output_annotation_and_explicit_schema(): input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)]) From 2499342fa1bccdaafdf4c38a8da35459b25b247d Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:30:28 +0800 Subject: [PATCH 02/11] feat(function): expose resolved environments and fresh lock requests (#5034) Function registration clients cannot request fresh dependency resolution or inspect the measured environment returned by the server. Add `refresh_lock=True` to Python registration and preserve the requested runtime and measured environments in Rust/Python Function version readback. Registration forwards both `exist_ok` and `refresh_lock`; defaults remain unchanged. Single-platform versions retain `resolved_environment`. Multiarchitecture versions expose `resolved_environments`, keyed by OCI `os/architecture`, and the Python `environment_report` alias. Platforms are never flattened: absent entries mean unknown measurements, while measured empty package lists remain present. Registration waits emit scalar and per-platform server warnings once per Job; catalog reads do not repeat them. Requires matching server support, including Sophon #10344 for per-platform publication. Nine focused Python source-overlay tests and 29 documentation tests passed for the additive map change; one documentation test requiring a newer native `exist_ok` binding was excluded. These checks reuse a prebuilt extension and do not establish current native integration. PR CI exercises the Rust transport/readback and Python bindings. Live multiarchitecture registration and GPU acceptance remain separate. --- docs/src/python/python.md | 8 + docs/web/management/function.mdx | 118 ++++++ python/python/lancedb/__init__.py | 4 + python/python/lancedb/db.py | 56 ++- python/python/lancedb/functions.py | 122 ++++++ python/python/lancedb/remote/db.py | 2 + .../tests/test_first_class_function_slice2.py | 371 +++++++++++++++++- rust/lancedb/src/function.rs | 279 ++++++++++++- rust/lancedb/src/remote/sql_test.rs | 135 +++++++ 9 files changed, 1087 insertions(+), 8 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5aa21f691..b7eb1704a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -564,6 +564,14 @@ with BlobReader(read_range, len(payload)) as reader: ::: lancedb.functions.FunctionVersion +::: lancedb.functions.FunctionEnvironment + +::: lancedb.functions.ResolvedEnvironment + +::: lancedb.functions.ResolvedPackage + +::: lancedb.functions.ResolvedEnvironmentProvenance + ::: lancedb.functions.HuggingFaceModel ::: lancedb.functions.PythonRuntimeSpec diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index f6264edbf..efcbcc799 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -178,6 +178,13 @@ with `db.get_function(name, version=...)`. The version may be an integer or its string form. Omit `version` to resolve and return the latest currently visible revision. +Re-registering unchanged code reuses the published version and its resolved +environment lock. Pass `refresh_lock=True` to `create_function` or +`create_function_async` to request a fresh lock for this registration. It is a +registration action, not part of the Function's source or runtime identity. +A deployment must support the field; an older server rejects the unknown +field rather than silently reusing the old lock. + {/* Draft for the function exist_ok release. Use `exist_ok=True` on `create_function` or `create_function_async` to return @@ -246,6 +253,117 @@ are not included; list each namespace separately. A version's `created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are all readable this way without applying or calling the function. +### Inspect the resolved environment {#resolved-environment} + +The version keeps the requested runtime separate from what the server actually +installed. The typed catalog API is available in Python and Rust; TypeScript +does not yet expose this readback API. `version.runtime` is the specification +sent at registration. `version.resolved_environment` is measured data from the +built image: + + +```python +version = db.get_function("double") +print(version.runtime) # requested runtime, or None for legacy +print(version.environment.resolved) # measured environment, or None for legacy +print(version.environment_report) # platform -> measured environment map + +if version.environment.resolved is not None: + for package in version.environment.resolved.packages: + print(package.name, package.version) # versions keep labels such as +cu130 +``` + +{/* Draft for the typed Rust environment inspection release. +```rust +# async fn inspect_environment(connection: &lancedb::Connection) -> Result<(), Box> { +let version = connection.get_function_latest("double", &[]).await?; +println!("Requested runtime: {:?}", version.runtime()); + +if let Some(environment) = version.resolved_environment() { + for package in &environment.packages { + println!("{} {}", package.name, package.version); + } +} + +for (platform, environment) in version.resolved_environments() { + println!("{platform}: {} measured packages", environment.packages.len()); + for package in &environment.packages { + println!("{} {}", package.name, package.version); + } +} +# Ok(()) +# } +``` +*/} + + +`version.environment.requested` and `version.environment.resolved` are +convenience members over the same canonical fields; they do not add another +wire shape. The canonical JSON exposes top-level `runtime` and +`resolved_environment`. A missing `resolved_environment` means the version or +environment cache predates measurement; it is unknown, not an empty installed +package list. A package's `source` is present only when the submitted lock +retained it, and provenance fields are reported without client-side guessing. + +For a multiarchitecture image, the scalar field is absent and +`version.resolved_environments` (also available as +`version.environment_report`) maps OCI `os/architecture` keys to the measured +environment for that platform. A missing platform key means its measurement is +unknown; an empty `packages` list inside a key is a measured empty environment +and is retained. The SDK never merges platforms or fabricates an aggregate +package list. + +The corresponding canonical payload has this shape: + +```json +{ + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": {"kind": "pip", "packages": ["vllm==0.11.0"]} + }, + "resolved_environment": { + "packages": [ + { + "name": "torch", + "version": "2.9.0+cu130", + "source": "https://packages.example/simple" + } + ], + "provenance": { + "configured_index_urls": ["https://packages.example/simple"], + "resolved_indexes": ["https://packages.example/simple"], + "cuda_toolkit": "12.8", + "torch_version": "torch==2.9.0+cu130" + }, + "warnings": [ + "torch resolved to torch==2.9.0+cu130 but is not pinned exactly; add torch==2.9.0+cu130 to pin it." + ] + } +} +``` + +The multiarchitecture form has the same package shape per platform: + +```json +{ + "resolved_environments": { + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + } +} +``` + +Environment warnings are part of the registration result. Waiting on +`create_function_async(...)` (or calling `create_function`) emits each server +warning from the scalar or per-platform measurements as a Python `UserWarning`; +`get_function` and `list_functions` read the same version but do not +replay those registration warnings. + ## Try it in SQL {#try-sql} A registered function is callable in SQL by its name, the same as any other diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 31285d100..acf25d35c 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -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, diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b84e4d581..12c7edd5c 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -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,7 @@ class DBConnection(EnforceOverrides): secrets: Optional[Sequence[EnvVarSecret]] = None, exist_ok: bool = False, namespace_path: Optional[List[str]] = None, + refresh_lock: bool = False, ) -> FunctionVersion: """Build and register a scalar Python function, then return its version. @@ -1040,6 +1073,13 @@ 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. + + 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 -------- @@ -1060,6 +1100,7 @@ class DBConnection(EnforceOverrides): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ).wait() def create_function_async( @@ -1069,6 +1110,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 +1121,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( @@ -2432,6 +2479,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 +2487,7 @@ class LanceDBConnection(DBConnection): secrets=secrets, exist_ok=exist_ok, namespace_path=namespace_path, + refresh_lock=refresh_lock, ) ) return Job(job) @@ -3788,6 +3837,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 +3852,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, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 18c504a8f..ecbc697d1 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -36,6 +36,7 @@ from typing import ( Any, Callable, Literal, + NamedTuple, Optional, TYPE_CHECKING, Union, @@ -101,6 +102,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 @@ -544,6 +551,67 @@ class FunctionImage(_RemoteValue): models: tuple[HuggingFaceModel, ...] = () +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: raise ValueError("Function version exceeds uint64") @@ -593,6 +661,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 +692,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 +713,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 +871,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 +886,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 +903,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 @@ -3043,6 +3161,7 @@ __all__ = [ "FunctionArtifactContent", "FunctionArtifactRequest", "FunctionBinding", + "FunctionEnvironment", "FunctionOutput", "FunctionParameter", "FunctionRegistrationRequest", @@ -3059,6 +3178,9 @@ __all__ = [ "PythonEnvironmentSpec", "PythonAdapterSpec", "PythonRuntimeSpec", + "ResolvedEnvironment", + "ResolvedEnvironmentProvenance", + "ResolvedPackage", "RefreshColumnResult", "FunctionDefinition", ] diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index b9928d278..913c8fc2c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -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) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 1e896f780..6dcc0bbbe 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -26,8 +26,9 @@ 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 +83,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 +156,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", @@ -2205,6 +2375,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 diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 582b5b08a..d0ef6570d 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -521,6 +521,59 @@ pub struct HuggingFaceModel { pub revision: String, } +/// One installed Python distribution as measured from a Function's baked +/// environment. +/// +/// `version` is the complete version string reported by the package metadata, +/// including local labels such as `+cu130`. `source` is present only when the +/// submitted lock retained a per-package source; a missing value is unknown and +/// must not be inferred from other package indexes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedPackage { + pub name: String, + pub version: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +/// Sanitized source and accelerator provenance retained with a resolved +/// environment. +/// +/// `configured_*` records what the build was asked to use. `resolved_indexes` +/// records indexes visible in the submitted lock, so a configured source is +/// not mistaken for evidence that a package came from it. Empty lists and +/// absent fields remain absent rather than being synthesized by the client. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironmentProvenance { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_index_urls: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub configured_find_links: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub resolved_indexes: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cuda_toolkit: Option, + /// The fully resolved `torch==` when torch was installed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub torch_version: Option, +} + +/// Actual installed distributions and registration warnings for one native +/// Function environment. +/// +/// A missing environment means its measurement is unknown, not an empty +/// installed-package list. The field keeps the complete versions and only the +/// provenance the producer recorded; SDK readers do not recompute package +/// policy. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResolvedEnvironment { + pub packages: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provenance: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + /// A complete OCI Function image. Its digest is independent of catalog names. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionImage { @@ -578,7 +631,9 @@ impl<'de> Deserialize<'de> for RowTimeoutSeconds { /// decoding, but they are not part of this value and are omitted from /// canonical JSON. Known fields retain their complete values, while unknown /// fields inside the open [`FunctionImage::descriptor`] JSON object remain -/// available. +/// available. Single-platform measurements use `resolved_environment`; +/// multiarchitecture measurements use `resolved_environments`, keyed by OCI +/// `os/architecture`, without flattening the platforms. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, @@ -626,6 +681,28 @@ pub struct FunctionVersion { /// Result-stability value declared at registration. #[serde(default, skip_serializing_if = "Option::is_none")] result_stability: Option, + /// The runtime requested at registration, with submitted lock bytes omitted. + /// + /// This is a specification, not the measured installation. Compare it with + /// [`Self::resolved_environment`] when the caller needs actual package + /// versions. + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime: Option, + /// Actual installed distributions, provenance, and registration warnings. + /// + /// This is the single-platform compatibility field. `None` on a + /// multiarchitecture version is expected; use + /// [`Self::resolved_environments`] for its per-platform measurements. + #[serde(default, skip_serializing_if = "Option::is_none")] + resolved_environment: Option, + /// Measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// Unmeasured platforms are absent. An empty map is unknown, not an + /// aggregate of packages from the available platforms. Single-platform + /// images use [`Self::resolved_environment`] instead. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + resolved_environments: BTreeMap, } impl FunctionVersion { @@ -716,6 +793,35 @@ impl FunctionVersion { self.result_stability.as_deref() } + /// The runtime specification requested at registration, when exposed by the + /// server. + /// + /// This is the requested configuration, not evidence of what was installed. + pub fn runtime(&self) -> Option<&PythonRuntimeSpec> { + self.runtime.as_ref() + } + + /// Actual installed distributions and registration warnings for a + /// single-platform image, when measured by the server. + /// + /// `None` is unknown, not an empty environment. Package versions are + /// retained verbatim, including local labels such as `+cu130`; `source` + /// remains absent when the producer did not retain it. + pub fn resolved_environment(&self) -> Option<&ResolvedEnvironment> { + self.resolved_environment.as_ref() + } + + /// Per-platform measurements for a multiarchitecture image, keyed by OCI + /// `os/architecture`. + /// + /// The map is returned without flattening or synthesis. A missing platform + /// means its measurement is unknown; an empty environment value is a + /// measured empty environment and is retained. Single-platform images use + /// [`Self::resolved_environment`] instead. + pub fn resolved_environments(&self) -> &BTreeMap { + &self.resolved_environments + } + pub fn signature(&self) -> &FunctionSignature { &self.signature } @@ -827,6 +933,10 @@ fn validate_row_timeout_value(value: Option) -> std::result::Result<(), &'s Ok(()) } +fn is_false(value: &bool) -> bool { + !*value +} + /// Stable request envelope for remote immutable Function registration. /// /// Credential values deliberately have no field here. The only secret-shaped @@ -877,10 +987,10 @@ pub struct FunctionRegistrationRequest { /// Model snapshots prepared by the service before user code runs. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub models: Vec, -} - -fn is_false(value: &bool) -> bool { - !*value + /// Ask the service to resolve a fresh environment lock for this request + /// instead of reusing the published version's lock. Omitted when false. + #[serde(default, skip_serializing_if = "is_false")] + pub refresh_lock: bool, } impl FunctionRegistrationRequest { @@ -1465,6 +1575,165 @@ mod tests { assert!(FunctionVersion::from_json(&document.to_string()).is_err()); } + #[test] + fn function_version_preserves_requested_and_resolved_environments() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert!(legacy.runtime().is_none()); + assert!(legacy.resolved_environment().is_none()); + assert!(legacy.resolved_environments().is_empty()); + + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environment"] = serde_json::json!({ + "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." + ] + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime().unwrap().kind(), "python"); + assert!(version.resolved_environments().is_empty()); + let resolved = version.resolved_environment().unwrap(); + assert_eq!(resolved.packages[0].version, "2.9.0+cu130"); + assert_eq!( + resolved.packages[0].source.as_deref(), + Some("https://packages.example/simple") + ); + assert_eq!(resolved.packages[1].source, None); + assert_eq!( + resolved + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(resolved.warnings.len(), 1); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert_eq!( + encoded_value["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + encoded_value["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environment"] = serde_json::json!({"warnings": []}); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + + #[test] + fn function_version_preserves_resolved_environments_by_platform() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + document["runtime"] = serde_json::json!({ + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": ["vllm==0.11.0"] + } + }); + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [ + {"name": "torch", "version": "2.9.0+cu130"} + ], + "warnings": ["amd64 measurement"] + }, + "linux/arm64": { + "packages": [], + "warnings": ["arm64 measurement"] + } + }); + + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(version.resolved_environment().is_none()); + let environments = version.resolved_environments(); + assert_eq!(environments.len(), 2); + assert_eq!( + environments["linux/amd64"].packages[0].version, + "2.9.0+cu130" + ); + assert!(environments["linux/arm64"].packages.is_empty()); + assert_eq!(environments["linux/arm64"].warnings, ["arm64 measurement"]); + + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + assert!(encoded_value.get("resolved_environment").is_none()); + assert_eq!( + encoded_value["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + encoded_value["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + + document["resolved_environments"] + .as_object_mut() + .unwrap() + .remove("linux/arm64"); + let missing_platform = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!( + !missing_platform + .resolved_environments() + .contains_key("linux/arm64") + ); + + document["resolved_environments"] = serde_json::json!({}); + let empty_map = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert!(empty_map.resolved_environments().is_empty()); + assert!( + !empty_map + .to_canonical_json() + .unwrap() + .contains("resolved_environments") + ); + + document["resolved_environments"] = serde_json::json!({ + "linux/amd64": {"warnings": []} + }); + assert!(FunctionVersion::from_json(&document.to_string()).is_err()); + } + #[test] fn blob_reader_access_survives_signature_round_trip() { let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({ diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 1c39eda19..5c7ae7673 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -3171,6 +3171,38 @@ async fn function_creation_and_description_use_sql_query_handles() { version_json["max_concurrency"] = serde_json::json!(4); version_json["row_timeout_seconds"] = serde_json::json!(8.0); version_json["result_stability"] = serde_json::json!("input_and_context"); + version_json["runtime"] = request_json["runtime"].clone(); + version_json["resolved_environment"] = serde_json::json!({ + "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": [], + "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." + ] + }); + version_json["resolved_environments"] = serde_json::json!({ + "linux/amd64": { + "packages": [{"name": "torch", "version": "2.9.0+cu130"}] + }, + "linux/arm64": { + "packages": [] + } + }); if with_models { let models = serde_json::json!([{ "repo": "sentence-transformers/all-MiniLM-L6-v2", @@ -3217,6 +3249,17 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created.max_concurrency(), Some(4)); assert_eq!(created.row_timeout_seconds(), Some(8.0)); assert_eq!(created.result_stability(), Some("input_and_context")); + assert_eq!(created.runtime().unwrap().kind(), "python"); + assert_eq!( + created.resolved_environment().unwrap().packages[0].version, + "2.9.0+cu130" + ); + assert_eq!(created.resolved_environments().len(), 2); + assert!( + created.resolved_environments()["linux/arm64"] + .packages + .is_empty() + ); // Assert the actual SQL body, after the same native JSON decode used // by the Python binding, rather than only the Python declaration. { @@ -3240,6 +3283,23 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(created_json["max_concurrency"], 4); assert_eq!(created_json["row_timeout_seconds"], 8.0); assert_eq!(created_json["result_stability"], "input_and_context"); + assert_eq!( + created_json["resolved_environment"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert!( + created_json["resolved_environment"]["packages"][1] + .get("source") + .is_none() + ); + assert_eq!( + created_json["resolved_environments"]["linux/amd64"]["packages"][0]["version"], + "2.9.0+cu130" + ); + assert_eq!( + created_json["resolved_environments"]["linux/arm64"]["packages"], + serde_json::json!([]) + ); assert_eq!( client.describe(id).await.unwrap().status, QueryStatus::Finished @@ -3253,6 +3313,19 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(described.max_concurrency(), Some(4)); assert_eq!(described.row_timeout_seconds(), Some(8.0)); assert_eq!(described.result_stability(), Some("input_and_context")); + assert_eq!(described.runtime().unwrap().kind(), "python"); + assert_eq!( + described + .resolved_environment() + .unwrap() + .provenance + .as_ref() + .unwrap() + .torch_version + .as_deref(), + Some("torch==2.9.0+cu130") + ); + assert_eq!(described.resolved_environments().len(), 2); let described_json: serde_json::Value = serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap(); assert_eq!(described_json["image"].get("models"), expected_models); @@ -3279,6 +3352,16 @@ async fn function_creation_and_description_use_sql_query_handles() { listed.items[0].result_stability(), Some("input_and_context") ); + assert_eq!(listed.items[0].runtime().unwrap().kind(), "python"); + assert_eq!( + listed.items[0] + .resolved_environment() + .unwrap() + .warnings + .len(), + 1 + ); + assert_eq!(listed.items[0].resolved_environments().len(), 2); let listed_json: serde_json::Value = serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap(); assert_eq!(listed_json["image"].get("models"), expected_models); @@ -3293,6 +3376,58 @@ async fn function_creation_and_description_use_sql_query_handles() { } } +#[tokio::test] +async fn function_creation_refresh_lock_is_forwarded_only_when_true() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + for (refresh_lock, expect_field) in [(false, false), (true, true)] { + let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + if refresh_lock { + request_json["refresh_lock"] = serde_json::json!(true); + } + let request = + crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string()) + .unwrap(); + assert_eq!(request.refresh_lock, refresh_lock); + let result = RecordBatch::try_from_iter(vec![( + "definition", + Arc::new(StringArray::from(vec![VERSION.to_string()])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: false, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|request| -> http::Response { + panic!("unexpected REST request: {}", request.url().path()); + }) + .with_sql_client(client.clone()); + let job = db.create_function_async(request, &[]).await.unwrap(); + job.wait().await.unwrap(); + let seen = statements.lock().unwrap(); + let encoded = seen[0] + .strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#) + .unwrap() + .strip_suffix('\'') + .unwrap(); + let sent: serde_json::Value = serde_json::from_str(&encoded.replace("''", "'")).unwrap(); + assert_eq!(sent.get("refresh_lock").is_some(), expect_field); + if expect_field { + assert_eq!(sent["refresh_lock"], serde_json::json!(true)); + } + drop(seen); + shutdown.send(()).unwrap(); + } +} + #[tokio::test] async fn function_creation_rejects_invalid_execution_controls_before_sql() { const REQUEST: &str = include_str!( From dc9eb269b15bae731e3d99ddcf67f61723fc703c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:30:47 +0800 Subject: [PATCH 03/11] feat(python): support map and decimal Function signatures (#5031) Python Function declarations reject Arrow map and decimal types before registration. Accept `dict[str, T]`, nullable map values, explicit Arrow maps, and `Annotated[Decimal, pa.decimal128/256(...)]` using the existing canonical JSON representation. Preserve map key/value nullability and decimal precision/scale; reject unsupported map keys, sorted maps, nested Blob values, and a bare Decimal without precision/scale. This is the SDK map/decimal portion of ENT-3414. Server validation and SQL support are separate changes; older servers can still reject these signatures. Nullable scalar output support remains separate in #5030. Validation: 129 Function signature tests passed; 30 documentation tests passed with one existing skip. Ruff format/lint and diff checks passed. Python tests used the existing Python 3.13 environment and prebuilt native extension with this Python source overlaid; no Rust build or remote-server execution was performed. --- docs/web/management/function.mdx | 40 +++++ python/python/lancedb/functions.py | 85 ++++++++-- .../tests/test_first_class_function_slice2.py | 153 +++++++++++++++++- 3 files changed, 267 insertions(+), 11 deletions(-) diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index efcbcc799..41e47dee1 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -139,6 +139,46 @@ compound temporal representation cannot read those signatures. A deployment must include the corresponding Lance Namespace and Sophon support; this client-side declaration does not add server support. +### Maps and decimals {#maps-decimals} + +A `dict[str, T]` annotation declares an Arrow map with a non-nullable `utf8` +key. A plain `T` value is non-nullable; annotate `dict[str, Optional[T]]` for +nullable values. An explicit `pa.map_(...)` schema preserves the value field's +own `nullable` flag: + +```python +@function +def word_counts(text: str) -> dict[str, int]: + ... +``` + +Map keys must be non-nullable `utf8`; `keys_sorted=True` is not supported, and +Blob v2 values inside a map are not supported. + +`Decimal` carries no precision or scale by itself, so a bare `Decimal` +annotation is rejected. Declare both explicitly with `Annotated`, or use an +explicit Arrow schema: + +```python +from decimal import Decimal +from typing import Annotated + +import pyarrow as pa + + +@function +def add_tax( + amount: Annotated[Decimal, pa.decimal128(12, 2)], +) -> Annotated[Decimal, pa.decimal128(12, 2)]: + ... +``` + +`decimal128` and `decimal256` keep the declared precision and scale in the +canonical signature; no default is chosen. Map and decimal signatures are sent +as canonical Arrow JSON. A deployment must support those types; an older +Enterprise server may reject the registration, and this client-side +declaration does not add server support. + ## Connect and create a table {#table} The remaining steps run against your Enterprise deployment. Replace the database diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index ecbc697d1..548129211 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -30,6 +30,7 @@ import types import warnings from collections.abc import Mapping, Sequence from datetime import date, datetime, timedelta +from decimal import Decimal from pathlib import Path from typing import ( Annotated, @@ -1378,6 +1379,13 @@ 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: @@ -1453,8 +1461,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}") @@ -1483,9 +1512,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, and timedelta has no unit of - # its own; the Annotated metadata supplies those types. - if base is dict or get_origin(base) is dict or base is timedelta: + # 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) @@ -1514,6 +1549,13 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: # 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 " @@ -1527,6 +1569,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}") @@ -2847,7 +2904,13 @@ def function( deployment must accept nullable scalar outputs; an older server rejects the registration. Every named-struct field may be nullable; Enterprise preserves the struct's validity when the result is expanded into sibling - columns. Bare ``datetime`` keeps its existing ``timestamp[us]`` default + 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 @@ -2958,10 +3021,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. 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. + 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 diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 6dcc0bbbe..dbc574e88 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -19,6 +19,7 @@ import sys import typing import urllib.parse import warnings +from decimal import Decimal from typing import Annotated, Optional import pyarrow as pa @@ -1054,7 +1055,6 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): == "large_list" ) for outside in [ - pa.decimal128(10, 2), pa.binary(4), pa.time32("s"), pa.time64("us"), @@ -1531,6 +1531,157 @@ def test_duration_annotation_and_explicit_schema_serialization(): 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)]) From e2f836da99deacb6b1a3a9ca7acc1222e7d39d3f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 14 Nov 2026 22:43:56 +0800 Subject: [PATCH 04/11] feat: expose per-call merge retry controls in Python and Node (#5015) Python and Node callers could not disable precommit retries for one merge without changing the connection. Add `execute(..., retries=0)` for Python sync/async and `execute(data, { retries: 0 })` for TypeScript, forwarding into the existing Rust control without persisting the override. Ambiguous 5xx outcomes remain non-replayable; permitted merge retries now log status and attempt at WARN, and the API docs explain retry budgets and timeout boundaries. Validation at `6001300` passed 70 Python HTTP cases, 36 Node HTTP cases, 14 local merge regressions per binding, and 34 scoped Rust tests, with rebuilt native extensions, TypeScript compilation, Clippy, scoped formatting/lint, and generated API docs. The public API and feature diff are unchanged after integrating main and the reviewed ingestion guide; that binding evidence is retained. Focused merged-tree validation additionally passed 267 Rust merge/retry/provenance cases and the CI fixtures. Existing root Ruff issues in docs/web-tests remain; local fixtures do not establish live proxy/server cancellation behavior. Refs #4256 and OSS-2370. --- .../js/interfaces/WriteExecutionOptions.md | 23 +++ docs/web/ingestion/merge-insert.mdx | 7 + nodejs/__test__/remote.test.ts | 157 +++++++++++++++++ nodejs/__test__/table.test.ts | 3 +- nodejs/lancedb/merge.ts | 28 +++- nodejs/src/merge.rs | 9 +- python/python/lancedb/_lancedb.pyi | 6 + python/python/lancedb/merge.py | 23 ++- python/python/lancedb/remote/table.py | 3 +- python/python/lancedb/table.py | 6 +- python/python/tests/test_remote_db.py | 158 ++++++++++++++++++ python/python/tests/test_table.py | 5 +- python/src/table.rs | 5 + rust/lancedb/src/remote/table.rs | 10 ++ 14 files changed, 433 insertions(+), 10 deletions(-) diff --git a/docs/src/js/interfaces/WriteExecutionOptions.md b/docs/src/js/interfaces/WriteExecutionOptions.md index 0ca796b6b..9c9be4489 100644 --- a/docs/src/js/interfaces/WriteExecutionOptions.md +++ b/docs/src/js/interfaces/WriteExecutionOptions.md @@ -8,6 +8,26 @@ ## Properties +### retries? + +```ts +optional retries: number; +``` + +Override the remote retry budget for this execution only (an integer from +0 to 255). Use `execute(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 `clientConfig.retryConfig` +([RetryConfig](RetryConfig.md)). 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. + +*** + ### timeoutMs? ```ts @@ -24,3 +44,6 @@ the second attempt will be cancelled after 10 seconds, hitting the first attempt will not be cancelled. When this is set, the timeout is enforced on all attempts, including the first. +For remote tables this 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. diff --git a/docs/web/ingestion/merge-insert.mdx b/docs/web/ingestion/merge-insert.mdx index 8106e7706..2d6fd8470 100644 --- a/docs/web/ingestion/merge-insert.mdx +++ b/docs/web/ingestion/merge-insert.mdx @@ -221,6 +221,13 @@ and check inserted or deleted counts when the SDK returns them. Repeating a merge is only safe when its keys, conditions and update values produce the intended result on retry. +To override the transport retry budget for one merge, pass `retries=0` to +Python's synchronous or asynchronous `builder.execute(data, retries=0)`, or +use TypeScript's `builder.execute(data, { retries: 0 })`. The override applies +only to that execution. A larger budget does not make an ambiguous 5xx result +safe to replay. See [write retry boundaries](/ingestion/insert#performance) +for the distinction between retryable failures and an unknown commit outcome. + ### Embeddings and expression predicates {#advanced} When a table uses an [embedding definition](/embedding), behavior depends on diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 3e8d5a79b..215df992d 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -542,6 +542,163 @@ describe("remote connection", () => { expect(attempts).toBe(scenario.attempts); }); + it.each( + [409, 429, 502, 503, 504].flatMap((status) => + [undefined, 0, 2].flatMap((retries) => + [[], ["analytics", "features"]].map((namespacePath) => ({ + status, + retries, + namespacePath, + })), + ), + ), + )("applies per-call merge retries: %j", async (scenario) => { + let attempts = 0; + const identifier = [...scenario.namespacePath, "items"].join("$"); + const succeeds = + [409, 429].includes(scenario.status) && scenario.retries !== 0; + await withMockDatabase( + (req, res) => { + const url = new URL(req.url ?? "", "http://localhost"); + if (url.pathname === `/v1/table/${identifier}/describe/`) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + try { + expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`); + expect(url.searchParams.get("use_index")).toBe("false"); + expect(req.headers["x-request-timeout-ms"]).toBe("10000"); + // Rust compresses the batches; Arrow JS can inspect the schema without a codec. + const reader = RecordBatchReader.from(Buffer.concat(chunks)).open(); + expect(reader.schema.fields.map((field) => field.name)).toEqual([ + "id", + ]); + } finally { + attempts++; + res + .writeHead(attempts === 1 ? scenario.status : 200) + .end('{"version":2}'); + } + }); + }, + async (db) => { + const table = await db.openTable("items", scenario.namespacePath); + const merge = table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .useIndex(false); + const result = merge.execute([{ id: 1n }], { + timeoutMs: 10_000, + retries: scenario.retries, + }); + if (succeeds) { + await expect(result).resolves.toMatchObject({ version: 2 }); + } else { + await expect(result).rejects.toThrow(); + } + }, + { + clientConfig: { + retryConfig: { + retries: 3, + statuses: [409, 429, 502, 503, 504], + backoffFactor: 0, + backoffJitter: 0, + }, + }, + }, + ); + expect(attempts).toBe(succeeds ? 2 : 1); + }); + + it("isolates merge retry overrides across reused builders and reads", async () => { + let attempts = 0; + let readAttempts = 0; + await withMockDatabase( + (req, res) => { + if (req.url?.endsWith("/describe/")) { + res.writeHead(200).end( + JSON.stringify({ + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int64" }, nullable: true }, + ], + }, + }), + ); + return; + } + req.resume(); + req.on("end", () => { + if (req.url?.endsWith("/count_rows/")) { + readAttempts++; + res.writeHead(readAttempts % 2 ? 429 : 200).end("1"); + } else { + attempts++; + res + .writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200) + .end('{"version":2}'); + expect(req.url).toContain("/merge_insert/"); + } + }); + }, + async (db) => { + const table = await db.openTable("items"); + const merge = table.mergeInsert("id").whenNotMatchedInsertAll(); + for (const retries of [ + -1, + 256, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + await expect( + merge.execute([{ id: 1n }], { retries }), + ).rejects.toThrow("retries must be an integer between 0 and 255"); + } + expect(attempts).toBe(0); + await expect( + merge.execute([{ id: 1n }], { retries: 0 }), + ).rejects.toThrow(); + expect(attempts).toBe(1); + await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({ + version: 2, + }); + await expect( + merge.execute([{ id: 1n }], { retries: 255 }), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(5); + await expect(table.countRows()).resolves.toBe(1); + expect(readAttempts).toBe(2); + await expect( + table + .mergeInsert("id") + .whenNotMatchedInsertAll() + .execute([{ id: 1n }]), + ).resolves.toMatchObject({ version: 2 }); + expect(attempts).toBe(7); + }, + { + clientConfig: { + retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 }, + }, + }, + ); + }); + it("should accept partial connection options", async () => { await connect("db://test", { apiKey: "fake", diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index e97b32e78..99c58a8c9 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -938,7 +938,8 @@ describe("merge insert", () => { .mergeInsert("a") .whenMatchedUpdateAll() .whenNotMatchedInsertAll() - .execute(newData, { timeoutMs: 10_000 }); + .useIndex(false) + .execute(newData, { timeoutMs: 10_000, retries: 0 }); expect(mergeInsertRes).toHaveProperty("version"); expect(mergeInsertRes.version).toBe(2); expect(mergeInsertRes.numInsertedRows).toBe(1); diff --git a/nodejs/lancedb/merge.ts b/nodejs/lancedb/merge.ts index 7bb36e678..7d95d4a36 100644 --- a/nodejs/lancedb/merge.ts +++ b/nodejs/lancedb/merge.ts @@ -127,6 +127,14 @@ export class MergeInsertBuilder { data: Data, execOptions?: Partial, ): Promise { + if ( + execOptions?.retries !== undefined && + (!Number.isInteger(execOptions.retries) || + execOptions.retries < 0 || + execOptions.retries > 255) + ) { + throw new Error("retries must be an integer between 0 and 255"); + } let schema: Schema; if (this.#schema instanceof Promise) { schema = await this.#schema; @@ -140,7 +148,7 @@ export class MergeInsertBuilder { } const buffer = await fromDataToBuffer(data, undefined, schema); - return await this.#native.execute(buffer); + return await this.#native.execute(buffer, execOptions?.retries); } } @@ -156,6 +164,24 @@ export interface WriteExecutionOptions { * first attempt will not be cancelled. * * When this is set, the timeout is enforced on all attempts, including the first. + * For remote tables this 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. */ timeoutMs?: number; + + /** + * Override the remote retry budget for this execution only (an integer from + * 0 to 255). Use `execute(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 `clientConfig.retryConfig` + * ({@link 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. + */ + retries?: number; } diff --git a/nodejs/src/merge.rs b/nodejs/src/merge.rs index ccff2a689..86901c04f 100644 --- a/nodejs/src/merge.rs +++ b/nodejs/src/merge.rs @@ -65,12 +65,17 @@ impl NativeMergeInsertBuilder { } #[napi(catch_unwind)] - pub async fn execute(&self, buf: Buffer) -> napi::Result { + pub async fn execute(&self, buf: Buffer, retries: Option) -> napi::Result { let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| { napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e))) })?; - let this = self.clone(); + let mut this = self.clone(); + if let Some(retries) = retries { + let retries = u8::try_from(retries) + .map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?; + this.inner.retries(retries); + } let res = this.inner.execute(data).await.map_err(|e| { napi::Error::from_reason(format!( diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a87b82a21..a86bae9d5 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -565,6 +565,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: ... diff --git a/python/python/lancedb/merge.py b/python/python/lancedb/merge.py index 49f4793ed..c861414aa 100644 --- a/python/python/lancedb/merge.py +++ b/python/python/lancedb/merge.py @@ -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 + ) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index b5d97eb62..818d2a257 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -945,9 +945,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") diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 45b2eb4f6..4a713da06 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2810,6 +2810,7 @@ class Table(ABC): new_data: DATA, on_bad_vectors: OnBadVectorsType, fill_value: float, + retries: Optional[int] = None, ) -> MergeResult: ... @abstractmethod @@ -5443,9 +5444,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 @@ -7777,6 +7779,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 +7811,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: diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index fc5b5df73..f404e36f7 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -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 = [] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index ce4f57c48..4b26a9003 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -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 ) diff --git a/python/src/table.rs b/python/src/table.rs index f5270a594..25a99e5db 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -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, ) -> PyResult> { let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; let on = parameters.on.iter().map(|s| s.as_str()).collect::>(); @@ -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); } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 29f3ab50e..2224203cf 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3707,7 +3707,17 @@ impl BaseTable for RemoteTable { return Ok(merge_result); } Err(err) if rescannable && self.is_retryable_write_error(&err) => { + let status = err.status_code(); retry_counter.increment_from_error(err)?; + log::warn!( + "Retrying merge insert {} after status {:?}; attempt {}", + retry_counter.request_id, + status.map(|s| s.as_u16()), + u16::from(retry_counter.request_failures) + + u16::from(retry_counter.connect_failures) + + u16::from(retry_counter.read_failures) + + 1, + ); tokio::time::sleep(retry_counter.next_sleep_time()).await; merge = merge.reset_state()?; continue; From e8a8dd1b2a240646b39ecfc848b1c3dd4a0701fc Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 14 Nov 2026 16:55:42 -0800 Subject: [PATCH 05/11] feat(sql): use server-issued catalog listing tokens (#5026) Migrates SQL-backed catalog listing APIs to `LIMIT ... FROM ''` and server-issued Arrow continuation metadata. Namespace-specific APIs send an explicit `IN` schema clause, including `IN "public"` for root, so raw SQL can default to all namespaces. ```sql SHOW VIEWS LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100; SHOW VIEWS IN team$ml LIMIT 100 FROM ''; SHOW VIEWS IN other_db.team$ml LIMIT 100; ``` SDK clients forward opaque tokens unchanged, preserve empty continuations, and decode identifier columns by name. Removes legacy cursor reconstruction and updates the SQL reference and Python Flight fixture. Public docs cover optional direct schema paths, all-namespace defaults, and the shared pagination syntax across every catalog listing. --- docs/web/docs.json | 1 + docs/web/management/function.mdx | 4 +- docs/web/management/index.mdx | 2 +- docs/web/sql/ddl/database.mdx | 20 +- docs/web/sql/ddl/function.mdx | 37 +- docs/web/sql/ddl/materialized-view.mdx | 25 +- docs/web/sql/ddl/namespace.mdx | 40 +- docs/web/sql/ddl/secret.mdx | 30 +- docs/web/sql/ddl/storage-integration.mdx | 25 +- docs/web/sql/ddl/table.mdx | 20 + docs/web/sql/ddl/view.mdx | 33 +- docs/web/sql/pagination.mdx | 68 +++ .../python/tests/test_storage_integration.py | 30 +- rust/lancedb/src/listing.rs | 8 +- rust/lancedb/src/remote/db.rs | 27 +- rust/lancedb/src/remote/sql/function.rs | 85 +-- .../src/remote/sql/materialized_view.rs | 58 +- rust/lancedb/src/remote/sql/objects.rs | 144 ++++- rust/lancedb/src/remote/sql/secret.rs | 62 +- rust/lancedb/src/remote/sql/view.rs | 62 +- rust/lancedb/src/remote/sql_test.rs | 554 +++++++++--------- .../lancedb/src/remote/storage_integration.rs | 23 - 22 files changed, 663 insertions(+), 695 deletions(-) create mode 100644 docs/web/sql/pagination.mdx diff --git a/docs/web/docs.json b/docs/web/docs.json index c586d4f62..0b26a7fc0 100644 --- a/docs/web/docs.json +++ b/docs/web/docs.json @@ -543,6 +543,7 @@ "group": "SQL Reference", "pages": [ "sql/index", + "sql/pagination", "sql/data-types", { "group": "DDL", diff --git a/docs/web/management/function.mdx b/docs/web/management/function.mdx index 41e47dee1..562de05c6 100644 --- a/docs/web/management/function.mdx +++ b/docs/web/management/function.mdx @@ -280,7 +280,9 @@ let latest = connection.get_function_latest("double", &[]).await?; ```sql SQL icon="database" SHOW FUNCTIONS -SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100) +SHOW FUNCTIONS IN "analytics" LIMIT 100 +SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 +SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 FROM '' DESCRIBE FUNCTION double WITH (version = '1') DESCRIBE FUNCTION double diff --git a/docs/web/management/index.mdx b/docs/web/management/index.mdx index fbef65756..50f6e7507 100644 --- a/docs/web/management/index.mdx +++ b/docs/web/management/index.mdx @@ -85,7 +85,7 @@ enables them; the SDK methods send the view's SQL query to the deployment. See | --- | --- | --- | --- | | create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` | | get | `get_function` | -- | `DESCRIBE FUNCTION` | -| list | `list_functions` | -- | `SHOW FUNCTIONS` | +| list | `list_functions` | -- | `SHOW FUNCTIONS HISTORY` | | drop | `drop_function` | -- | `DROP FUNCTION` | Enterprise A function runs on the server, and only on diff --git a/docs/web/sql/ddl/database.mdx b/docs/web/sql/ddl/database.mdx index e8cdb55bc..f84d4cfb9 100644 --- a/docs/web/sql/ddl/database.mdx +++ b/docs/web/sql/ddl/database.mdx @@ -57,15 +57,21 @@ properties and requires system `USAGE`. ## SHOW DATABASES {#show} - -```sql SQL icon="database" -SHOW DATABASES +```sql +SHOW DATABASES LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; ``` - -Returns a sorted `name` column containing the databases the caller has -`USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters -are unsupported. +Returns one non-null `name` column, sorted by database name and filtered to +databases the caller has `USAGE` on, including `system` when permitted. +Databases are above namespaces, so this command does not accept `IN` or +return a `namespace_path` column. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## ATTACH DATABASE {#attach} diff --git a/docs/web/sql/ddl/function.mdx b/docs/web/sql/ddl/function.mdx index 55e2d6fe7..691118026 100644 --- a/docs/web/sql/ddl/function.mdx +++ b/docs/web/sql/ddl/function.mdx @@ -135,20 +135,33 @@ from it. ## SHOW FUNCTIONS {#show} - -```sql SQL icon="database" -SHOW FUNCTIONS -SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100) -SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100) +```sql +SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100; +SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -`SHOW FUNCTIONS` returns the highest published numeric revision for each name. -Add `HISTORY` to list every published revision, as Python's `list_functions()` -does. Rows are ordered by name and numeric revision, so `2` comes before `10`. -`after_name` and `after_version` must be supplied together for keyset pagination. -`limit` bounds -the response; `include_definition = false` omits the optional definition JSON. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +`SHOW FUNCTIONS` lists each function once. Add `HISTORY` to list every +published revision with its metadata and definition, as `list_functions()` +does. History uses the same pagination suffix; numeric revision order is +encoded in the token, so revision `2` precedes `10`. + +```sql +SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100; +SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100 FROM ''; +``` + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP FUNCTION {#drop} diff --git a/docs/web/sql/ddl/materialized-view.mdx b/docs/web/sql/ddl/materialized-view.mdx index a2453ba01..a2a5024f6 100644 --- a/docs/web/sql/ddl/materialized-view.mdx +++ b/docs/web/sql/ddl/materialized-view.mdx @@ -70,16 +70,25 @@ automatic execution needs the same server-side switch enabled. Omitting ## SHOW MATERIALIZED VIEWS {#show} - -```sql SQL icon="database" -SHOW MATERIALIZED VIEWS +```sql +SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100; +SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - - -This asks the server for its views, as the SDK's `list_materialized_views` does -on a `db://` connection. - +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +The listing contains identifiers; use `DESCRIBE MATERIALIZED VIEW` for its defining query and refresh metadata. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## Refreshing one {#refresh} diff --git a/docs/web/sql/ddl/namespace.mdx b/docs/web/sql/ddl/namespace.mdx index 8f446f1e7..14391ac18 100644 --- a/docs/web/sql/ddl/namespace.mdx +++ b/docs/web/sql/ddl/namespace.mdx @@ -17,7 +17,7 @@ backtick-quoted identifier with `$` between components, such as one path component, relative to an explicit parent schema or the session's current schema -- it cannot contain `$` or be qualified with a database. -`SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete +For single-object commands, `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete schema identifier. Names are lowercased unless quoted. ## CREATE SCHEMA and CREATE NAMESPACE {#create} @@ -126,27 +126,30 @@ Requires `USAGE` on the database and the namespace. ## SHOW SCHEMAS and SHOW NAMESPACES {#show} - -```sql SQL icon="database" -SHOW SCHEMAS -SHOW NAMESPACES -SHOW NAMESPACES IN analytics.team +```sql +SHOW SCHEMAS LIMIT 100; +SHOW SCHEMAS LIMIT 100 FROM ''; +SHOW NAMESPACES IN analytics.team LIMIT 100; +SHOW NAMESPACES IN analytics.team LIMIT 100 FROM ''; ``` - -`SHOW SCHEMAS` returns complete paths in the current database, recursively, -including `public` when the caller can use it. It does not accept `IN`. +Both commands return two non-null string columns: `namespace_path`, the +parent path as a compact JSON array, and `name`, the unqualified child name. +Results are ordered by parent path components, then name, and omit namespaces +the caller cannot use. -`SHOW NAMESPACES` lists only immediate child names under the session's -current schema. `IN` selects a different parent schema, optionally in -another database -- use `IN public` for the current database's root, or -`IN analytics.public` for another database's root. A missing parent is an -error. +`SHOW SCHEMAS` and `SHOW NAMESPACES` are equivalent listings. Without `IN`, +both list recursively in the current database, include the implicit `public` +root, and ignore the session namespace. With `IN`, both list immediate children +of the selected parent. A schema path can appear directly: `IN team$features`; +a database qualifier is optional. `IN public` selects the current database root, +and `IN analytics.public` selects another database's root. -Both forms return a sorted `name` column and omit namespaces the caller -cannot use. Large listings that exceed 10,000 namespaces, or recursive -listings deeper than 32 levels, return an error suggesting a narrower -listing. +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP SCHEMA and DROP NAMESPACE {#drop} @@ -187,7 +190,6 @@ with `IF EXISTS`. Inspect a cascade drop's child jobs with | `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` | | `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` | | `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` | -| `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` | ## What to read next {#next} diff --git a/docs/web/sql/ddl/secret.mdx b/docs/web/sql/ddl/secret.mdx index 922dec247..15039c6c7 100644 --- a/docs/web/sql/ddl/secret.mdx +++ b/docs/web/sql/ddl/secret.mdx @@ -98,21 +98,25 @@ picked up by every Function still bound to that name. ## SHOW SECRETS {#show} - -```sql SQL icon="database" -SHOW SECRETS -SHOW SECRETS IN platform -SHOW SECRETS IN analytics.`ml$vision` -SHOW SECRETS IN public -SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50 +```sql +SHOW SECRETS IN analytics.`team$ml` LIMIT 100; +SHOW SECRETS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -Lists the Secret names in one namespace as a sorted `name` column. Without -`IN`, it lists the session's namespace; `IN public` lists the root. `WHERE -name > ''` pages past the last name already seen, and `LIMIT` -bounds the page size; `WHERE` must compare `name` with `>`. Requires -`USAGE` on the database and the namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +Secret listings contain no values or Secret metadata. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DESCRIBE SECRET {#describe} diff --git a/docs/web/sql/ddl/storage-integration.mdx b/docs/web/sql/ddl/storage-integration.mdx index 9444824ac..de64ba4e5 100644 --- a/docs/web/sql/ddl/storage-integration.mdx +++ b/docs/web/sql/ddl/storage-integration.mdx @@ -194,16 +194,25 @@ only the reference naming it. ## SHOW STORAGE INTEGRATIONS {#show} - -```sql SQL icon="database" -SHOW STORAGE INTEGRATIONS -SHOW STORAGE INTEGRATIONS IN platform -LIST STORAGE INTEGRATIONS +```sql +SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100; +SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` - -`LIST` is an alias for `SHOW` here. Returns one `name` column; `IN` -narrows the listing to one namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +`LIST STORAGE INTEGRATIONS` is an exact alias, including pagination. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## DROP STORAGE INTEGRATION {#drop} diff --git a/docs/web/sql/ddl/table.mdx b/docs/web/sql/ddl/table.mdx index c8c42d4e0..d2196b93a 100644 --- a/docs/web/sql/ddl/table.mdx +++ b/docs/web/sql/ddl/table.mdx @@ -268,3 +268,23 @@ deployment stores its catalog. See Renaming, retyping and dropping columns from the SDK. + +## SHOW TABLES {#show} + +```sql +SHOW TABLES IN analytics.`team$ml` LIMIT 100; +SHOW TABLES IN analytics.`team$ml` LIMIT 100 FROM ''; +``` + +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. + +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). diff --git a/docs/web/sql/ddl/view.mdx b/docs/web/sql/ddl/view.mdx index 3d94292ab..38fd37e30 100644 --- a/docs/web/sql/ddl/view.mdx +++ b/docs/web/sql/ddl/view.mdx @@ -81,29 +81,22 @@ was none to begin with. ## Listing {#listing} ```sql -SHOW VIEWS -SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100 +SHOW VIEWS IN analytics.`team$ml` LIMIT 100; +SHOW VIEWS IN analytics.`team$ml` LIMIT 100 FROM ''; ``` -`SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to -the selected namespace. +Returns two non-null string columns: `namespace_path`, a compact JSON array +of parent namespace components (`[]` for root), and `name`, the unqualified +object name. Omitting `IN` lists all authorized namespaces in the current database; +`IN team$ml` selects that exact path without a database qualifier; `IN public` selects +the current database's root. Listings require the relevant database and +namespace `USAGE` privileges. -Object commands retain their small results in shared storage even when general -query-result copying is disabled, so asynchronous polling can use any query node. - -Views and tables share a namespace, and both are things you can query. The -catalog distinguishes them: - -| | | -| --- | --- | -| view names | the views in the database | -| table names | the tables | -| relation names | everything queryable (both) | - -Use the relation listing when the question is "what can I select from," and the -separate listings when the distinction matters: before dropping, for -instance, since dropping a view removes only the saved query while dropping a -table removes data. +Page through results using `LIMIT n [FROM '']`. Read the opaque +`lancedb.next_page_token` from the Arrow result schema metadata and pass it back +unchanged with the same object type and scope. Stop when no token is returned; +a short or empty page can still carry a continuation. See +[catalog listing pagination](/sql/pagination). ## Choosing between a view and a materialized view {#choosing} diff --git a/docs/web/sql/pagination.mdx b/docs/web/sql/pagination.mdx new file mode 100644 index 000000000..d6649ebfe --- /dev/null +++ b/docs/web/sql/pagination.mdx @@ -0,0 +1,68 @@ +--- +title: "Catalog listing pagination" +description: "Use one continuation-token syntax for SQL catalog listings." +--- + +Catalog `SHOW` statements share one pagination suffix: + +```sql +SHOW [IN ] [LIMIT [FROM '']]; +``` + +This applies to tables, views, materialized views, functions and function +history, secrets, storage integrations, namespaces/schemas, and databases. + +```sql +SHOW TABLES LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100; +SHOW TABLES IN team$ml LIMIT 100 FROM ''; +SHOW TABLES IN analytics.team$ml LIMIT 100; +SHOW DATABASES LIMIT 100 FROM ''; +``` + +## Namespace scope + +`IN` is optional. Without it, listings include root and every authorized +namespace in the current database, regardless of the session's default namespace. +With `IN`, objects are listed only in that exact namespace. The scope accepts a +schema directly: `IN team$ml` means the absolute namespace path `["team", "ml"]` +in the current database. Use `IN public` for root, or `IN other_db.team$ml` to +select a different database. Quote schema identifiers containing punctuation or +mixed case, for example `IN "Team$ML"`. + +`SHOW SCHEMAS` and `SHOW NAMESPACES` use the same rules: without `IN` they +include all namespace paths and the public root; with `IN` they list the +selected parent's immediate children. `SHOW DATABASES` remains global and +does not accept `IN`. + +SDK APIs that take a namespace send an explicit `IN` clause and continue to +list that one namespace. + +## Continuation metadata + +The Arrow result schema carries `lancedb.next_page_token` when more results +remain. Pass that opaque value unchanged in `FROM` on the next request. +The token identifies the object type, database, namespace scope, and complete +position, including namespace path and any numeric revision. It cannot be +reused with another object type or scope. + +The token is metadata, not an additional result column or a synthetic row. +Namespace-scoped object listings contain `namespace_path` and `name`; +databases contain only `name`. Function history retains revision metadata. +SDK listing APIs expose this server-issued value as the page's `page_token`. + +Continue until no token is returned. A short or empty page may still have a +token. Pages observe the live catalog; continuation does not create a snapshot. + +## Page size and ordering + +The default page limit is 1,000, with a maximum of 10,000. `LIMIT 0` returns +no rows. Object catalogs order identifiers by namespace path components and +unqualified name; database names are ordered by name. Table page boundaries +follow native catalog order, which may differ from logical name order for +directory-backed tables; table names are sorted within each returned page. Function history uses +numeric revision order within each name. The token preserves that complete +position, including when names repeat in different namespaces. + +The old name-comparison `WHERE` and Function `WITH` pagination forms are no +longer supported. Use the same `LIMIT ... FROM ...` suffix for every listing. diff --git a/python/python/tests/test_storage_integration.py b/python/python/tests/test_storage_integration.py index ff7995ab3..84052e54c 100644 --- a/python/python/tests/test_storage_integration.py +++ b/python/python/tests/test_storage_integration.py @@ -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 diff --git a/rust/lancedb/src/listing.rs b/rust/lancedb/src/listing.rs index a0f6e5d5e..a5541b629 100644 --- a/rust/lancedb/src/listing.rs +++ b/rust/lancedb/src/listing.rs @@ -19,7 +19,10 @@ pub struct ListingOptions { /// Starting continuation token; `None` starts at the beginning. pub page_token: Option, /// Maximum results per request, not a limit on the entire listing. - /// `None` uses the backend default. Must be between 1 and `i32::MAX`. + /// `None` uses the backend default. SQL-backed catalog listings default to + /// 1,000 rows and accept 1 through 10,000. The public listing API rejects + /// zero; SQL statements can separately use `LIMIT 0`. Other backends may + /// impose different limits. pub page_limit: Option, } @@ -31,6 +34,9 @@ impl ListingOptions { } /// Set the maximum number of results requested per page. + /// + /// SQL-backed catalog listings accept 1 through 10,000. A server can return + /// fewer rows, including none, with a continuation token. pub fn page_limit(mut self, limit: u32) -> Self { self.page_limit = Some(limit); self diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 7100e1b04..1a825bebc 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1008,30 +1008,9 @@ impl Database for RemoteDatabase { namespace_path: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace_path)?; - let result = self - .execute_query_async(ExecuteQueryRequest { - query: "SHOW STORAGE INTEGRATIONS".into(), - default_namespace_path: namespace_path.to_vec(), - parameters: None, - }) - .await?; - let mut names = - integration_sql::decode_names(&result.reader().await?.try_collect::>().await?)?; - if let Some(token) = options.page_token { - names.retain(|name| name > &token); - } - let mut page_token = None; - if let Some(limit) = options.page_limit - && names.len() > limit as usize - { - names.truncate(limit as usize); - page_token = names.last().cloned(); - } - Ok(ListingPage { - items: names, - page_token, - }) + self.sql_client()? + .list_names("SHOW STORAGE INTEGRATIONS", namespace_path, options) + .await } async fn drop_storage_integration(&self, name: &str, namespace_path: &[String]) -> Result<()> { diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index 19a1a6cbc..f0ebf1894 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -14,7 +14,6 @@ use crate::{ listing::{ListingOptions, ListingPage}, utils::{validate_function_name, validate_namespace}, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; /// The SQL result of one Function drop, before the public boolean wrapper /// discards the advisory details. @@ -89,81 +88,17 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid = || Error::InvalidInput { - message: "invalid function page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid())?; - let (database, prefix, path, name, version): ( - String, - Option, - Vec, - String, - String, - ) = serde_json::from_slice(&bytes).map_err(|_| invalid())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid()); - } - Some((name, version)) - } else { - None - }; - let mut sql_options = vec![ - format!("limit = {}", u64::from(limit) + 1), - "include_definition = true".to_owned(), - ]; - if let Some((name, version)) = &after { - sql_options.push(format!("after_name = {}", literal(name))); - sql_options.push(format!("after_version = {}", literal(version))); - } - let mut items: Vec = self - .object_job( - ExecuteQueryRequest { - query: format!("SHOW FUNCTIONS HISTORY WITH ({})", sql_options.join(", ")), - default_namespace_path: namespace.to_vec(), - parameters: None, - }, - |batches| { - strings(&batches, "definition")? - .into_iter() - .map(|value| { - serde_json::from_str(&value).map_err(|error| Error::Runtime { - message: error.to_string(), - }) - }) - .collect::>>() - }, - ) - .await? - .wait() + let (batches, page_token) = self + .listing_page("SHOW FUNCTIONS HISTORY", namespace, options) .await?; - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let last = items.last().unwrap(); - let bytes = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - last.name(), - last.version(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(bytes)) - } else { - None - }; + let items = strings(&batches, "definition")? + .into_iter() + .map(|value| { + serde_json::from_str(&value).map_err(|error| Error::Runtime { + message: error.to_string(), + }) + }) + .collect::>>()?; Ok(ListingPage { items, page_token }) } pub(in crate::remote) async fn drop_function_outcome( diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index e982afac7..c8e1aa5c3 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use arrow_array::{Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::TryStreamExt; use super::SqlClient; @@ -157,60 +156,7 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid materialized-view page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (database, prefix, path, last): (String, Option, Vec, String) = - serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!( - "SHOW MATERIALIZED VIEWS{after} LIMIT {}", - u64::from(limit) + 1 - ), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&batch, "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW MATERIALIZED VIEWS", namespace, options) + .await } } diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index ff87e0000..2ffb08936 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -1,42 +1,118 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::SqlClient; +use super::{SqlClient, materialized_view::quote_identifier}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, job::Job, + listing::{ListingOptions, ListingPage}, + utils::validate_namespace, }; -use arrow_array::{Array, ListArray, RecordBatch, StringArray}; +use arrow_array::{Array, LargeStringArray, ListArray, RecordBatch, StringArray, StringViewArray}; use futures::TryStreamExt; use serde::{Serialize, de::DeserializeOwned}; use std::sync::Arc; +const DEFAULT_SQL_LISTING_LIMIT: u32 = 1_000; +const MAX_SQL_LISTING_LIMIT: u32 = 10_000; +const NEXT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.next_page_token"; + +impl SqlClient { + pub(in crate::remote) async fn listing_page( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result<(Vec, Option)> { + validate_namespace(namespace)?; + let limit = options.page_limit.unwrap_or(DEFAULT_SQL_LISTING_LIMIT); + if limit > MAX_SQL_LISTING_LIMIT { + return Err(Error::InvalidInput { + message: format!("page limit must be between 0 and {MAX_SQL_LISTING_LIMIT}"), + }); + } + if options.page_token.as_ref().is_some_and(String::is_empty) { + return Err(Error::InvalidInput { + message: "page token must not be empty".into(), + }); + } + if limit == 0 { + return Ok((Vec::new(), None)); + } + let schema = if namespace.is_empty() { + "public".to_owned() + } else { + namespace.join("$") + }; + let mut statement = format!("{statement} IN {} LIMIT {limit}", quote_identifier(&schema)); + if let Some(token) = options.page_token { + statement.push_str(&format!(" FROM {}", literal(&token))); + } + let query = self + .execute(ExecuteQueryRequest { + query: statement, + default_namespace_path: namespace.to_vec(), + parameters: None, + }) + .await?; + let reader = query.reader().await?; + let token = reader + .schema() + .metadata() + .get(NEXT_PAGE_TOKEN_METADATA_KEY) + .cloned() + .filter(|token| !token.is_empty()); + let batches = reader.try_collect::>().await?; + if batches.iter().map(RecordBatch::num_rows).sum::() > limit as usize { + return Err(Error::Runtime { + message: "SQL listing exceeded its requested page size".into(), + }); + } + Ok((batches, token)) + } + + pub(in crate::remote) async fn list_names( + &self, + statement: &str, + namespace: &[String], + options: ListingOptions, + ) -> Result> { + let (batches, page_token) = self.listing_page(statement, namespace, options).await?; + Ok(ListingPage { + items: strings(&batches, "name")?, + page_token, + }) + } +} + pub(super) fn literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result> { - batches - .iter() - .map(|batch| { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("SQL result is missing UTF-8 column '{name}'"), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: format!("SQL result contains null '{name}'"), - }); - } - Ok(values - .iter() - .map(|value| value.unwrap().to_owned()) - .collect::>()) - }) - .collect::>>() - .map(|rows| rows.into_iter().flatten().collect()) + let mut result = Vec::new(); + for batch in batches { + let column = batch.column_by_name(name).ok_or_else(|| Error::Runtime { + message: format!("SQL result is missing string column '{name}'"), + })?; + if column.null_count() != 0 { + return Err(Error::Runtime { + message: format!("SQL result contains null '{name}'"), + }); + } + if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else if let Some(values) = column.as_any().downcast_ref::() { + result.extend(values.iter().map(|value| value.unwrap().to_owned())); + } else { + return Err(Error::Runtime { + message: format!("SQL result column '{name}' is not a string"), + }); + } + } + Ok(result) } /// Read an optional `List` column. Older servers do not return the @@ -112,9 +188,9 @@ impl SqlClient { #[cfg(test)] mod tests { - use super::string_lists; + use super::{string_lists, strings}; use arrow_array::builder::{ListBuilder, StringBuilder}; - use arrow_array::{ArrayRef, RecordBatch}; + use arrow_array::{ArrayRef, LargeStringArray, RecordBatch, StringArray, StringViewArray}; use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; @@ -126,6 +202,24 @@ mod tests { )])) } + #[test] + fn listing_strings_accept_all_arrow_string_representations() { + for values in [ + Arc::new(StringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(LargeStringArray::from(vec!["a", "z"])) as ArrayRef, + Arc::new(StringViewArray::from(vec!["a", "z"])) as ArrayRef, + ] { + let batch = RecordBatch::try_from_iter(vec![("name", values)]).unwrap(); + assert_eq!(strings(&[batch], "name").unwrap(), ["a", "z"]); + } + let batch = RecordBatch::try_from_iter(vec![( + "name", + Arc::new(StringViewArray::from(vec![Some("a"), None])) as ArrayRef, + )]) + .unwrap(); + assert!(strings(&[batch], "name").is_err()); + } + #[test] fn reads_warnings_after_an_empty_first_batch() { let schema = warning_schema(); diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 6ddc78645..93c2a6c6e 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -10,8 +10,6 @@ use crate::{ utils::{validate_namespace, validate_secret_name}, }; use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use std::sync::Arc; pub(in crate::remote) enum SecretWriteOperation { @@ -135,65 +133,7 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid secret page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "secret" - || database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!("SHOW SECRETS{after} LIMIT {}", u64::from(limit) + 1), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&[batch], "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - "secret", - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW SECRETS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index 513113187..b058269a0 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -9,8 +9,6 @@ use crate::{ utils::{validate_namespace, validate_view_name}, view::ViewDescription, }; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; -use futures::TryStreamExt; use lance_namespace::models::JsonArrowSchema; use std::sync::Arc; #[derive(Clone, serde::Serialize, serde::Deserialize)] @@ -147,64 +145,6 @@ impl SqlClient { namespace: &[String], options: ListingOptions, ) -> Result> { - validate_namespace(namespace)?; - let limit = options.page_limit.unwrap_or(100); - if limit == 0 || limit > i32::MAX as u32 { - return Err(Error::InvalidInput { - message: "page limit must be between 1 and i32::MAX".into(), - }); - } - let invalid_token = || Error::InvalidInput { - message: "invalid view page token for this database or namespace".into(), - }; - let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) { - let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?; - let (kind, database, prefix, path, last): ( - String, - String, - Option, - Vec, - String, - ) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?; - if kind != "view" - || database != self.inner.database - || prefix != self.inner.database_prefix - || path != namespace - { - return Err(invalid_token()); - } - format!(" WHERE name > '{}'", last.replace('\'', "''")) - } else { - String::new() - }; - let query = self - .execute(ExecuteQueryRequest { - query: format!("SHOW VIEWS{after} LIMIT {}", u64::from(limit) + 1), - default_namespace_path: namespace.to_vec(), - parameters: None, - }) - .await?; - let mut reader = query.reader().await?; - let mut items = Vec::new(); - while let Some(batch) = reader.try_next().await? { - items.extend(strings(&[batch], "name")?); - } - let page_token = if items.len() > limit as usize { - items.truncate(limit as usize); - let cursor = serde_json::to_vec(&( - "view", - &self.inner.database, - &self.inner.database_prefix, - namespace, - items.last().unwrap(), - )) - .map_err(|error| Error::Runtime { - message: error.to_string(), - })?; - Some(URL_SAFE_NO_PAD.encode(cursor)) - } else { - None - }; - Ok(ListingPage { items, page_token }) + self.list_names("SHOW VIEWS", namespace, options).await } } diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 5c7ae7673..d7249da9b 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -14,7 +14,6 @@ use arrow_flight::{ FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, }; use arrow_schema::{DataType, Field, Schema}; -use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt}; use tonic::metadata::MetadataMap; @@ -2919,25 +2918,54 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() { assert_rejected_before_submission(None, None, Some(true)).await; } +fn sql_listing_batch(column: &str, values: &[&str], token: Option<&str>) -> RecordBatch { + let mut columns: Vec<(&str, ArrayRef)> = Vec::new(); + if column == "name" { + columns.push(( + "namespace_path", + Arc::new(StringArray::from(vec![ + r#"["team","reports"]"#; + values.len() + ])), + )); + } + columns.push((column, Arc::new(StringArray::from(values.to_vec())))); + let batch = RecordBatch::try_from_iter(columns).unwrap(); + let metadata = token + .map(|token| HashMap::from([("lancedb.next_page_token".to_owned(), token.to_owned())])) + .unwrap_or_default(); + let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata)); + RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap() +} + #[tokio::test] -async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { +async fn remote_mv_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["a", "b'c", "z"])) as ArrayRef, - )]) - .unwrap(); + let token = "server'opaque:token"; + let next_sql = + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); let headers = service.headers.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|request| -> http::Response { - panic!("unexpected REST request: {}", request.url().path()); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; @@ -2948,41 +2976,31 @@ async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() { ) .await .unwrap(); - assert_eq!(first.items, ["a", "b'c"]); - let token = first.page_token.unwrap(); - db.list_materialized_views( - &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(&token), - ) - .await - .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_materialized_views( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); assert_eq!( *statements.lock().unwrap(), [ - "SHOW MATERIALIZED VIEWS LIMIT 3", - "SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3" + "SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2", + next_sql ] ); - assert!( - headers - .lock() - .unwrap() - .iter() - .all(|header| header.namespace_path == "team$reports") - ); - for (path, token) in [(vec![], token), (namespace, "invalid".into())] { - assert!(matches!( - db.list_materialized_views( - &path, - crate::listing::ListingOptions::default().page_token(token) - ) - .await, - Err(Error::InvalidInput { .. }) - )); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } @@ -3123,7 +3141,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() let statements = statements.lock().unwrap(); assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'")); assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\""); - assert_eq!(statements[2], "SHOW STORAGE INTEGRATIONS"); + assert_eq!( + statements[2], + "SHOW STORAGE INTEGRATIONS IN \"platform$aws\" LIMIT 1000" + ); assert_eq!(statements[3], "DROP STORAGE INTEGRATION \"raw\""); assert!(statements[4].contains( "STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"credentials\".\"key\"" @@ -3670,29 +3691,20 @@ async fn secret_description_uses_the_sql_metadata_projection() { } #[tokio::test] -async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { +async fn secret_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["api-key", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW SECRETS LIMIT 3".to_string(), first_result), - ( - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3704,11 +3716,10 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let first = db .list_secrets( &namespace, @@ -3716,90 +3727,144 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() { ) .await .unwrap(); - assert_eq!(first.items, ["api-key", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); let second = db .list_secrets( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) .await .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW SECRETS LIMIT 3", - "SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW SECRETS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - for (path, token) in [ - (vec!["other".to_owned()], token), - (namespace.clone(), "invalid".to_owned()), - ] { - assert!(matches!( - db.list_secrets( - &path, - crate::listing::ListingOptions::default().page_token(token) - ) - .await, - Err(Error::InvalidInput { .. }) - )); - } - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } #[tokio::test] -async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { - let empty = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(Vec::::new())) as ArrayRef, - )]) - .unwrap(); +async fn storage_integration_listing_uses_server_continuation_tokens() { + for defer in [false, true] { + let token = "server'opaque:token"; + let next_sql = + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (client, shutdown) = start_sql_service_with_prefix( + service, + ClientConfig::default(), + Some("tenant/production"), + ) + .await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let namespace = vec!["team".to_owned(), "reports".to_owned()]; + let first = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db + .list_storage_integrations( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(second.items, ["z"]); + assert!(second.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2", + next_sql + ] + ); + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); + } + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn secret_listing_preserves_empty_continuations_and_validates_page_options() { let service = TestSqlService { adaptive: true, defer: true, - result: empty, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &[], Some("continue-empty")), + ), + ( + "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'continue-empty'".to_owned(), + sql_listing_batch("name", &["last"], None), + ), + ]))), ..Default::default() }; let statements = service.statements.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - let page = db .list_secrets( &namespace, - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(""), + crate::listing::ListingOptions::default().page_limit(2), ) .await .unwrap(); assert!(page.items.is_empty()); - assert!(page.page_token.is_none()); - - for limit in [0, i32::MAX as u32 + 1] { + assert_eq!(page.page_token.as_deref(), Some("continue-empty")); + let last = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(page.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items, ["last"]); + assert!(last.page_token.is_none()); + for limit in [10_001, u32::MAX] { assert!(matches!( db.list_secrets( &namespace, @@ -3809,12 +3874,29 @@ async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() { Err(Error::InvalidInput { .. }) )); } - assert_eq!(*statements.lock().unwrap(), ["SHOW SECRETS LIMIT 3"]); + assert!( + db.list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_token("") + ) + .await + .is_err() + ); + let zero = db + .list_secrets( + &namespace, + crate::listing::ListingOptions::default().page_limit(0), + ) + .await + .unwrap(); + assert!(zero.items.is_empty()); + assert!(zero.page_token.is_none()); + assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } #[tokio::test] -async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { +async fn function_listing_uses_server_tokens_for_numeric_revision_pages() { const VERSION: &str = include_str!( "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" ); @@ -3824,74 +3906,65 @@ async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() { let mut tenth: serde_json::Value = serde_json::from_str(VERSION).unwrap(); tenth["version"] = serde_json::json!("10"); let tenth = tenth.to_string(); - let result = RecordBatch::try_from_iter(vec![( - "definition", - Arc::new(StringArray::from(vec![ - VERSION, - second.as_str(), - tenth.as_str(), - ])) as ArrayRef, - )]) - .unwrap(); - let service = TestSqlService { - adaptive: true, - defer: true, - result, - ..Default::default() - }; - service.result_overrides.lock().unwrap().insert( - "SHOW FUNCTIONS HISTORY WITH (limit = 3, include_definition = true, after_name = 'embed', after_version = '2')".into(), - RecordBatch::try_from_iter(vec![("definition", Arc::new(StringArray::from(vec![tenth.as_str()])) as ArrayRef)]).unwrap(), - ); - let statements = service.statements.clone(); - let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; - let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); - }) - .with_sql_client(client); - let first = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default().page_limit(2), - ) - .await - .unwrap(); - assert_eq!( - first - .items - .iter() - .map(|item| item.version()) - .collect::>(), - ["1", "2"] - ); - let token = first.page_token.unwrap(); - let second = db - .list_functions( - &["team".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token.clone()), - ) - .await - .unwrap(); - assert_eq!(second.items.len(), 1); - assert_eq!(second.items[0].version(), "10"); - assert!(second.page_token.is_none()); - assert!( - db.list_functions( - &["other".into()], - crate::listing::ListingOptions::default() - .page_limit(2) - .page_token(token) - ) - .await - .is_err() - ); - let seen = statements.lock().unwrap(); - assert_eq!(seen.len(), 2); - assert!(seen[0].starts_with("SHOW FUNCTIONS HISTORY WITH (limit = 3,")); - assert!(seen[1].contains("after_version = '2'")); - shutdown.send(()).unwrap(); + for defer in [false, true] { + let service = TestSqlService { + adaptive: true, + defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2".to_owned(), + sql_listing_batch("definition", &[VERSION, &second], Some("revision-cursor")), + ), + ( + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'".to_owned(), + sql_listing_batch("definition", &[&tenth], None), + ), + ]))), + ..Default::default() + }; + let statements = service.statements.clone(); + let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|_| -> http::Response { + panic!("unexpected REST request") + }) + .with_sql_client(client); + let first = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default().page_limit(2), + ) + .await + .unwrap(); + assert_eq!( + first + .items + .iter() + .map(|item| item.version()) + .collect::>(), + ["1", "2"] + ); + assert_eq!(first.page_token.as_deref(), Some("revision-cursor")); + let last = db + .list_functions( + &["team".into()], + crate::listing::ListingOptions::default() + .page_limit(2) + .page_token(first.page_token.unwrap()), + ) + .await + .unwrap(); + assert_eq!(last.items.len(), 1); + assert_eq!(last.items[0].version(), "10"); + assert!(last.page_token.is_none()); + assert_eq!( + *statements.lock().unwrap(), + [ + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2", + "SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'" + ] + ); + shutdown.send(()).unwrap(); + } } #[tokio::test] @@ -3999,29 +4072,20 @@ async fn view_drop_uses_a_repeatable_query_job() { } #[tokio::test] -async fn view_listing_uses_bounded_sql_and_scoped_cursors() { +async fn view_listing_uses_server_continuation_tokens() { for defer in [false, true] { - let first_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["adults", "hf'prod", "openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let second_result = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef, - )]) - .unwrap(); - let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([ - ("SHOW VIEWS LIMIT 3".to_string(), first_result), - ( - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3".to_string(), - second_result, - ), - ]))); + let token = "server'opaque:token"; + let next_sql = "SHOW VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'"; let service = TestSqlService { adaptive: true, defer, - result_overrides, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "SHOW VIEWS IN \"team$reports\" LIMIT 2".to_owned(), + sql_listing_batch("name", &["a", "b"], Some(token)), + ), + (next_sql.to_owned(), sql_listing_batch("name", &["z"], None)), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -4033,107 +4097,39 @@ async fn view_listing_uses_bounded_sql_and_scoped_cursors() { ) .await; let db = RemoteDatabase::new_mock(|_| -> http::Response { - panic!("unexpected REST request"); + panic!("unexpected REST request") }) .with_sql_client(client); - let connection = Connection::new( - Arc::new(db), - Arc::new(crate::embeddings::MemoryRegistry::new()), - ); let namespace = vec!["team".to_owned(), "reports".to_owned()]; - - let first = connection + let first = db .list_views( &namespace, crate::listing::ListingOptions::default().page_limit(2), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(first.items, ["adults", "hf'prod"]); - let token = first.page_token.expect("a third row must produce a token"); - - let second = connection + assert_eq!(first.items, ["a", "b"]); + assert_eq!(first.page_token.as_deref(), Some(token)); + let second = db .list_views( &namespace, crate::listing::ListingOptions::default() .page_limit(2) - .page_token(&token), + .page_token(first.page_token.unwrap()), ) - .next_page() .await - .unwrap() .unwrap(); - assert_eq!(second.items, ["openai-prod"]); + assert_eq!(second.items, ["z"]); assert!(second.page_token.is_none()); - assert_eq!( *statements.lock().unwrap(), - [ - "SHOW VIEWS LIMIT 3", - "SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3" - ] + ["SHOW VIEWS IN \"team$reports\" LIMIT 2", next_sql] ); - { - let headers = headers.lock().unwrap(); - assert!(!headers.is_empty()); - for header in headers.iter() { - assert_eq!(header.database, "analytics"); - assert_eq!(header.database_prefix, "tenant/production"); - assert_eq!(header.namespace_path, "team$reports"); - } + for header in headers.lock().unwrap().iter() { + assert_eq!(header.database, "analytics"); + assert_eq!(header.database_prefix, "tenant/production"); + assert_eq!(header.namespace_path, "team$reports"); } - - let encode_token = - |kind: &str, database: &str, prefix: Option<&str>, path: &[String], last: &str| { - URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&(kind, database, prefix, path.to_vec(), last)).unwrap(), - ) - }; - for forged in [ - encode_token( - "secret", - "analytics", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token( - "view", - "billing", - Some("tenant/production"), - &namespace, - "hf'prod", - ), - encode_token("view", "analytics", Some("other"), &namespace, "hf'prod"), - encode_token( - "view", - "analytics", - Some("tenant/production"), - &["other".to_owned()], - "hf'prod", - ), - "not-a-json-token".to_string(), - ] { - let mut listing = connection.list_views( - &namespace, - crate::listing::ListingOptions::default().page_token(forged), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - } - let mut listing = connection.list_views( - &["other".to_owned()], - crate::listing::ListingOptions::default().page_token(&token), - ); - assert!(matches!( - listing.next_page().await, - Err(Error::InvalidInput { .. }) - )); - assert_eq!(statements.lock().unwrap().len(), 2); shutdown.send(()).unwrap(); } } diff --git a/rust/lancedb/src/remote/storage_integration.rs b/rust/lancedb/src/remote/storage_integration.rs index 48dab4c6a..6c132ab4b 100644 --- a/rust/lancedb/src/remote/storage_integration.rs +++ b/rust/lancedb/src/remote/storage_integration.rs @@ -259,29 +259,6 @@ pub(super) fn decode_info(batches: &[RecordBatch]) -> Result Result> { - let mut names = Vec::new(); - for batch in batches { - let column = batch - .column_by_name("name") - .ok_or_else(|| invalid("SQL storage integration listing is missing names"))?; - for row in 0..batch.num_rows() { - if column.is_null(row) { - return Err(invalid("SQL storage integration name cannot be null")); - } - names.push( - string_value(column.as_ref(), row) - .ok_or_else(|| { - invalid("SQL storage integration listing requires string names") - })? - .to_string(), - ); - } - } - names.sort(); - Ok(names) -} - #[cfg(test)] mod tests { use std::sync::Arc; From 530d379fc4d3abbf8c4c8759f7d48804d2055677 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 15 Nov 2026 02:08:34 +0000 Subject: [PATCH 06/11] =?UTF-8?q?Bump=20version:=200.42.0-beta.13=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.14?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 04ce71470..8491e70dc 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.13" +current_version = "0.42.0-beta.14" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a84f1d6fd..755ba70a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5992,7 +5992,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "ahash", "anyhow", @@ -6103,7 +6103,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "anyhow", "arrow-array", @@ -6146,7 +6146,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "arrow-array", "arrow-buffer", @@ -6171,7 +6171,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1aadbe68f..ca0113382 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.13 + 0.42.0-beta.14 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index e8a9a76ec..0ed2c85d9 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.13 + 0.42.0-beta.14 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9b062f4e8..ead5955fa 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.13 + 0.42.0-beta.14 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 7f8468eb5..87919848f 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 0fb6fde09..4c29cfeb3 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 24e779721..86c223618 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 8ee7bd66b..2e32e7fc3 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 3c7c63b86..7d984b9f4 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 75e68cacd..3607a6b93 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 3422e095c..369ff1c10 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e9ceb4dfb..d0852d725 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 512e390aa..8520e7b83 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.13", + "version": "0.42.0-beta.14", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 0f7667320..08113dee6 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 2dac7bda3..3a963d193 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 581504423..0b566e596 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.13" +version = "0.42.0-beta.14" edition = "2021" license.workspace = true repository.workspace = true From f17a07a2cda583af25f67797192ea776b8b8efa2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 15 Nov 2026 00:50:58 -0800 Subject: [PATCH 07/11] feat: expose server-side job listing filters (#5041) Expose server-side job filters and lazy Listing indexing, slicing, and length helpers. Document cache, cursor, and SDK/server compatibility behavior. --- docs/web/basics/jobs.mdx | 51 ++++++-- nodejs/__test__/remote.test.ts | 53 +++++++-- python/python/lancedb/_lancedb.pyi | 14 ++- python/python/lancedb/db.py | 136 ++++++++++++++++++--- python/python/lancedb/listing.py | 72 ++++++++++- python/python/lancedb/remote/db.py | 48 +++++++- python/python/tests/test_listing.py | 178 +++++++++++++++++++++++++++- python/src/connection.rs | 38 +++++- rust/lancedb/src/connection.rs | 35 +++++- rust/lancedb/src/database.rs | 47 ++++++++ rust/lancedb/src/remote/db.rs | 137 ++++++++++++++++++++- 11 files changed, 756 insertions(+), 53 deletions(-) diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 264acd728..db5b49ab5 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -177,14 +177,51 @@ for info in db.list_jobs(page_limit=50): live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds each server request, not the total yielded items, and `page_token` resumes a listing. It is a lazy iterator: iteration performs requests and can raise -request errors. To materialize it, use `list(db.list_jobs(...))`; it does not -support list indexing, `len()`, or a `.to_list()` method. +request errors. Use `list(db.list_jobs(...))` to collect all remaining results; +there is no `.to_list()` method. -`Listing.num_page_results()` reports cached items remaining in the current -page and `Listing.page_token()` reports the next request's token. Drain the -cached items before saving that token, or resuming can skip them. A `None` -token after the final page can coexist with unread cached items. A resumed -listing is not a transactionally frozen view of jobs submitted in the meantime. + +Job filters and synchronous `Listing` indexing, slicing, and `len()` require +a Python SDK release that includes these APIs. Older SDKs expose only +`page_token` and `page_limit`; collect results with `list(...)` before indexing +or counting them. Filtering also requires a matching Enterprise server that +supports the requested filters. + + +Filter jobs on the server before pagination with `table`, `state`, `job_type` +or `job_types`, and creation-time bounds. `table` names a table in +`namespace_path` (the root by default) and includes all its branches. Requests +stay scoped to the connected database. Creation times are Unix milliseconds: +`created_at_gte_millis` is inclusive and `created_at_lt_millis` is exclusive. +Choose either `job_type` or `job_types`. + +The `state` filter uses registry states: `in_progress`, `succeeded`, `failed`, +`canceled`, and `timed_out`. These differ from the SDK lifecycle labels such +as `running` and `finished` returned in `JobInfo.state`. + +```python +jobs = db.list_jobs(table="events", state="in_progress", page_limit=5) +first_five = jobs[:5] +for info in first_five: + print(info.job_id, info.state) +``` + +Synchronous indexing and slicing refer to the remaining results without +consuming them. A bounded forward slice such as `jobs[:5]` fetches only enough +pages to reach its stop. `len(jobs)` returns the remaining count by fetching +and caching every remaining result. Negative indexes and open-ended or reverse +slices also fetch and cache all remaining results. These operations can raise +request errors; later iteration drains their cache. `AsyncListing` remains an +async iterator: use `async for` to read it. + +`Listing.num_page_results()` reports cached items available without another +request, including items retained by indexing, slicing, or counting. +`Listing.page_token()` reports the next request's token. Drain all cached +items before saving that token, or resuming can skip them. Resume with the same +filters, for example `db.list_jobs(table="events", state="in_progress", +page_token=saved_token, page_limit=5)`. A `None` token after the final page can +coexist with unread cached items. A resumed listing is not a transactionally +frozen view of jobs submitted in the meantime. `events.schema` describes the Arrow response. Use `events.to_pylist()` for Python row dictionaries. Common event columns are `event_seq` (int64), `state` diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 215df992d..9baa51292 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -2318,10 +2318,30 @@ describe("remote connection jobs surface", () => { queue_reason: "Waiting for Function worker capacity", }); const descriptions = [ - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`, - `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 3000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 20, + 80, + 2000, + knownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress( + 40, + 60, + 1000, + unknownFleet, + )}}`, + `{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress( + 60, + 0, + 0, + unknownFleet, + )}}`, ]; let describeCount = 0; @@ -2393,12 +2413,24 @@ describe("remote connection jobs surface", () => { it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => { const now = Date.now(); const descriptions = [ - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`, - `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 5000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${ + now - 4000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 3000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 2000 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1500 + }}}`, + `{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${ + now - 1000 + }}}`, ]; await withMockDatabase( @@ -2574,6 +2606,7 @@ describe("lazy resource listings", () => { if (kind === "jobs") { expect(url.pathname).toBe("/v1/jobs/list"); expect(request.body).toEqual({ + database: "dev", // biome-ignore lint/style/useNamingConvention: server wire format page_token: token, limit: 2, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a86bae9d5..0cce2085e 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 12c7edd5c..b225a6e65 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1602,13 +1602,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( @@ -2799,16 +2825,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 @@ -4375,16 +4437,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: diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 59aba1431..f85599b2d 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -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() diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 913c8fc2c..2927f2726 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -1324,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 diff --git a/python/python/tests/test_listing.py b/python/python/tests/test_listing.py index cc1c44e90..d18e8580b 100644 --- a/python/python/tests/test_listing.py +++ b/python/python/tests/test_listing.py @@ -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 diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a171032c..2d65a0459 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -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, page_limit: Option, + table: Option, + namespace_path: Option>, + state: Option, + job_type: Option, + job_types: Option>, + created_at_gte_millis: Option, + created_at_lt_millis: Option, ) -> PyResult { + 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)), )) } diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 6dacbbbea..29f70d164 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -23,8 +23,8 @@ use crate::connection::create_table::CreateTableBuilder; use crate::data::scannable::Scannable; use crate::database::listing::ListingDatabase; use crate::database::{ - CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, OpenTableRequest, - PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, + CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, JobListFilter, + OpenTableRequest, PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest, }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; @@ -1366,6 +1366,37 @@ impl Connection { }) } + /// List jobs using server-side filters, without scanning all history in the client. + /// + /// Filters are preserved on every page, including when resuming with a saved + /// token. Requests and errors occur during iteration, as with [`Self::list_jobs`]. + /// + /// ``` + /// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// use lancedb::{database::JobListFilter, listing::ListingOptions}; + /// let mut filter = JobListFilter::default(); + /// filter.table = Some("events".into()); + /// let mut jobs = connection.list_jobs_filtered(filter, ListingOptions::default().page_limit(5)); + /// if let Some(job) = jobs.try_next().await? { + /// println!("{}", job.job_id); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Listing { + let database = self.database().clone(); + Listing::new(options, move |options| { + let database = database.clone(); + let filter = filter.clone(); + async move { database.list_jobs_filtered(filter, options).await } + }) + } + /// Request cancellation of a server-side job by id. Returns true if the /// server accepted the cancellation, false if no such job exists. pub async fn cancel_job(&self, job_id: impl AsRef) -> Result { diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 638ae0dd5..8a7a941f6 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -238,6 +238,45 @@ pub enum ReadConsistency { Strong, } +/// Registry lifecycle states accepted when filtering jobs. +#[derive(Clone, Copy, Debug, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum JobListState { + /// A job that has not reached a terminal state. + InProgress, + /// A job that completed successfully. + Succeeded, + /// A job that failed. + Failed, + /// A job that was canceled. + Canceled, + /// A job that exceeded its timeout. + TimedOut, +} + +/// Server-side filters applied before job pagination. +/// +/// Continuation tokens must be resumed with the same filters. Creation times +/// are Unix timestamps in milliseconds; the lower bound is inclusive and the +/// upper bound is exclusive. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct JobListFilter { + /// Table name within `namespace_path`, including all its branches; absent means all tables. + pub table: Option, + /// Namespace of `table`; requires a table name. + pub namespace_path: Vec, + /// Registry state, such as `in_progress`, `succeeded`, or `failed`. + /// These are server states, rather than the labels in [`JobInfo::state`]. + pub state: Option, + /// Include jobs of any of these types; empty means all types. + pub job_types: Vec, + /// Inclusive creation-time lower bound. + pub created_at_gte_millis: Option, + /// Exclusive creation-time upper bound. + pub created_at_lt_millis: Option, +} + /// A row from [`Database::list_jobs`]: one server-side job (index build, /// compaction, column refresh, ...). #[derive(Debug, Clone)] @@ -781,6 +820,14 @@ pub trait Database: async fn list_jobs(&self, _options: ListingOptions) -> Result> { job_op_not_supported("list_jobs") } + /// Fetch one page of jobs matching server-side filters. + async fn list_jobs_filtered( + &self, + _filter: JobListFilter, + _options: ListingOptions, + ) -> Result> { + job_op_not_supported("list_jobs_filtered") + } /// Request cancellation of a job by id. Returns true if the server /// accepted the cancellation, false if no such job exists. Cancelling an /// already-terminal job is a no-op success. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 1a825bebc..125930cb7 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -22,7 +22,8 @@ use lance_namespace::models::{ use crate::Error; use crate::database::{ CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions, - ExecuteQueryRequest, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, + ExecuteQueryRequest, JobInfo, JobListFilter, OpenTableRequest, ReadConsistency, + TableNamesRequest, }; use crate::error::Result; use crate::function::{FunctionRegistrationRequest, FunctionVersion, GpuClass}; @@ -1290,7 +1291,54 @@ impl Database for RemoteDatabase { } async fn list_jobs(&self, options: ListingOptions) -> Result> { - let mut body = serde_json::json!({}); + self.list_jobs_filtered(JobListFilter::default(), options) + .await + } + + async fn list_jobs_filtered( + &self, + filter: JobListFilter, + options: ListingOptions, + ) -> Result> { + if self.db_name.is_empty() { + return Err(Error::InvalidInput { + message: "list_jobs requires a connected database".into(), + }); + } + if filter.table.is_none() && !filter.namespace_path.is_empty() { + return Err(Error::InvalidInput { + message: "namespace_path requires a table filter".into(), + }); + } + if let (Some(start), Some(end)) = + (filter.created_at_gte_millis, filter.created_at_lt_millis) + && start >= end + { + return Err(Error::InvalidInput { + message: "created_at_gte_millis must be less than created_at_lt_millis".into(), + }); + } + let mut body = serde_json::json!({"database": self.db_name}); + if let Some(table) = filter.table { + validate_table_name(&table)?; + validate_namespace(&filter.namespace_path)?; + body["table_ref"] = serde_json::json!({ + "db_name": self.db_name, + "table_id": {"namespace_path": filter.namespace_path, "table_name": table}, + }); + } + if let Some(state) = filter.state { + body["state"] = serde_json::json!(state); + } + if !filter.job_types.is_empty() { + body["job_types"] = serde_json::json!(filter.job_types); + } + if let Some(start) = filter.created_at_gte_millis { + body["created_at_gte_millis"] = start.into(); + } + if let Some(end) = filter.created_at_lt_millis { + body["created_at_lt_millis"] = end.into(); + } if let Some(token) = options.page_token { body["page_token"] = token.into(); } @@ -1999,7 +2047,7 @@ mod tests { use rstest::rstest; use crate::connection::ConnectBuilder; - use crate::database::Database; + use crate::database::{Database, JobListFilter, JobListState}; use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity}; use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition}; use crate::materialized_view::CreateMaterializedViewRequest; @@ -4133,7 +4181,10 @@ mod tests { let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) .unwrap(); - assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2})); + assert_eq!( + body, + serde_json::json!({"database": "default", "page_token": token, "limit": 2}) + ); } else { let ns = "team"; assert_eq!( @@ -4336,6 +4387,84 @@ mod tests { )); } + #[tokio::test] + async fn test_list_jobs_filters_every_page_without_eager_fetching() { + let count = Arc::new(AtomicUsize::new(0)); + let seen = count.clone(); + let conn = Connection::new_with_handler(move |request| { + let page = seen.fetch_add(1, Ordering::SeqCst); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let mut expected = serde_json::json!({ + "database": "default", + "table_ref": { + "db_name": "default", + "table_id": {"namespace_path": ["team", "project"], "table_name": "events"}, + }, + "state": "in_progress", + "job_types": ["column_refresh", "materialized_view_refresh"], + "created_at_gte_millis": 100, + "created_at_lt_millis": 200, + "limit": 1, + }); + if page > 0 { + expected["page_token"] = "next".into(); + } + assert_eq!(body, expected); + http::Response::builder().status(200).body(serde_json::json!({ + "jobs": [{"job_id": format!("job-{page}"), "table": "events", "job_type": "column_refresh", "state": "in_progress", "created_at_millis": 100}], + "page_token": (page == 0).then_some("next"), + }).to_string()).unwrap() + }); + let filter = JobListFilter { + table: Some("events".into()), + namespace_path: vec!["team".into(), "project".into()], + state: Some(JobListState::InProgress), + job_types: vec!["column_refresh".into(), "materialized_view_refresh".into()], + created_at_gte_millis: Some(100), + created_at_lt_millis: Some(200), + }; + let mut jobs = + conn.list_jobs_filtered(filter.clone(), ListingOptions::default().page_limit(1)); + assert_eq!(count.load(Ordering::SeqCst), 0); + assert_eq!(jobs.try_next().await.unwrap().unwrap().job_id, "job-0"); + assert_eq!(count.load(Ordering::SeqCst), 1); + let resumed = conn.list_jobs_filtered( + filter, + ListingOptions::default() + .page_limit(1) + .page_token(jobs.page_token().unwrap()), + ); + let remaining = resumed.try_collect::>().await.unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].job_id, "job-1"); + assert_eq!(count.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn test_list_jobs_invalid_filters_never_reach_server() { + let conn = Connection::new_with_handler(|_| -> http::Response { + panic!("invalid filters must not reach the server") + }); + let namespace_only = JobListFilter { + namespace_path: vec!["team".into()], + ..Default::default() + }; + let invalid_time = JobListFilter { + created_at_gte_millis: Some(200), + created_at_lt_millis: Some(100), + ..Default::default() + }; + for filter in [namespace_only, invalid_time] { + let mut jobs = conn.list_jobs_filtered(filter, ListingOptions::default()); + assert!(matches!( + jobs.try_next().await, + Err(Error::InvalidInput { .. }) + )); + assert!(jobs.try_next().await.unwrap().is_none()); + } + } + #[tokio::test] async fn test_list_jobs_does_not_truncate_after_100_pages() { let conn = Connection::new_with_handler(|request| { From 1feec84d2bb8166919a9c52640a7ad64d6f6e0e2 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 15 Nov 2026 01:21:28 -0800 Subject: [PATCH 08/11] feat(python): expose FTS operators and match counts (#5042) String full-text searches now accept `operator="AND"` or `operator="OR"`, preserving the existing OR default. Sync and async FTS builders expose `count_rows()` to count every match satisfying the filter, independently of pagination, projection, ordering, and reranking. Counting streams matching scores without reading document columns; it can scan all matches. ```python query = table.search("gripper closed", query_type="fts", operator="AND") query = query.where("active = true") matching_rows = query.count_rows() page = query.limit(20).to_list() query = await async_table.search("gripper closed", query_type="fts", operator="AND") matching_rows = await query.where("active = true").count_rows() ``` Phrase searches keep the existing index default and now explain how to rebuild an index with `FTS(with_position=True)`. AND requests retain their operator through namespace pushdown and fail explicitly on older remote servers that cannot represent it. Regression coverage includes indexed and unindexed queries, filtered counts above the default limit, pagination preservation, remote serialization, and phrase indexes with and without positions. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/namespace.py | 25 ++++ python/python/lancedb/query.py | 127 ++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 59 ++++++++- python/python/tests/test_fts.py | 184 ++++++++++++++++++++++++-- python/python/tests/test_namespace.py | 42 +++++- python/python/tests/test_remote_db.py | 43 ++++++ python/src/query.rs | 37 +++++- rust/lancedb/src/remote/table.rs | 16 ++- rust/lancedb/src/table/query.rs | 118 ++++++++++++----- 11 files changed, 599 insertions(+), 61 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 0cce2085e..63d442703 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -943,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] diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 67fcc61f7..463536619 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -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( diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index f99aaeb73..214d2255f 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -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 diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 818d2a257..2d068536e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -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( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 4a713da06..807edbc46 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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 @@ -5061,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 @@ -5072,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 @@ -5085,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 @@ -5096,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( @@ -5108,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/) @@ -5168,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 @@ -5193,6 +5219,7 @@ class LanceTable(Table): ordering_field_name=ordering_field_name, fts_columns=fts_columns or [], fast_search=fast_search, + operator=operator, ) @classmethod @@ -7376,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 @@ -7386,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 @@ -7396,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 @@ -7406,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 @@ -7416,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 @@ -7426,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( @@ -7437,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/) @@ -7480,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() @@ -7604,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: @@ -7720,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 diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index f2fcc970b..26ce5e528 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -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 diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 9bce1059d..b4ca746b0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -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 diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index f404e36f7..587e2d587 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -7802,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() diff --git a/python/src/query.rs b/python/src/query.rs index 2097dac69..9864d7d74 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -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::()?; + 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> { + 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 { let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?; Ok(HybridQuery { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 2224203cf..1394f1ab0 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -20,7 +20,7 @@ use crate::error::{HttpErrorSource, RemoteErrorMetadata}; use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; -use crate::index::scalar::FtsQuery; +use crate::index::scalar::{FtsQuery, Operator}; use crate::index::waiter::{MAX_WAIT, wait_for_index}; use crate::job::Job; use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult}; @@ -1374,6 +1374,20 @@ impl RemoteTable { "query": full_text_search.query.clone(), }); } else { + let has_and = match &full_text_search.query { + FtsQuery::Match(query) => query.operator == Operator::And, + FtsQuery::MultiMatch(query) => query + .match_queries + .iter() + .any(|query| query.operator == Operator::And), + _ => false, + }; + if has_and { + return Err(Error::NotSupported { + message: "AND full-text queries require server version 0.3.0 or later" + .into(), + }); + } body["full_text_query"] = serde_json::json!({ "columns": full_text_search.columns().into_iter().collect::>(), "query": full_text_search.query.query(), diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index e9bcd380d..7d98dc001 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -12,6 +12,7 @@ use super::NativeTable; use crate::connection::NamespaceClientPushdownOperation; use crate::error::{Error, Result}; use crate::expr::expr_to_sql_string; +use crate::index::scalar::{FtsQuery, Operator as FullTextOperator}; use crate::query::{ DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest, }; @@ -36,12 +37,13 @@ use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec}; use lance_datafusion::exec::{analyze_plan as lance_analyze_plan, execute_plan}; use lance_index::IndexType; use lance_index::metrics::NoOpMetricsCollector; +use lance_index::scalar::FullTextSearchQuery; use lance_index::vector::DIST_COL; use lance_linalg::distance::DistanceType as LanceDistanceType; use lance_namespace::LanceNamespace; use lance_namespace::models::{ QueryTableRequest as NsQueryTableRequest, QueryTableRequestColumns, - QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, + QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, StructuredFtsQuery, }; #[derive(Debug, Clone)] @@ -124,6 +126,10 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { if query.base().use_rte.is_some() || query.base().has_take() { return true; } + if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) + { + return true; + } matches!( query, AnyQuery::VectorQuery(vector_query) @@ -858,6 +864,33 @@ async fn execute_namespace_query( parse_arrow_ipc_response(response_bytes).await } +fn namespace_fts_query(fts: &FullTextSearchQuery) -> Result> { + if !matches!(&fts.query, FtsQuery::Match(query) if query.operator == FullTextOperator::Or) { + let query = serde_json::to_value(&fts.query) + .and_then(serde_json::from_value) + .map_err(|error| Error::InvalidInput { + message: format!("Cannot serialize namespace full-text query: {error}"), + })?; + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: None, + structured_query: Some(Box::new(StructuredFtsQuery::new(query))), + })) + } else { + let columns = fts.columns(); + Ok(Box::new(QueryTableRequestFullTextQuery { + string_query: Some(Box::new(StringFtsQuery { + query: fts.query.query().clone(), + columns: if columns.is_empty() { + None + } else { + Some(columns.into_iter().collect()) + }, + })), + structured_query: None, + })) + } +} + /// Convert an AnyQuery to the namespace QueryTableRequest format. fn convert_to_namespace_query(query: &AnyQuery) -> Result { query.base().check_filter()?; @@ -912,21 +945,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { } // Convert FTS query if present - let full_text_query = vq.base.full_text_search.as_ref().map(|fts| { - let columns = fts.columns(); - let columns_vec = if columns.is_empty() { - None - } else { - Some(columns.into_iter().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = vq + .base + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; Ok(NsQueryTableRequest { id: None, // Will be set in namespace_query @@ -963,7 +987,6 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { let k = match q.limit { Some(limit) => limit as i32, - None if q.full_text_search.is_some() => DEFAULT_TOP_K as i32, None => i32::MAX, }; @@ -995,20 +1018,11 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { }; // Handle full text search if present - let full_text_query = q.full_text_search.as_ref().map(|fts| { - let columns_vec = if fts.columns().is_empty() { - None - } else { - Some(fts.columns().iter().cloned().collect()) - }; - Box::new(QueryTableRequestFullTextQuery { - string_query: Some(Box::new(StringFtsQuery { - query: fts.query.to_string(), - columns: columns_vec, - })), - structured_query: None, - }) - }); + let full_text_query = q + .full_text_search + .as_ref() + .map(namespace_fts_query) + .transpose()?; // Empty vector for non-vector queries let vector = Box::new(QueryTableRequestVector { @@ -1023,6 +1037,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result { filter, columns, prefilter: Some(q.prefilter), + fast_search: Some(q.fast_search), offset: q.offset.map(|o| o as i32), vector_column: None, // No vector column for plain queries with_row_id: Some(q.with_row_id), @@ -1147,6 +1162,7 @@ async fn parse_arrow_ipc_response(bytes: bytes::Bytes) -> Result Date: Sun, 15 Nov 2026 02:05:06 -0800 Subject: [PATCH 09/11] fix(python): show Function registration progress and image details (#5040) Report registration lifecycle and client elapsed time through existing job handles, and provide concise image inspection. Preserve quiet wait behavior, environment-lock forwarding, failure diagnostics and timeout recovery. --- docs/src/python/python.md | 19 ++ python/python/lancedb/db.py | 11 +- python/python/lancedb/functions.py | 59 +++++- python/python/lancedb/job.py | 75 ++++++- .../tests/test_first_class_function_slice1.py | 55 +++++ python/python/tests/test_job.py | 190 +++++++++++++++++- 6 files changed, 396 insertions(+), 13 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b7eb1704a..b0425e1f7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -424,6 +424,25 @@ code that used the former LanceDB Enterprise-only argument order. ## Functions and Jobs +Use `progress=True` when waiting for Function registration in a notebook or +terminal. A callback receives structured snapshots instead: + +```python +fn = db.create_function(my_function, progress=True) +registration = db.create_function_async(other_function) +fn = registration.wait(progress=lambda snapshot: print(snapshot)) +print(fn.image.describe()) +``` + +Registration uses the existing SQL query handle. The current handle reports +lifecycle state and `client_elapsed_time_millis` since the handle was created; +detailed build phases and build logs are unavailable. Keep the same handle after +a wait timeout to resume waiting. Failures retain the server error and request +identifiers. `fn.image` has a concise representation; `describe()` exposes Python +and CUDA requirements without inspecting Pydantic internals. Platforms, base image +and size are `None` until the service reports them. The full image descriptor and +canonical JSON remain available. + A `@function` definition is also a local callable. Call a decorated function directly with row inputs, or call a decorated class with its initialization fields and then call the returned instance; call `close()` if the class defines it. This diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index b225a6e65..8c9901aff 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -1051,6 +1051,7 @@ class DBConnection(EnforceOverrides): 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. @@ -1076,6 +1077,9 @@ class DBConnection(EnforceOverrides): 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 @@ -1095,13 +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, refresh_lock=refresh_lock, - ).wait() + ) + if progress is False or progress is None: + return job.wait() + return job.wait(progress=progress) def create_function_async( self, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 548129211..f57a114dc 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -544,13 +544,70 @@ 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. diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 9195e01ae..e49609e1f 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -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: diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 07be57e15..004aca90c 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -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"] ) diff --git a/python/python/tests/test_job.py b/python/python/tests/test_job.py index 9897d97b5..e71945b7f 100644 --- a/python/python/tests/test_job.py +++ b/python/python/tests/test_job.py @@ -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 From 613653a7db1d023da706823e5287d9e4a236af6b Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 15 Nov 2026 06:04:30 -0800 Subject: [PATCH 10/11] chore: update lance dependency to v15.0.0-beta.22 (#5057) Update Rust and Java Lance dependencies to [v15.0.0-beta.22](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.22), synchronize the Python test pin to `pylance==15.0.0b22`, and refresh the lockfiles with all published platform wheels. Preserve Function freshness only when an UPDATE changes rows, so beta.22's no-match updates cannot mark previously invalidated outputs as fresh. Extend the existing regression cases to cover no-match updates after input and output changes, including unchanged table versions. Rust formatting passed. CI validates the compatibility fix; no local builds or tests were run. --------- Co-authored-by: Jack Ye --- Cargo.lock | 134 +++++++++++++++++----------- Cargo.toml | 30 +++---- java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 18 ++-- rust/lancedb/src/table/freshness.rs | 19 ++-- rust/lancedb/src/table/update.rs | 15 ++-- 7 files changed, 132 insertions(+), 88 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 755ba70a4..f454ff87a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1361,6 +1361,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "better_io" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef0a3155e943e341e557863e69a708999c94ede624e37865c8e2a91b94efa78f" + [[package]] name = "bigdecimal" version = "0.4.10" @@ -3278,6 +3284,12 @@ dependencies = [ "litrs", ] +[[package]] +name = "dtype_dispatch" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab23e69df104e2fd85ee63a533a22d2132ef5975dc6b36f9f3e5a7305e4a8ed7" + [[package]] name = "dunce" version = "1.0.5" @@ -3824,8 +3836,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5303,8 +5315,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5379,8 +5391,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5402,7 +5414,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5416,7 +5428,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "59.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5425,8 +5437,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrayref", "crunchy", @@ -5436,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5475,8 +5487,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5507,8 +5519,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5533,8 +5545,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5546,13 +5558,13 @@ dependencies = [ "hex", "rand 0.9.5", "rand_distr 0.5.1", - "rand_xoshiro", + "rand_xoshiro 0.7.0", ] [[package]] name = "lance-derive" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "proc-macro2", "quote", @@ -5561,8 +5573,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-arith", "arrow-array", @@ -5585,6 +5597,7 @@ dependencies = [ "log", "lz4", "num-traits", + "pco", "prost", "serde_json", "tokio", @@ -5595,8 +5608,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-arith", "arrow-array", @@ -5627,8 +5640,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5659,8 +5672,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5733,8 +5746,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5757,8 +5770,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5803,8 +5816,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "byteorder", "ethnum", @@ -5821,8 +5834,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5837,8 +5850,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "async-trait", @@ -5852,8 +5865,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arc-swap", "arrow", @@ -5907,8 +5920,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-buffer", @@ -5922,8 +5935,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow", "arrow-array", @@ -5964,8 +5977,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "arrow-array", "arrow-schema", @@ -5978,8 +5991,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d" +version = "15.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467" dependencies = [ "frostem", "icu_segmenter", @@ -6651,7 +6664,7 @@ dependencies = [ "quanta", "radix_trie", "rand 0.9.5", - "rand_xoshiro", + "rand_xoshiro 0.7.0", "sketches-ddsketch", ] @@ -7837,6 +7850,18 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "pco" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f01ab51a847e7002371c2384b2c88f50dd45982cc2764e7997751971f1bfbf" +dependencies = [ + "better_io", + "dtype_dispatch", + "half", + "rand_xoshiro 0.6.0", +] + [[package]] name = "pem" version = "3.0.6" @@ -9025,6 +9050,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xoshiro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "rand_xoshiro" version = "0.7.0" diff --git a/Cargo.toml b/Cargo.toml index bc9d85c72..0e60bcb51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,21 +19,21 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/java/pom.xml b/java/pom.xml index ead5955fa..2b7a90e03 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.21 + 15.0.0-beta.22 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index d464424c7..e2b140626 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -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", diff --git a/python/uv.lock b/python/uv.lock index 31ac68b4d..8e03e90d8 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -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]] diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 563a2a4e5..9980c3a75 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -3460,15 +3460,18 @@ mod tests { } #[rstest::rstest] - #[case::input_same_rows("body", "a", true)] - #[case::input_other_rows("body", "c", false)] - #[case::output_same_rows("search_text", "a", true)] - #[case::output_other_rows("search_text", "c", false)] + #[case::input_same_rows("body", "a", true, 1)] + #[case::input_other_rows("body", "c", false, 1)] + #[case::input_no_rows("body", "missing", false, 0)] + #[case::output_same_rows("search_text", "a", true, 1)] + #[case::output_other_rows("search_text", "c", false, 1)] + #[case::output_no_rows("search_text", "missing", false, 0)] #[tokio::test] async fn function_write_preserves_prior_invalidation( #[case] changed_column: &str, #[case] title: &str, #[case] dirty_product: bool, + #[case] expected_updated_rows: u64, ) { let table = fresh_function_table().await; let native = table.as_native().unwrap(); @@ -3489,14 +3492,20 @@ mod tests { ); native.dataset.update(result.new_dataset.as_ref().clone()); - table + let before_version = table.version().await.unwrap(); + let update = table .update() .only_if(format!("title = '{title}'")) .column("spare", "1") .execute() .await .unwrap(); + assert_eq!(update.rows_updated, expected_updated_rows); let dataset = native.dataset.get().await.unwrap(); + if expected_updated_rows == 0 { + assert_eq!(update.version, before_version); + assert_eq!(dataset.version().version, before_version); + } let stale = function_plan(&dataset, "search_text").await; assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}"); if !dirty_product { diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 93e8a08ea..10895aa69 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -130,13 +130,14 @@ pub(crate) async fn execute_update( let operation = builder.build()?; let res = operation.execute().await?; let mut new_dataset = res.new_dataset.as_ref().clone(); - if let Err(error) = super::freshness::preserve_function_freshness( - &mut new_dataset, - super::freshness::FunctionWrite::Update { - columns: &written_columns, - }, - ) - .await + if res.rows_updated > 0 + && let Err(error) = super::freshness::preserve_function_freshness( + &mut new_dataset, + super::freshness::FunctionWrite::Update { + columns: &written_columns, + }, + ) + .await { log::warn!("update committed but Function freshness could not be preserved: {error}"); } From 2ab103d7754308cac7e4eceb91fd72b0ed8460df Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 15 Nov 2026 14:05:38 +0000 Subject: [PATCH 11/11] =?UTF-8?q?Bump=20version:=200.42.0-beta.14=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 8 ++++---- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/cli/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 8491e70dc..99297338c 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.14" +current_version = "0.42.0-beta.15" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index f454ff87a..a6ae84b72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6005,7 +6005,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "ahash", "anyhow", @@ -6116,7 +6116,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "anyhow", "arrow-array", @@ -6159,7 +6159,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "arrow-array", "arrow-buffer", @@ -6184,7 +6184,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index ca0113382..9d7162444 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.14 + 0.42.0-beta.15 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 0ed2c85d9..21f80cd99 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.14 + 0.42.0-beta.15 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 2b7a90e03..26c94d3bf 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.14 + 0.42.0-beta.15 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 87919848f..3cee8b0ad 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 4c29cfeb3..03c295432 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 86c223618..2cb5a722c 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index 2e32e7fc3..70880c70a 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 7d984b9f4..ed2f276a1 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index 3607a6b93..748cc1640 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 369ff1c10..52d79a178 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d0852d725..60cebaa37 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 8520e7b83..92c70bc3b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.14", + "version": "0.42.0-beta.15", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 08113dee6..fe135a99d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 3a963d193..d00feaf72 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 0b566e596..5b1744cc3 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.14" +version = "0.42.0-beta.15" edition = "2021" license.workspace = true repository.workspace = true