From ee231aad066289febc88bc4088b9c6f93b1e4d49 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 22:56:36 -0800 Subject: [PATCH 1/8] fix(python): validate function package requirements before registration (#4971) Function dependency typos currently reach the environment build before failing. Validate pip requirements with `packaging.requirements.Requirement` and conda requirements with Rattler's MatchSpec parser when constructing a function definition, before source packaging or registration. Errors identify the original entry and its index. ```python @lancedb.function(pip=["numpy", "torch>=2.0,,<3"]) def score(value: float) -> float: return value # ValueError: invalid pip[1] requirement 'torch>=2.0,,<3': ... ``` Preserves pip extras, markers, named references, bare archive/git URLs, and conda channel/build specifications. The existing native extension exposes the conda parser, so no additional Python package is required. Adds regression coverage for invalid and supported forms, including the deprecated `udf` alias. --- Cargo.lock | 288 +++++++++++++++++- python/Cargo.toml | 1 + python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/functions.py | 33 +- .../tests/test_function_requirements.py | 125 ++++++++ python/src/lib.rs | 1 + python/src/util.rs | 8 + 7 files changed, 450 insertions(+), 7 deletions(-) create mode 100644 python/python/tests/test_function_requirements.py diff --git a/Cargo.lock b/Cargo.lock index ee2a3d919..f38252fc5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1422,6 +1422,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "blake3" version = "1.8.5" @@ -2734,7 +2743,7 @@ dependencies = [ "arrow", "arrow-buffer", "base64 0.23.1", - "blake2", + "blake2 0.10.6", "blake3", "chrono", "chrono-tz 0.10.4", @@ -3197,6 +3206,15 @@ dependencies = [ "dirs-sys 0.5.0", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -3442,6 +3460,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -3572,6 +3601,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "file_url" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec49f140842acf886ff3e4fd47600ffdbb5f1b1ba70f6775880e688837a0b174" +dependencies = [ + "itertools 0.15.0", + "percent-encoding", + "thiserror 2.0.18", + "typed-path", + "url", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3616,6 +3658,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + [[package]] name = "float8" version = "0.7.0" @@ -3747,6 +3798,15 @@ version = "1.20260804.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "fs4" version = "0.13.1" @@ -4323,6 +4383,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "halfbrown" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09" +dependencies = [ + "hashbrown 0.16.1", + "serde", +] + [[package]] name = "hash32" version = "0.3.1" @@ -4428,7 +4498,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ - "dirs", + "dirs 6.0.0", "futures", "http", "indicatif", @@ -5624,7 +5694,7 @@ dependencies = [ "datafusion-functions-nested", "datafusion-physical-expr", "datafusion-physical-plan", - "dirs", + "dirs 6.0.0", "fst", "futures", "half", @@ -6132,6 +6202,7 @@ dependencies = [ "pyo3", "pyo3-async-runtimes", "pyo3-build-config", + "rattler_conda_types", "reqwest 0.13.5", "serde", "serde_json", @@ -6140,6 +6211,29 @@ dependencies = [ "uuid", ] +[[package]] +name = "lazy-regex" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" +dependencies = [ + "lazy-regex-proc_macros", + "once_cell", + "regex", +] + +[[package]] +name = "lazy-regex-proc_macros" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 3.0.3", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -6903,6 +6997,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "nom-language" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29" +dependencies = [ + "nom 8.0.0", +] + [[package]] name = "now" version = "0.1.3" @@ -8587,6 +8690,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" +[[package]] +name = "purl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ebe4262ae91ddd28c8721111a0a6e9e58860e211fc92116c4bb85c98fd96ad" +dependencies = [ + "hex", + "percent-encoding", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "pyo3" version = "0.29.3" @@ -8973,6 +9088,99 @@ dependencies = [ "rustversion", ] +[[package]] +name = "rattler_conda_types" +version = "0.58.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda631350e17df9bc789082d6b6c0fbde38e65cba580593ee3317fb6730644f2" +dependencies = [ + "ahash", + "core-foundation 0.10.1", + "dirs 7.0.0", + "fancy-regex 0.19.2", + "file_url", + "fs-err", + "glob", + "hex", + "indexmap 2.14.0", + "itertools 0.15.0", + "jiff", + "lazy-regex", + "memmap2 0.9.10", + "nom 8.0.0", + "nom-language", + "purl", + "rattler_conda_version", + "rattler_digest", + "rattler_macros", + "rattler_redaction", + "regex", + "serde", + "serde-untagged", + "serde_json", + "serde_repr", + "serde_with", + "serde_yaml", + "simd-json", + "smallvec", + "strum", + "tempfile", + "thiserror 2.0.18", + "tracing", + "typed-path", + "url", +] + +[[package]] +name = "rattler_conda_version" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee922b54cd30c198e93c542096a0d671cefba1a97600768b2ec4af3c11c44f55" +dependencies = [ + "itertools 0.15.0", + "nom 8.0.0", + "serde", + "smallvec", + "thiserror 2.0.18", +] + +[[package]] +name = "rattler_digest" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda554663860e074665f838a4d9a89fbf671f576eaf288d29525114b345adc9" +dependencies = [ + "blake2 0.11.0", + "digest 0.11.3", + "hex", + "md-5", + "serde", + "serde-untagged", + "serde_bytes", + "serde_with", + "sha2 0.11.0", + "url", +] + +[[package]] +name = "rattler_macros" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a42690ed14c8b9d610aafc0f2eb715b85c05f3d3a2a307896e4f8d820aaa284f" +dependencies = [ + "quote", + "syn 3.0.3", +] + +[[package]] +name = "rattler_redaction" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b5ee47d0375643b037205a4fe238b90c518ca3fc83c7c240d82c49ba87d61c" +dependencies = [ + "url", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -9926,6 +10134,28 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -10056,6 +10286,19 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -10170,7 +10413,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" dependencies = [ "bstr", - "dirs", + "dirs 6.0.0", "os_str_bytes", ] @@ -10235,6 +10478,20 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd-json" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebe141eb4a23ecc4d5de93fa5b139ac65dc07c38037a2fe9a8fb7c9d36bd832" +dependencies = [ + "halfbrown", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + [[package]] name = "simd_cesu8" version = "1.1.1" @@ -10274,6 +10531,9 @@ name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "smartstring" @@ -11403,6 +11663,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.0" @@ -11583,6 +11849,18 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-trait" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b" +dependencies = [ + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -12561,7 +12839,7 @@ dependencies = [ "colored", "const-str", "ctor", - "dirs", + "dirs 6.0.0", "futures", "git-version", "humantime", diff --git a/python/Cargo.toml b/python/Cargo.toml index 07ca7de02..7c11d5fdf 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -37,6 +37,7 @@ pyo3-async-runtimes = { version = "0.29", features = [ "tokio-runtime", ] } reqwest.workspace = true +rattler_conda_types = { version = "0.58.3", default-features = false } pin-project.workspace = true futures.workspace = true serde.workspace = true diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4029525e9..521cc46bb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1310,3 +1310,4 @@ class AuthzObject: def __repr__(self) -> str: ... def validate_function_retry_policy(json: str) -> None: ... +def _validate_conda_requirement(requirement: str) -> None: ... diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 737abc44e..4bf028306 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -44,6 +44,7 @@ from typing import ( ) import pyarrow as pa +from packaging.requirements import Requirement from pydantic import ( AfterValidator, BaseModel, @@ -57,6 +58,7 @@ from pydantic import ( from .schema import blob as _blob_field from .schema import is_blob_v2_field as _is_blob_v2_field from ._blob_reader import BlobReader +from ._lancedb import _validate_conda_requirement from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) @@ -1701,6 +1703,29 @@ def _packaged_by_source(value: Any) -> bool: return True +def _validate_package_requirements(kind: str, packages: Sequence[str]) -> None: + for index, package in enumerate(packages): + field = f"{kind}[{index}]" + if not isinstance(package, str): + raise TypeError(f"{field} must be a string, got {package!r}") + if not package or package != package.strip(): + raise ValueError( + f"{field} requirement {package!r} must be non-empty and trimmed" + ) + try: + if kind == "conda": + _validate_conda_requirement(package) + else: + candidate = package + if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://", package): + candidate = f"dependency @ {package}" + Requirement(candidate) + except ValueError as error: + raise ValueError( + f"invalid {field} requirement {package!r}: {error}" + ) from error + + def _requirement_name(requirement: str) -> str: requirement = requirement.rpartition("::")[2] match = _REQUIREMENT_NAME.match(requirement.strip()) @@ -2242,6 +2267,7 @@ class FunctionDefinition: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") + _validate_package_requirements("conda" if conda else "pip", conda or pip) gpu_marker = _normalize_gpu_marker(gpu) if gpu_class is not None: _validate_gpu_class_name(gpu_class) @@ -2595,9 +2621,12 @@ def function( non-nullable. 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. + Pip requirements for the remote environment. Syntax is validated at + decoration time, including extras and environment markers. Named direct + references and bare package or git URLs are supported. conda : sequence of str, optional - Conda packages for the remote environment, instead of ``pip``. + Conda packages for the remote environment, instead of ``pip``. MatchSpec + syntax is validated at decoration time, including channels and builds. conda_channels : sequence of str, optional Conda channels in priority order; requires ``conda``. apt : sequence of str, optional diff --git a/python/python/tests/test_function_requirements.py b/python/python/tests/test_function_requirements.py new file mode 100644 index 000000000..6f94d1313 --- /dev/null +++ b/python/python/tests/test_function_requirements.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +from lancedb import function, udf +from lancedb.functions import FunctionDefinition + + +def identity(value: int) -> int: + return value + + +@pytest.mark.parametrize( + "package", + [ + "torch>=2.0,,<3", + "torch>=", + "torch=>2.0", + "torch[", + "torch; python_version >=", + "", + " torch", + "torch ", + ], +) +def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch): + def unexpected_packaging(*args, **kwargs): + pytest.fail("invalid requirements must fail before packaging the function") + + monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging) + with pytest.raises(ValueError) as error: + function(pip=["numpy", package])(identity) + assert "pip[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize( + "package", + [ + "numpy>=1,,<3", + "numpy>=", + "numpy[version=]", + "numpy[unknown_field=value]", + "", + " numpy", + "numpy ", + ], +) +def test_invalid_conda_requirement_names_entry(package): + with pytest.raises(ValueError) as error: + function(conda=["scipy", package])(identity) + assert "conda[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize("kind", ["pip", "conda"]) +@pytest.mark.parametrize("package", [None, 42, ["numpy"]]) +def test_requirement_must_be_a_string(kind, package): + with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"): + function(**{kind: ["numpy", package]})(identity) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "torch>=2.0,<3", + 'requests[security,socks]>=2; python_version >= "3.10"', + "numpy (>=1.26, <3)", + "six @ https://example.com/six-1.16.0.tar.gz", + "six @ git+https://github.com/benjaminp/six.git@main", + "https://example.com/six-1.16.0.tar.gz", + "git+https://github.com/benjaminp/six.git@main", + "git+ssh://git@github.com/benjaminp/six.git@main", + ], +) +def test_supported_pip_requirements_are_preserved(package): + definition = function(pip=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "numpy=1.26", + "numpy>=1.26,<3", + "numpy=1.26=py310_0", + "numpy 1.26 py310_0", + "conda-forge::numpy>=1.26", + "conda-forge/linux-64::numpy>=1.26", + "numpy[version='>=1.26,<3',build='py310*']", + ], +) +def test_supported_conda_requirements_are_preserved(package): + definition = function(conda=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +def test_requirements_still_sort_and_deduplicate(): + definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity) + assert definition.registration_request.runtime.environment.packages == ( + "numpy", + "torch>=2", + ) + + +def test_deprecated_udf_alias_validates_requirements(): + with pytest.warns(DeprecationWarning, match="use lancedb.function"): + with pytest.raises(ValueError, match=r"pip\[0\]"): + udf(pip=["torch>=2.0,,<3"])(identity) + + +def test_direct_function_definition_validates_requirements(): + with pytest.raises(ValueError, match=r"pip\[0\]"): + FunctionDefinition( + identity, + name=None, + input_schema=None, + output_schema=None, + pip=("torch>=2.0,,<3",), + env={}, + python_version=None, + ) diff --git a/python/src/lib.rs b/python/src/lib.rs index f78c4e7bb..b0698d5e0 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -150,6 +150,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?; m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; diff --git a/python/src/util.rs b/python/src/util.rs index a956066f1..44efa165a 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -9,6 +9,7 @@ use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, pyfunction, }; +use rattler_conda_types::{MatchSpec, ParseStrictness}; /// A wrapper around a rust builder /// @@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> { .map_err(|e| PyValueError::new_err(e.to_string())) } +#[pyfunction(name = "_validate_conda_requirement")] +pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> { + MatchSpec::from_str(requirement, ParseStrictness::Lenient) + .map(|_| ()) + .map_err(|error| PyValueError::new_err(error.to_string())) +} + /// Parse field references with the same identifier syntax as Lance writes. #[pyfunction(name = "_parse_field_path")] pub fn parse_field_path(path: &str) -> PyResult> { From e622254108f15e159627d8a1d8e42e983e45cd81 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 23:32:19 -0800 Subject: [PATCH 2/8] fix(python): use direct lookups for table existence checks (#4974) Table existence checks should not depend on listing every table or searching only the first 100 names. Use a direct lookup for `name in db` and implement `table_exists(table_id)` on synchronous local connections, matching the remote and asynchronous APIs. Native namespace connections use their initialized Rust connection for existence checks; custom namespace clients retain their existing callback. Missing tables return `False`; other lookup errors propagate. ```python if "events" in db: db.drop_table("events") exists = db.table_exists(["analytics", "events"]) all_names = list(db.list_tables()) ``` Clarify that `.tables` contains one page and update deprecation guidance with safe replacements. Add regression coverage for lookups beyond the first page, nested namespaces, native and custom namespace clients, missing tables, permission errors, and lookups that do not list tables. Include an unpublished draft for the table-management guide until the new SDK support ships. --- docs/src/python/python.md | 17 +++++++ docs/web/management/table.mdx | 23 ++++++++- python/python/lancedb/db.py | 56 +++++++++++++++++---- python/python/lancedb/listing.py | 8 +++ python/python/lancedb/namespace.py | 30 ++++++++--- python/python/lancedb/remote/db.py | 13 +++-- python/python/tests/test_db.py | 46 +++++++++++++---- python/python/tests/test_namespace.py | 41 +++++++++++++++ python/python/tests/test_remote_db.py | 26 ++++++++++ python/python/tests/test_sync_api_parity.py | 25 ++++++--- 10 files changed, 246 insertions(+), 39 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index eccaae6ce..8de5b5517 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -42,6 +42,18 @@ table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same patterns apply to `list_namespaces()`. Other resource listings use `page_limit`. +For existence checks, use `db.table_exists(["events"])` or `"events" in db`. +These look up the table directly and work even when the database has more than +100 tables. For a table in a namespace, include the namespace segments: + +```python +exists = db.table_exists(["analytics", "events"]) +``` + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. Checking `name in db.list_tables().tables` only +searches the first page and can miss an existing table. + Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and `list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to collect synchronous results, or `[name async for name in db.list_views()]` with @@ -1055,6 +1067,11 @@ the page list does not consume the iterator. `page.page_token` is the token for the next request; drain cached results before using it to resume in a new listing. The same behavior applies to namespaces. +Use `await db.table_exists(["events"])` to check for a table in the root +namespace, or `await db.table_exists(["analytics", "events"])` for a table in +a namespace. Checking membership in an awaited listing's `.tables` attribute +only searches one page. + ::: lancedb.listing.AsyncTableListing ::: lancedb.listing.AsyncNamespaceListing diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 2a05b4a0f..23fdbdb4a 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -201,7 +201,7 @@ setting. See [Limits](/basics/limits#schema). ```python Python icon="python" tbl = db.open_table("documents") -db.table_names() +names = list(db.list_tables()) ``` ```typescript TypeScript icon="square-js" @@ -230,6 +230,27 @@ listing. A missing table raises `ValueError` on a local directory and A listing returns one page of names at a time, so check every page. TypeScript has no `tableExists`. +{/* +Draft for the table-existence lookup release (#4974). Once released, replace +the two table-existence paragraphs above with this guidance: + +For Python local, remote, and namespace connections, use +`db.table_exists(["documents"])` or `"documents" in db` to check whether a root +table exists. For an async connection, use +`await db.table_exists(["documents"])`. Include namespace segments before the +table name, for example `["analytics", "documents"]`. These checks return +`False` when the table is missing and propagate other errors, including +permission errors. They look up the table directly, regardless of the number +of tables in the database. + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. To collect every table name, use +`list(db.list_tables())`, or `[name async for name in db.list_tables()]` on an +async connection. The `.tables` attribute holds only one page (100 names by +default), so membership checks against it can miss existing tables. TypeScript +has no `tableExists`. +*/} + ## Rename and clone tables {#rename-clone} diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 73c8305ff..84ebb41a1 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -322,6 +322,9 @@ class DBConnection(EnforceOverrides): def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in + ``list_tables().tables``, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -331,12 +334,20 @@ class DBConnection(EnforceOverrides): Returns ------- bool - True if the table exists, False otherwise. + True if the table exists, False if it is not found. + Other errors, including permission errors, are propagated. Raises ------ NotImplementedError - If the connection type does not support namespace operations. + If the connection type does not support table existence checks. + + Examples + -------- + >>> def check_table(conn): + ... root_exists = conn.table_exists(["events"]) + ... nested_exists = conn.table_exists(["analytics", "events"]) + ... return root_exists, nested_exists """ raise NotImplementedError( "Namespace operations are not supported for this connection type" @@ -348,7 +359,11 @@ class DBConnection(EnforceOverrides): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + ``list_tables().tables`` contains only the first page (100 names by + default). Use ``list(list_tables())`` to collect all names, or + ``table_exists([name])`` to check whether a particular table exists. Parameters ---------- @@ -934,7 +949,7 @@ class DBConnection(EnforceOverrides): def __contains__(self, name: str) -> bool: """Return whether the root namespace contains the named table.""" - return name in self._all_table_names() + return self.table_exists([name]) def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -1849,6 +1864,10 @@ class LanceDBConnection(DBConnection): ) -> DescribeNamespaceResponse: return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path)) + @override + def table_exists(self, table_id: List[str]) -> bool: + return LOOP.run(self._conn.table_exists(table_id)) + @override def list_tables( self, @@ -1856,7 +1875,11 @@ class LanceDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1894,7 +1917,9 @@ class LanceDBConnection(DBConnection): """Get the names of all tables in the database. The names are sorted. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -1914,7 +1939,8 @@ class LanceDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -2878,6 +2904,9 @@ class AsyncConnection(object): async def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in an awaited listing's + ``tables`` attribute, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -2903,7 +2932,11 @@ class AsyncConnection(object): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> AsyncTableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -2942,7 +2975,9 @@ class AsyncConnection(object): """List all tables in this database, in sorted order .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -2966,7 +3001,8 @@ class AsyncConnection(object): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 8abc9d85b..59aba1431 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -175,6 +175,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]): class AsyncTableListing(_AsyncPagedNameListing): """Awaitable table iterator; awaiting loads one page. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``await db.table_exists([name])`` for existence checks. + For example:: page = await db.list_tables(limit=20) @@ -229,6 +232,10 @@ class _PagedNameListing(Iterator[str]): class TableListing(_PagedNameListing): """Table iterator retaining the current page as a list. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``db.table_exists([name])`` or ``name in db`` for + existence checks. Use ``list(db.list_tables())`` to collect all names. + For example:: page = db.list_tables(limit=20) @@ -239,6 +246,7 @@ class TableListing(_PagedNameListing): @property def tables(self) -> list[str]: + """A copy of the table names in the most recently fetched page.""" return self._inner.tables diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3356b363c..aa9025641 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -579,12 +579,15 @@ class LanceNamespaceDBConnection(DBConnection): If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1015,6 +1018,8 @@ class LanceNamespaceDBConnection(DBConnection): bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return LOOP.run(self._inner.table_exists(table_id)) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1030,7 +1035,11 @@ class LanceNamespaceDBConnection(DBConnection): limit: Optional[int] = None, ) -> TableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1227,12 +1236,15 @@ class AsyncLanceNamespaceDBConnection: If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1614,6 +1626,8 @@ class AsyncLanceNamespaceDBConnection: bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return await self._inner.table_exists(table_id) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1628,7 +1642,11 @@ class AsyncLanceNamespaceDBConnection: limit: Optional[int] = None, ) -> AsyncTableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ebceba16b..21ad37b36 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -430,7 +430,11 @@ class RemoteDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List a page of tables in this database. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -468,7 +472,9 @@ class RemoteDBConnection(DBConnection): """List the names of all tables in the database. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -488,7 +494,8 @@ class RemoteDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 64bf928c0..80a98bc18 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -282,9 +282,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path): assert empty.page_token is None -def test_db_contains_stops_after_matching_table_page( - tmp_db: lancedb.DBConnection, monkeypatch -): +def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch): calls = [] pages = { None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"), @@ -297,18 +295,44 @@ def test_db_contains_stops_after_matching_table_page( monkeypatch.setattr(tmp_db, "list_tables", list_tables) - assert "table_1" in tmp_db - assert calls == [None] - - calls.clear() - assert "table_2" in tmp_db - assert calls == [None, "next"] - - calls.clear() assert len(tmp_db) == 3 assert calls == [None, "next"] +@pytest.mark.asyncio +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]]) +async def test_local_table_exists_without_listing( + tmp_path, monkeypatch, namespace_path +): + db = lancedb.connect(tmp_path) + for depth in range(1, len(namespace_path) + 1): + db.create_namespace(namespace_path[:depth]) + db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path) + if not namespace_path: + for idx in range(100): + (tmp_path / f"a{idx:03}.lance").mkdir() + assert "events" not in db.list_tables().tables + adb = await lancedb.connect_async(tmp_path) + + def fail_listing(*args, **kwargs): + raise AssertionError("Existence checks must not list tables") + + monkeypatch.setattr(db, "list_tables", fail_listing) + monkeypatch.setattr(adb, "list_tables", fail_listing) + table_id = namespace_path + ["events"] + assert db.table_exists(table_id) is True + assert await adb.table_exists(table_id) is True + assert db.table_exists(namespace_path + ["missing"]) is False + assert await adb.table_exists(namespace_path + ["missing"]) is False + assert ("events" in db) is (not namespace_path) + assert "missing" not in db + assert table_id == namespace_path + ["events"] + + db.drop_table("events", namespace_path=namespace_path) + assert db.table_exists(table_id) is False + assert await adb.table_exists(table_id) is False + + @pytest.mark.asyncio async def test_table_names_async(tmp_path): db = lancedb.connect(tmp_path) diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 5eb9c02bd..9bce1059d 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -34,6 +34,27 @@ PUSHDOWN_DATA = pa.table( ) +@pytest.mark.asyncio +@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) +async def test_custom_namespace_table_exists_uses_namespace_api(table_id): + class ExistenceNamespace(LanceNamespace): + def namespace_id(self): + return "existence-test" + + def table_exists(self, request): + if request.id == ["missing"]: + raise TableNotFoundError("Table not found") + + def describe_table(self, request): + raise AssertionError("Custom existence checks must not open tables") + + namespace = ExistenceNamespace() + db = LanceNamespaceDBConnection(namespace) + adb = lancedb.AsyncLanceNamespaceDBConnection(namespace) + assert db.table_exists(table_id) is (table_id != ["missing"]) + assert await adb.table_exists(table_id) is (table_id != ["missing"]) + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -411,8 +432,16 @@ class TestNamespaceConnection: assert "test_ns" in db.list_namespaces().namespaces schema = pa.schema([pa.field("id", pa.int64())]) + db.create_table("root_table", schema=schema) + assert db.table_exists(["root_table"]) is True + assert "root_table" in db + assert db.table_exists(["missing"]) is False + assert "missing" not in db table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"]) assert table.namespace == ["test_ns"] + assert db.table_exists(["test_ns", "test_table"]) is True + assert db.table_exists(["test_ns", "missing"]) is False + assert "test_table" not in db assert "test_table" in db.table_names(namespace_path=["test_ns"]) assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables @@ -420,7 +449,10 @@ class TestNamespaceConnection: assert opened.namespace == ["test_ns"] db.drop_table("test_table", namespace_path=["test_ns"]) + assert db.table_exists(["test_ns", "test_table"]) is False assert db.list_tables(namespace_path=["test_ns"]).tables == [] + db.drop_table("root_table") + assert "root_table" not in db db.drop_namespace(["test_ns"]) assert "test_ns" not in db.list_namespaces().namespaces @@ -942,12 +974,18 @@ class TestAsyncNamespaceConnection: assert "test_ns" in (await db.list_namespaces()).namespaces schema = pa.schema([pa.field("id", pa.int64())]) + await db.create_table("root_table", schema=schema) + assert await db.table_exists(["root_table"]) is True + assert await db.table_exists(["missing"]) is False table = await db.create_table( "test_table", schema=schema, namespace_path=["test_ns"] ) assert table._namespace_path == ["test_ns"] assert table._namespace_client is None assert table._route_pushdown_to_rust is True + assert await db.table_exists(["test_ns", "test_table"]) is True + assert await db.table_exists(["test_ns", "missing"]) is False + assert await db.table_exists(["test_table"]) is False assert "test_table" in await db.table_names(namespace_path=["test_ns"]) assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables @@ -955,7 +993,10 @@ class TestAsyncNamespaceConnection: assert opened._namespace_path == ["test_ns"] await db.drop_table("test_table", namespace_path=["test_ns"]) + assert await db.table_exists(["test_ns", "test_table"]) is False assert (await db.list_tables(namespace_path=["test_ns"])).tables == [] + await db.drop_table("root_table") + assert await db.table_exists(["root_table"]) is False await db.drop_namespace(["test_ns"]) assert "test_ns" not in (await db.list_namespaces()).namespaces diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 407596d26..952437051 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -22,6 +22,7 @@ import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch import uuid +import warnings from packaging.version import Version from lance_namespace.errors import TableNotFoundError @@ -461,6 +462,31 @@ def test_remote_table_exists_rechecks_cached_table(): assert requests == ["/v1/table/ns$table/describe/"] * 2 +@pytest.mark.parametrize("status", [200, 404, 403]) +def test_remote_membership_uses_direct_lookup(status): + requests = [] + + def handler(request): + requests.append(request.path) + assert request.command == "POST" + assert request.path == "/v1/table/t129/describe/" + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}" if status == 200 else b"lookup failed") + + with mock_lancedb_connection(handler) as db: + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + if status in (200, 404): + assert ("t129" in db) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + "t129" in db + assert exc_info.value.status_code == status + assert requests == ["/v1/table/t129/describe/"] + + def paginated_table_listing_handler(request): url = urlparse(request.path) assert url.path in { diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py index a12efd0c9..230fb45c6 100644 --- a/python/python/tests/test_sync_api_parity.py +++ b/python/python/tests/test_sync_api_parity.py @@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table): ] -def respond(request, body): - request.send_response(200) +def respond(request, body, status=200): + request.send_response(status) request.send_header("Content-Type", "application/json") request.end_headers() request.wfile.write(json.dumps(body).encode()) @@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute): @pytest.mark.parametrize("tables", [[], ["first", "last"]]) -def test_remote_len_and_contains_follow_pages(tables): +def test_remote_len_paginates_and_contains_looks_up_table(tables): requests = [] def handler(request): requests.append(request.path) - query = parse_qs(urlparse(request.path).query) + url = urlparse(request.path) + if request.command == "POST": + name = url.path.split("/")[3] + assert url.path == f"/v1/table/{name}/describe/" + respond(request, {}, status=200 if name in tables else 404) + return + assert request.command == "GET" + assert url.path == "/v1/namespace/$/table/list" + query = parse_qs(url.query) if tables and "page_token" not in query: respond(request, {"tables": [tables[0]], "page_token": "opaque-next"}) else: @@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables): with mock_lancedb_connection(handler) as db: assert len(db) == len(tables) - assert ("last" in db) == bool(tables) - assert "missing" not in db + assert len(requests) == (2 if tables else 1) requests.clear() - assert ("first" in db) == bool(tables) - assert len(requests) == 1 + for name in ("last", "missing", "first"): + assert (name in db) is (name in tables) + assert requests == [f"/v1/table/{name}/describe/"] + requests.clear() @pytest.mark.parametrize("namespace", [[], ["parent", "child"]]) From 1dee9b006caf2d02de96daf3db3c3bf37c56633b Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Wed, 11 Nov 2026 23:32:57 -0800 Subject: [PATCH 3/8] fix(python): reject unsupported Function callables early (#4972) Reject synchronous and asynchronous generator Functions, including class `__call__` methods, during decoration so invalid outputs never reach remote execution. Give actionable errors for lambdas and decorated wrappers such as `functools.lru_cache`. Defaulted callable inputs remain unsupported; the error now names the parameter and explains how to use class initialization fields. ```python @function def double(value: float) -> float: yield value * 2 # TypeError: generator Functions are not supported; return a value instead of # yielding, or return a list for multiple values ``` The deprecated `@udf` alias shares the validation. Adds regression coverage for both decorators, class methods, explicit schemas, and the supported list-return alternative. Fixes https://linear.app/lancedb/issue/ENT-3539 --- python/python/lancedb/functions.py | 39 ++++++- .../python/tests/test_function_packaging.py | 104 +++++++++++++++++- 2 files changed, 138 insertions(+), 5 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 4bf028306..74cc2adf4 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1298,6 +1298,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError(f"unsupported Function annotation: {annotation!r}") +def _validate_callable(function: Any) -> None: + if hasattr(function, "__wrapped__"): + raise TypeError( + "decorated wrappers are not supported; put caching inside the function " + "body or use a class Function with a cache in __init__" + ) + if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function): + raise TypeError( + "generator Functions are not supported; return a value instead of " + "yielding, or return a list for multiple values" + ) + if inspect.isfunction(function) and function.__name__ == "": + raise TypeError("lambda Functions are not supported; use a named def instead") + + def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Parameter, ...]: parameters = tuple(inspect.signature(function).parameters.values()) for parameter in parameters: @@ -1308,7 +1323,11 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete ): raise TypeError("Function callables require named, non-variadic parameters") if parameter.default is not inspect.Parameter.empty: - raise TypeError("Function callable defaults are not supported") + raise TypeError( + f"Function callable defaults are not supported: {parameter.name!r}; " + "move configuration parameters to a class Function's __init__ " + "and pass them as binding-time initialization values" + ) return parameters @@ -2201,6 +2220,7 @@ def _class_member(cls: type, name: str) -> Any: def _class_call(cls: type) -> Callable[..., Any]: call = _class_member(cls, "__call__") + _validate_callable(call) if not inspect.isfunction(call) or inspect.iscoroutinefunction(call): raise TypeError("a class Function must define a synchronous __call__ method") close = _class_member(cls, "close") @@ -2257,12 +2277,10 @@ class FunctionDefinition: if not is_class and ( not inspect.isfunction(function) or inspect.iscoroutinefunction(function) ): + _validate_callable(function) raise TypeError( "@function requires a synchronous Python function or a class" ) - function_name = name or function.__name__ - if not _FUNCTION_NAME.fullmatch(function_name): - raise ValueError(f"invalid Function name: {function_name!r}") if pip and conda: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: @@ -2324,6 +2342,11 @@ class FunctionDefinition: "model Functions reserve environment variables " f"{reserved!r}; the worker sets them for the private snapshot" ) + if not is_class: + _validate_callable(function) + function_name = name or function.__name__ + if not _FUNCTION_NAME.fullmatch(function_name): + raise ValueError(f"invalid Function name: {function_name!r}") if is_class: if "<" in function.__qualname__ or "." in function.__qualname__: raise ValueError( @@ -2555,6 +2578,14 @@ def function( reuses them. An instance serves many batches of one binding, so state is shared across them, but not across instances or workers. + Functions and ``__call__`` methods must return a value. Generators, + including async generators, are not supported; return a list to produce + multiple values for a list output. Lambdas and decorated wrappers such as + ``functools.lru_cache`` are not supported. Use a named ``def`` and keep + caches inside the body or in a class instance initialized by ``__init__``. + Callable input parameters cannot have defaults; move configurable values + to class initialization fields instead. + **Initialization.** The annotated parameters of a class's ``__init__`` are the Function's initialization fields. Their values belong to each binding, not to the Function: ``function(text=col("body"), model="small")`` diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 83dfdaeb3..440adc4da 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,7 +20,7 @@ import pyarrow as pa import pytest from lancedb import col -from lancedb.functions import FunctionDefinition, FunctionVersion, function +from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf FIXTURES = ( Path(__file__).parents[3] @@ -127,6 +127,108 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_schemas", [False, True]) +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize( + ("declaration", "statement"), + [ + ("def", "yield value"), + ("def", "yield from [value]"), + ("async def", "yield value"), + ], +) +def test_generator_functions_are_rejected_at_decoration( + helper_package, decorator, explicit_schemas, class_function, declaration, statement +): + signature = ( + "__call__(self, value: int)" if class_function else "generates(value: int)" + ) + source = f"{declaration} {signature} -> int:\n {statement}\n" + if class_function: + source = "class generates:\n" + textwrap.indent(source, " ") + module = helper_package("fx_generator", {"__init__.py": source}) + options = ( + { + "input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]), + "output_schema": pa.int64(), + } + if explicit_schemas + else {} + ) + with pytest.raises(TypeError) as error: + decorator(**options)(module.generates) + message = str(error.value) + assert "generator Functions are not supported" in message + assert "return a value" in message + assert "return a list" in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_name", [False, True]) +def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name): + options = {"name": "double"} if explicit_name else {} + with pytest.raises(TypeError, match="lambda.*use a named def"): + decorator(**options)(lambda value: value * 2) + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"]) +def test_cached_functions_explain_where_to_keep_caches( + helper_package, class_function, cache_decorator +): + signature = "__call__(self, value: int)" if class_function else "cached(value: int)" + source = ( + f"@functools.{cache_decorator}\ndef {signature} -> int:\n return value * 2\n" + ) + if class_function: + source = "class cached:\n" + textwrap.indent(source, " ") + module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source}) + with pytest.raises(TypeError) as error: + function(module.cached) + message = str(error.value) + assert "decorated wrappers are not supported" in message + assert "inside the function body" in message + assert "class Function with a cache in __init__" in message + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("keyword_only", [False, True]) +def test_callable_defaults_explain_class_initialization( + helper_package, class_function, keyword_only +): + parameters = "value: float, " + ("*, " if keyword_only else "") + parameters += "threshold: float = 0.5" + signature = ( + f"__call__(self, {parameters})" + if class_function + else f"thresholded({parameters})" + ) + source = f"def {signature} -> bool:\n return value >= threshold\n" + if class_function: + source = "class thresholded:\n" + textwrap.indent(source, " ") + module = helper_package("fx_defaults", {"__init__.py": source}) + with pytest.raises(TypeError) as error: + function(module.thresholded) + message = str(error.value) + assert "defaults are not supported: 'threshold'" in message + assert "class Function's __init__" in message + assert "binding-time initialization values" in message + + +def test_function_can_return_a_list_from_a_generator_expression(): + @function + def many(value: int) -> list[int]: + return list(item * 2 for item in range(value)) + + namespace = {} + exec(compile(artifact(many), "user_function.py", "exec"), namespace) + assert namespace["many"](3) == [0, 2, 4] + assert many.registration_request.signature.output.arrow_type == "list" + + @pytest.mark.parametrize("kind", ["function", "class"]) @pytest.mark.parametrize( ("global_value", "value_type"), From 5a38066234552fc1bd9826d12d71fc88fd64be93 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 12 Nov 2026 16:09:13 +0800 Subject: [PATCH 4/8] chore(deps): upgrade Lance to v15.0.0-beta.18 (#4965) Upgrade the Rust Lance dependency, Java lance-core, and Python test dependency from beta.17 to the officially published [v15.0.0-beta.18](https://github.com/lance-format/lance/releases/tag/v15.0.0-beta.18) (`079fd77683a7acf056b0912f6ecda938e39ee120`). This provides a compatible SDK for the newer Lance source already adopted downstream. Rust registry versions and checksums are unchanged; the Python lock uses the six published beta.18 wheels. ### Compatibility The adopted release includes [Lance #10863](https://github.com/lance-format/lance/pull/10863): `FilteredReadOptionsProto.has_fragment_ids` distinguishes an explicit empty fragment selection. Older executors ignore this field, so upgrade executors before relying on the corrected empty-selection behavior. Rust callers constructing this generated struct need the new field. [Lance #10112](https://github.com/lance-format/lance/pull/10112) also replaces the internal `hamming_distance_batch` API with `hamming_distance_batch_into`. The Linux Python matrix timeout is raised from 30 to 60 minutes: the Python 3.13 cold native build and both test passes completed, but the job hit its limit during cleanup. Build profiles, test commands, and coverage are unchanged. ### Validation - Three native FRI/ANN regressions passed: deferred-compaction refined RQ, deferred index remapping, and approximate-query builder. - `cargo clippy --quiet --locked --features remote --tests --examples -- -D warnings` passed with pinned Rust 1.97.0. - Locked metadata, formatting, Python Makefile-scope Ruff checks, and `uv lock --check --offline` passed. - YAML, whitespace, end-of-file, and typo checks passed for the timeout-only workflow change. ### Publication and CI Java beta.18 is now published. After [Lance #10968](https://github.com/lance-format/lance/pull/10968) merged, the [normal publication workflow](https://github.com/lance-format/lance/actions/runs/43146352505) built all three JNI targets and published successfully; the Maven jar is available. The upstream Python publication run was cancelled after its Windows ARM job hit the one-hour timeout; six other wheels were published and are the actual artifacts recorded in this lock. Cross-platform SDK CI is still required. No performance claim is made by this dependency update. --- .github/workflows/python.yml | 3 +- Cargo.lock | 96 ++++++++++++++++++------------------ Cargo.toml | 30 +++++------ java/pom.xml | 2 +- python/pyproject.toml | 2 +- python/uv.lock | 16 +++--- 6 files changed, 75 insertions(+), 74 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2fabb4a6a..e208ac7cd 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -130,7 +130,8 @@ jobs: run: pytest --doctest-modules python/lancedb linux: name: "Linux: python-3.${{ matrix.python-minor-version }}" - timeout-minutes: 30 + # A cold native build plus both test passes can exhaust 30 minutes. + timeout-minutes: 60 strategy: matrix: python-minor-version: ["10", "13"] diff --git a/Cargo.lock b/Cargo.lock index f38252fc5..4e6d2665a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3825,8 +3825,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5313,8 +5313,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5389,8 +5389,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5412,7 +5412,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.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5426,7 +5426,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.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5435,8 +5435,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrayref", "crunchy", @@ -5446,8 +5446,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5485,8 +5485,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5517,8 +5517,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5543,8 +5543,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5561,8 +5561,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "proc-macro2", "quote", @@ -5571,8 +5571,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5605,8 +5605,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5637,8 +5637,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5669,8 +5669,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5742,8 +5742,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5766,8 +5766,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5812,8 +5812,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "byteorder", "ethnum", @@ -5830,8 +5830,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "argminmax 0.7.1", "arrow-array", @@ -5846,8 +5846,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "async-trait", @@ -5861,8 +5861,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5916,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5931,8 +5931,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5973,8 +5973,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5987,8 +5987,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 9fc33e6ab..c45eef6da 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.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "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 610c095b9..9356288dc 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.17 + 15.0.0-beta.18 2.18.12 false 2.30.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index 5ba1d4bbf..6940dce4f 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.0b17", + "pylance==15.0.0b18", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/uv.lock b/python/uv.lock index 01693079f..369d558d2 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.0b17" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b18" }, { 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.0b17" +version = "15.0.0b18" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,12 @@ 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_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" }, - { url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" }, - { url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, ] [[package]] From 01e9ea44aa0609630cec2f3f728198a36374befd Mon Sep 17 00:00:00 2001 From: Lance Release Date: Thu, 12 Nov 2026 08:12:34 +0000 Subject: [PATCH 5/8] =?UTF-8?q?Bump=20version:=200.42.0-beta.11=20?= =?UTF-8?q?=E2=86=92=200.42.0-beta.12?= 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 076443831..e4989d1eb 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.11" +current_version = "0.42.0-beta.12" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 4e6d2665a..efe0338cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6001,7 +6001,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "ahash", "anyhow", @@ -6112,7 +6112,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "anyhow", "arrow-array", @@ -6155,7 +6155,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arrow-array", "arrow-buffer", @@ -6180,7 +6180,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arc-swap", "arrow", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index c06b4f230..ca77b251c 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.11 + 0.42.0-beta.12 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 903be2b77..792b434a1 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.11 + 0.42.0-beta.12 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9356288dc..df709fb4f 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 91d808647..22cfe6ecc 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.11" +version = "0.42.0-beta.12" 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 1a9011b34..283a32fdc 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.11", + "version": "0.42.0-beta.12", "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 00b2918d6..5fd392245 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.11", + "version": "0.42.0-beta.12", "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 f94f27216..ec5103284 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.11", + "version": "0.42.0-beta.12", "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 e0eefa2e9..1d45a2ed2 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.11", + "version": "0.42.0-beta.12", "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 f0891fbed..d17a3b4e7 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.11", + "version": "0.42.0-beta.12", "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 04b65ba86..a7c4a74b6 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.11", + "version": "0.42.0-beta.12", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e5e0effab..0e3a4a626 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.11", + "version": "0.42.0-beta.12", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a03e1a794..b0d99fb60 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 7c11d5fdf..5a2923216 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index cbb0142e1..737c385c1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" 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 cde8b295a..b22a3b8d8 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.11" +version = "0.42.0-beta.12" edition = "2021" license.workspace = true repository.workspace = true From 478d1d9b0103971dbd31be655bfb7e5073995bd5 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 00:30:19 -0800 Subject: [PATCH 6/8] fix: expose comparable Function runtime identity (#4975) Expose `FunctionVersion.runtime_digest` through Rust and Python, and add `PythonRuntimeSpec.digest` so clients can compare declared environment inputs before registering a Function. Dependency pins, environment variables, Python version, and GPU settings affect this digest; package ordering does not. Clarify that matching `source_digest` alone is insufficient for reuse. Older servers/images leave `runtime_digest` unset, which cannot establish a match. Both digests and the other registration inputs must match before reusing a version. ```python request = definition.registration_request same_source = version.source_digest == request.artifact.digest same_runtime = version.runtime_digest == request.runtime.digest ``` Add shared runtime digest fixtures and coverage for environment-only changes and catalog decoding. Local builds and tests were skipped as requested. --- python/python/lancedb/functions.py | 39 +++ .../tests/test_first_class_function_slice1.py | 34 ++- .../tests/test_first_class_function_slice2.py | 28 ++ python/python/tests/test_remote_db.py | 3 + rust/lancedb/src/function.rs | 39 ++- .../v1/runtime_identity.json | 269 ++++++++++++++++++ 6 files changed, 410 insertions(+), 2 deletions(-) create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 74cc2adf4..a5c741cd8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -495,6 +495,35 @@ class PythonRuntimeSpec(_RemoteValue): object.__setattr__(self, "gpu_class", None) return self + @property + def digest(self) -> str: + """SHA-256 identity of the declared runtime, before building an image. + + Covers Python version, environment sources, environment variables, and + GPU settings. Package and system-package order is ignored; conda channel + order is preserved. Compare with ``runtime_digest`` on + [FunctionVersion][lancedb.functions.FunctionVersion]. + This identifies build inputs, not the resolved contents of unpinned + dependencies or the deployment's default base image. + """ + if self.kind not in {"python", "python_v2"}: + raise ValueError(f"cannot digest unknown runtime kind {self.kind!r}") + value = self._known_dict() + if not value.get("env"): + value.pop("env", None) + environment = value["environment"] + for field in ("packages", "system_packages"): + if field in environment: + environment[field] = sorted(environment[field]) + encoded = json.dumps( + value, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return f"sha256:{hashlib.sha256(encoded).hexdigest()}" + class FunctionImage(_RemoteValue): """A complete OCI Function image identified by its exact manifest digest.""" @@ -536,8 +565,17 @@ class FunctionVersion(_RemoteValue): of the built ``image``. Compare it with ``definition.registration_request.artifact.digest`` to check whether a local [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source. + It does not cover dependencies, environment variables, Python version, or + GPU settings. Equal source digests alone do not mean a version can be reused. It is ``None`` when the server does not provide a source digest. + ``runtime_digest`` identifies the declared environment inputs. Compare it + with ``definition.registration_request.runtime.digest`` to check whether + the local runtime matches. It is ``None`` for images built before runtime + identity was exposed. A missing digest cannot establish a match. Reusing a + version also requires matching the source and all other registration inputs, + including signature, Secret bindings, models, and execution controls. + ``gpu_class`` is the operator-defined GPU pool fixed into this Function version, or ``None`` when registration used the deployment default. @@ -554,6 +592,7 @@ class FunctionVersion(_RemoteValue): version: _ObjectVersion image: FunctionImage source_digest: Optional[str] = None + runtime_digest: Optional[str] = None signature: FunctionSignature secret_bindings: tuple[SecretBinding, ...] = () created_at_millis: int diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index f8e225183..867672fe9 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -34,7 +34,7 @@ FIXTURES = ( def fixture(name: str) -> str: - return (FIXTURES / name).read_text() + return (FIXTURES / name).read_text(encoding="utf-8") def job_result(name: str) -> dict: @@ -148,6 +148,38 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize( + "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"] +) +def test_runtime_digests_match_server_golden_values(case): + runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"])) + assert runtime.digest == case["digest"] + assert ( + PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest + == runtime.digest + ) + + +def test_unknown_runtime_digest_fails_closed(): + runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}') + with pytest.raises(ValueError, match="cannot digest unknown runtime kind"): + runtime.digest + + +@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"]) +def test_function_version_preserves_runtime_digest(runtime_digest): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.runtime_digest is None + assert "runtime_digest" not in json.loads(legacy.to_canonical_json()) + value["runtime_digest"] = runtime_digest + version = FunctionVersion.from_json(json.dumps(value)) + assert version.runtime_digest == runtime_digest + assert FunctionVersion.from_json(version.to_canonical_json()) == version + with pytest.raises((TypeError, ValueError)): + version.runtime_digest = "sha256:changed" + + @pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"]) def test_function_version_preserves_source_digest(source_digest): value = job_result("remote_function_job.json") diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 2cc731892..d99a7aa21 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1891,6 +1891,29 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): return value +def test_default_function_runtime_matches_server_identity(): + definition = function(python_version="3.12")(analyze_caption.__wrapped__) + runtime = definition.registration_request.runtime + assert runtime.env == {} + cases = json.loads((FIXTURES / "runtime_identity.json").read_text(encoding="utf-8")) + expected = next( + case["digest"] for case in cases if case["name"] == "empty-environment" + ) + assert runtime.digest == expected + + +def test_environment_changes_do_not_change_source_identity(): + definition = function( + pip=["openai==3.46.0"], + env={"MODE": "test"}, + python_version="3.12", + )(analyze_caption.__wrapped__) + previous = analyze_caption.registration_request + changed = definition.registration_request + assert previous.artifact.digest == changed.artifact.digest + assert previous.runtime.digest != changed.runtime.digest + + def test_local_function_catalog_operations_are_not_supported(tmp_path): db = lancedb.connect(tmp_path) message = "Function catalog operations are not supported by this database" @@ -1950,6 +1973,7 @@ async def test_async_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -1977,6 +2001,7 @@ def test_sync_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -2090,6 +2115,9 @@ def _mock_remote_function_catalog(): )["image"], "signature": body["signature"], "source_digest": body["artifact"]["digest"], + "runtime_digest": PythonRuntimeSpec.from_json( + json.dumps(body["runtime"]) + ).digest, "secret_bindings": body.get("secret_bindings", []), "created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z } diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 952437051..b0098aca3 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -6304,6 +6304,8 @@ def test_remote_function_registration_transports_max_concurrency(): def registered(value: float) -> float: return value + definition["runtime_digest"] = registered.registration_request.runtime.digest + class RegistrationServer(flight.FlightServerBase): def __init__(self): super().__init__("grpc://127.0.0.1:0") @@ -6322,6 +6324,7 @@ def test_remote_function_registration_transports_max_concurrency(): assert len(server.tickets) == 1 assert b'"max_concurrency":4' in server.tickets[0] assert version.max_concurrency == 4 + assert version.runtime_digest == registered.registration_request.runtime.digest @pytest.mark.asyncio diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 3566fc938..e3d47948e 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -594,6 +594,8 @@ pub struct FunctionVersion { image: FunctionImage, #[serde(default, skip_serializing_if = "Option::is_none")] source_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -665,7 +667,9 @@ impl FunctionVersion { /// Digest of the registered source artifact, when provided by the server. /// /// Compare this with [`FunctionArtifactRequest::digest`] to identify matching - /// source, independently of the built image's manifest digest. + /// source, independently of the built image's manifest digest. It excludes + /// dependencies, environment variables, Python version, and GPU settings; + /// matching source alone does not establish that a version can be reused. /// /// ``` /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; @@ -678,6 +682,15 @@ impl FunctionVersion { self.source_digest.as_deref() } + /// Digest of canonical runtime inputs, when provided by the server. + /// + /// Includes Python version, environment sources, variables, and GPU settings. + /// A missing digest cannot establish that a local runtime matches. Reusing a + /// version also requires matching its source and other registration inputs. + pub fn runtime_digest(&self) -> Option<&str> { + self.runtime_digest.as_deref() + } + /// Operator-defined GPU class declared at registration. pub fn gpu_class(&self) -> Option<&str> { self.gpu_class.as_deref() @@ -1329,6 +1342,30 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_runtime_digest() { + 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_eq!(legacy.runtime_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + for digest in [Value::Null, serde_json::json!("sha256:runtime-inputs")] { + document["runtime_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime_digest(), digest.as_str()); + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + if digest.is_null() { + assert!(encoded_value.get("runtime_digest").is_none()); + } else { + assert_eq!(encoded_value["runtime_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + #[test] fn function_version_preserves_source_digest() { const VERSION: &str = include_str!( diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json new file mode 100644 index 000000000..7bf0c375c --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json @@ -0,0 +1,269 @@ +[ + { + "name": "pip", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "reordered-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy==2.2.0", + "openai==3.40.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "changed-pin", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.46.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:43da49cfcf8ecd47becb5be20b9eff06c5267f9244c18e751b230c624f5ad12a" + }, + { + "name": "changed-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "prod", + "LABEL": "你好" + } + }, + "digest": "sha256:9b305e9188f4ddda5a0b72d2235c2c46ba50de9bf82c699f5060b02e4aa0820d" + }, + { + "name": "changed-python", + "runtime": { + "kind": "python", + "python_version": "3.11", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:8fa58561581414b02d0619e466e3720828d1820d8211b0e73c90ec4b0d3ecd0c" + }, + { + "name": "gpu", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true + }, + "digest": "sha256:3ea9354ff101038937b1f5a3b6639c4cc6dcb88ee975dcb8e1a5dee2500c283c" + }, + { + "name": "gpu-class", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true, + "gpu_class": "a100" + }, + "digest": "sha256:253f0641ef029aed8337bbcb210f7769147d671747406f7ce4fa5dc40d5c5efc" + }, + { + "name": "conda", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "conda-forge", + "defaults" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:9246f88a6b1daceb3090c51930650ea967947142cdc70737c847a6bf72c85d30" + }, + { + "name": "reordered-channels", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "defaults", + "conda-forge" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:12ef13a6f5b8730a719288ab2406e7f6c13634b14dbef2390f0bbe62f847e18d" + }, + { + "name": "system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "zlib1g", + "ffmpeg" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "reordered-system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "ffmpeg", + "zlib1g" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "empty-environment", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + } + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-fields", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [], + "channels": [], + "modules": [], + "system_packages": [] + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + } +] From 7b2dfb9e361bddfbf4b3e16f2d950f377d5b5e33 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:19:05 -0800 Subject: [PATCH 7/8] fix(python): align catalog and database connection inputs (#4983) Align Python catalog connection inputs with database connections, warn when region is ignored, and preserve remote storage settings in opened databases. --- docs/web/basics/catalog.mdx | 18 +++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/catalog.py | 154 ++++++++++++++++++++++-- python/python/lancedb/remote/db.py | 3 +- python/python/tests/test_catalog.py | 176 +++++++++++++++++++++++++++- python/python/type_tests/connect.py | 20 +++- python/src/catalog.rs | 8 +- rust/lancedb/src/catalog.rs | 12 ++ rust/lancedb/src/remote/catalog.rs | 10 ++ rust/lancedb/src/remote/db.rs | 2 +- 10 files changed, 389 insertions(+), 15 deletions(-) diff --git a/docs/web/basics/catalog.mdx b/docs/web/basics/catalog.mdx index 1e95aeca4..519d86067 100644 --- a/docs/web/basics/catalog.mdx +++ b/docs/web/basics/catalog.mdx @@ -158,6 +158,24 @@ list, create and drop databases across the whole deployment. Its `connect_database(name)` and `create_database(name)` then return the same kind of database connection `lancedb.connect()` does. +In Python, `connect_catalog` and `connect_catalog_async` accept the same +connection settings as their database counterparts. Use `host_override` to +share settings that include a `db://` URI; the catalog connection targets +the root of that deployment and ignores the database name. An explicitly +supplied `region` is ignored with a warning, since the HTTP(S) endpoint +selects the deployment. Embedded-only session and namespace settings are +unsupported. + +```python +settings = { + "uri": "db://analytics", + "api_key": "secret", + "host_override": "https://my-server.example", +} +db = lancedb.connect(**settings) +catalog = lancedb.connect_catalog(**settings) +``` + This connection is for database administration, not table or query work: list, create and drop databases through it, then switch to a **database** connection for everything else -- tables, queries, and SQL all run within a diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 521cc46bb..11798a520 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1227,6 +1227,7 @@ async def connect_catalog( sql_host_override: Optional[str] = None, read_consistency_interval: Optional[float] = None, oauth_config: Optional[Any] = None, + storage_options: Optional[dict[str, str]] = None, ) -> Catalog: ... class NameListing: diff --git a/python/python/lancedb/catalog.py b/python/python/lancedb/catalog.py index 338be98b8..5b3b0509c 100644 --- a/python/python/lancedb/catalog.py +++ b/python/python/lancedb/catalog.py @@ -3,13 +3,17 @@ """Remote catalogs manage databases.""" -from functools import cached_property +import os +import warnings +from concurrent.futures import ThreadPoolExecutor from datetime import timedelta +from functools import cached_property from typing import Any, AsyncIterator, Iterator, Optional, Union from . import _lancedb from .background_loop import LOOP from .authz import AsyncAuthorization, Authorization +from .common import URI, sanitize_uri from .db import AsyncConnection, DBConnection from .remote import ClientConfig, OAuthConfig from .remote.db import RemoteDBConnection @@ -163,12 +167,14 @@ class Catalog: client_config=None, sql_host_override: Optional[str] = None, oauth_config: Optional[OAuthConfig] = None, + storage_options: Optional[dict[str, str]] = None, ): self._inner = inner self._api_key = api_key self._client_config = client_config self._sql_host_override = sql_host_override self._oauth_config = oauth_config + self._storage_options = storage_options @cached_property def authz(self) -> Authorization: @@ -198,6 +204,7 @@ class Catalog: self._client_config, self._oauth_config, self._sql_host_override, + self._storage_options, ) def list_databases( @@ -227,28 +234,71 @@ class Catalog: async def connect_catalog_async( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_properties: Optional[dict[str, str]] = None, oauth_config: Optional[OAuthConfig] = None, ) -> AsyncCatalog: - """Connect to an HTTP(S) server's root catalog. + """Connect to a server's root catalog using database connection settings. + + ``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise + ``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with + [connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's + database is ignored and requests target the root catalog. + + ``region`` is ignored with a warning when supplied. Catalog connections use + the explicit endpoint rather than a region-derived Cloud (legacy) endpoint. + ``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable. + Embedded-only ``session``, ``manifest_enabled`` and + ``namespace_client_properties`` are not supported. Root requests omit database-selection headers. API key, client configuration, - OAuth, and table read consistency settings are inherited by opened databases. + OAuth, storage options, and table read consistency settings are inherited by + opened databases. Database names containing slashes remain single logical names. Set ``sql_host_override`` to the SQL service endpoint to execute SQL through returned connections when the catalog endpoint uses HTTPS. """ + if region is not None: + warnings.warn( + "region is ignored by connect_catalog_async; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + for name, value in ( + ("session", session), + ("manifest_enabled", manifest_enabled or None), + ("namespace_client_properties", namespace_client_properties), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + endpoint = host_override if host_override is not None else uri + if endpoint is None: + raise ValueError("uri or host_override is required for catalog connections") if isinstance(client_config, dict): client_config = ClientConfig(**client_config) if client_config is None: client_config = ClientConfig() + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") inner = await _lancedb.connect_catalog( - endpoint, + sanitize_uri(endpoint), api_key=api_key, client_config=client_config, sql_host_override=sql_host_override, @@ -258,32 +308,115 @@ async def connect_catalog_async( else None ), oauth_config=oauth_config, + storage_options=storage_options, ) return AsyncCatalog(inner) def connect_catalog( - endpoint: str, + uri: Optional[URI] = None, *, api_key: Optional[str] = None, - client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + region: Optional[str] = None, + host_override: Optional[str] = None, sql_host_override: Optional[str] = None, read_consistency_interval: Optional[timedelta] = None, + request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None, + client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None, + storage_options: Optional[dict[str, str]] = None, + session: Optional[_lancedb.Session] = None, + manifest_enabled: bool = False, + namespace_client_impl: Optional[str] = None, + namespace_client_properties: Optional[dict[str, str]] = None, + namespace_client_pushdown_operations: Optional[list[str]] = None, oauth_config: Optional[OAuthConfig] = None, + **kwargs: Any, ) -> Catalog: - """Connect synchronously to an HTTP(S) server's root catalog. + """Connect synchronously to a root catalog using database connection settings. See [connect_catalog_async][lancedb.connect_catalog_async] for options. + The inputs match [connect][lancedb.connect]; ``region`` is ignored with a + warning when supplied. Namespace client options and embedded session settings + are not supported. ``request_thread_pool`` is deprecated and unused, as in + ``connect``. Local filesystem and object-store catalogs are not supported. + + Examples + -------- + ```python + settings = {"api_key": "secret", "host_override": "https://my-server.example"} + catalog = lancedb.connect_catalog("db://analytics", **settings) + db = lancedb.connect("db://analytics", **settings) + ``` """ + unknown_kwargs = { + key: value + for key, value in kwargs.items() + if key not in ("connection_timeout", "read_timeout") + } + if unknown_kwargs: + raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}") + for name, value in ( + ("namespace_client_impl", namespace_client_impl), + ("namespace_client_pushdown_operations", namespace_client_pushdown_operations), + ): + if value is not None: + raise NotImplementedError( + f"{name} is not supported for catalog connections" + ) + if region is not None: + warnings.warn( + "region is ignored by connect_catalog; the catalog endpoint " + "is selected by host_override or uri.", + UserWarning, + stacklevel=2, + ) + if request_thread_pool is not None: + warnings.warn( + "request_thread_pool is no longer used and will be removed in " + "a future release.", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(client_config, dict): + client_config = ClientConfig(**client_config) + if client_config is None: + client_config = ClientConfig() + for name, field in ( + ("connection_timeout", "connect_timeout"), + ("read_timeout", "read_timeout"), + ): + if kwargs.get(name) is not None: + warnings.warn( + f"{name} is deprecated and will be removed in a future release. " + f"Please use client_config.timeout_config.{field} instead.", + DeprecationWarning, + stacklevel=2, + ) + setattr( + client_config.timeout_config, + field, + timedelta(seconds=kwargs[name]), + ) + if ( + api_key is None + and oauth_config is None + and client_config.header_provider is None + ): + api_key = os.environ.get("LANCEDB_API_KEY") return Catalog( LOOP.run( connect_catalog_async( - endpoint, + uri, api_key=api_key, + host_override=host_override, client_config=client_config, sql_host_override=sql_host_override, read_consistency_interval=read_consistency_interval, + storage_options=storage_options, + session=session, + manifest_enabled=manifest_enabled, + namespace_client_properties=namespace_client_properties, oauth_config=oauth_config, ) ), @@ -291,4 +424,5 @@ def connect_catalog( client_config=client_config, sql_host_override=sql_host_override, oauth_config=oauth_config, + storage_options=storage_options, ) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 21ad37b36..4219ca40b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -214,6 +214,7 @@ class RemoteDBConnection(DBConnection): client_config, oauth_config, sql_host_override, + storage_options, ): config = ( ClientConfig(**client_config) @@ -233,7 +234,7 @@ class RemoteDBConnection(DBConnection): result.region = "us-east-1" result.host_override = endpoint result.sql_host_override = sql_host_override - result.storage_options = None + result.storage_options = storage_options result.client_config = replace(config, extra_headers=headers) result._catalog_oauth = oauth_config is not None result._conn = inner diff --git a/python/python/tests/test_catalog.py b/python/python/tests/test_catalog.py index 95b03c6e7..edac21bc1 100644 --- a/python/python/tests/test_catalog.py +++ b/python/python/tests/test_catalog.py @@ -2,7 +2,9 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from datetime import timedelta import json +import warnings import pytest @@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): endpoint, api_key="secret", sql_host_override="invalid://localhost", + storage_options={"azure_storage_account_name": "catalog-account"}, client_config={ "extra_headers": { "X-LanceDB-Database": "wrong", @@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): assert db.table_names() == [] restored = lancedb.deserialize_conn(db.serialize()) assert restored.sql_host_override == "invalid://localhost" + assert restored.storage_options == {"azure_storage_account_name": "catalog-account"} for connection in (db, restored): with pytest.raises(ValueError, match="sql_host_override must use"): connection.execute_query_async("SELECT 1") @@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server): ) assert "x-lancedb-database-prefix" not in headers assert headers["x-api-key"] == "secret" + assert headers["x-azure-storage-account-name"] == "catalog-account" @pytest.mark.asyncio @@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server): ] ) catalog = await lancedb.connect_catalog_async( - endpoint, sql_host_override="invalid://localhost" + endpoint, + sql_host_override="invalid://localhost", + storage_options={"account_name": "async-account"}, ) assert isinstance(catalog, lancedb.AsyncCatalog) db = await catalog.connect_database("analytics") @@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server): await catalog.drop_database("full") await catalog.drop_database("missing", ignore_missing=True) assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"} + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-azure-storage-account-name"] == "async-account" @pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"]) @@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint): lancedb.connect_catalog(endpoint) +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"]) +@pytest.mark.asyncio +async def test_catalog_accepts_database_connection_settings( + catalog_server, asynchronous, region +): + endpoint, requests, responses = catalog_server + responses.extend([(200, {"namespaces": []}), (200, {"tables": []})]) + settings = { + "uri": "db://analytics", + "api_key": "shared-secret", + "region": region, + "host_override": endpoint, + "sql_host_override": "invalid://localhost", + "read_consistency_interval": timedelta(seconds=5), + "client_config": {"extra_headers": {"x-shared-setting": "shared"}}, + "storage_options": {"azure_storage_account_name": "shared-account"}, + "session": None, + "manifest_enabled": False, + "namespace_client_properties": None, + } + if not asynchronous: + settings.update( + request_thread_pool=None, + namespace_client_impl=None, + namespace_client_pushdown_operations=None, + ) + with pytest.warns( + UserWarning, match="region is ignored by connect_catalog" + ) as caught: + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert len(caught) == 1 + assert catalog.uri == endpoint + assert ( + [name async for name in catalog.list_databases()] + if asynchronous + else list(catalog.list_databases()) + ) == [] + db = ( + await lancedb.connect_async(**settings) + if asynchronous + else lancedb.connect(**settings) + ) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + root_headers = {key.lower(): value for key, value in requests[0][1].items()} + db_headers = {key.lower(): value for key, value in requests[1][1].items()} + for headers in (root_headers, db_headers): + assert headers["x-api-key"] == "shared-secret" + assert headers["x-shared-setting"] == "shared" + assert headers["x-azure-storage-account-name"] == "shared-account" + assert "x-lancedb-database" not in root_headers + assert db_headers["x-lancedb-database"] == "analytics" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize("host_only", [False, True]) +@pytest.mark.asyncio +async def test_catalog_default_region_is_silent_and_api_key_uses_environment( + catalog_server, monkeypatch, asynchronous, host_only +): + endpoint, requests, responses = catalog_server + monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret") + responses.extend([(200, {}), (200, {"tables": []})]) + settings = {"host_override": endpoint} if host_only else {"uri": endpoint} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert caught == [] + assert catalog.uri == endpoint + db = ( + await catalog.connect_database("analytics") + if asynchronous + else catalog.connect_database("analytics") + ) + if not asynchronous: + db = lancedb.deserialize_conn(db.serialize()) + assert (await db.table_names() if asynchronous else db.table_names()) == [] + for _, headers, _ in requests: + headers = {key.lower(): value for key, value in headers.items()} + assert headers["x-api-key"] == "environment-secret" + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.asyncio +async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous): + endpoint, _, _ = catalog_server + settings = {"uri": "https://unused.example", "host_override": endpoint} + catalog = ( + await lancedb.connect_catalog_async(**settings) + if asynchronous + else lancedb.connect_catalog(**settings) + ) + assert catalog.uri == endpoint + + +@pytest.mark.parametrize("asynchronous", [False, True]) +@pytest.mark.parametrize( + "options, message", + [ + ({}, "uri or host_override is required"), + ({"session": object()}, "session"), + ({"manifest_enabled": True}, "manifest_enabled"), + ({"namespace_client_properties": {}}, "namespace_client_properties"), + ], +) +@pytest.mark.asyncio +async def test_catalog_rejects_unsupported_connection_settings( + catalog_server, asynchronous, options, message +): + _, requests, _ = catalog_server + error = NotImplementedError if options else ValueError + with pytest.raises(error, match=message): + if asynchronous: + await lancedb.connect_catalog_async(**options) + else: + lancedb.connect_catalog(**options) + assert requests == [] + + +@pytest.mark.parametrize( + "options, error, message", + [ + ( + {"namespace_client_impl": "dir"}, + NotImplementedError, + "namespace_client_impl", + ), + ( + {"namespace_client_pushdown_operations": []}, + NotImplementedError, + "namespace_client_pushdown_operations", + ), + ({"unknown_option": True}, ValueError, "Unknown keyword arguments"), + ], +) +def test_catalog_rejects_unsupported_sync_settings(options, error, message): + with pytest.raises(error, match=message): + lancedb.connect_catalog(**options) + + +def test_catalog_accepts_deprecated_sync_settings(catalog_server): + endpoint, _, responses = catalog_server + responses.append((200, {})) + with pytest.warns(DeprecationWarning) as caught: + catalog = lancedb.connect_catalog( + endpoint, + request_thread_pool=2, + connection_timeout=5, + read_timeout=10, + ) + assert len(caught) == 3 + db = catalog.connect_database("analytics") + assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5) + assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10) + + @pytest.mark.parametrize("asynchronous", [False, True]) @pytest.mark.asyncio @pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)]) diff --git a/python/python/type_tests/connect.py b/python/python/type_tests/connect.py index eb2cba37c..6da32d2ec 100644 --- a/python/python/type_tests/connect.py +++ b/python/python/type_tests/connect.py @@ -4,12 +4,30 @@ from typing import assert_type import lancedb -from lancedb import AsyncConnection, DBConnection +from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection def check_connect_type() -> None: assert_type(lancedb.connect("memory://"), DBConnection) + assert_type( + lancedb.connect_catalog( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + Catalog, + ) async def check_connect_async_type() -> None: assert_type(await lancedb.connect_async("memory://"), AsyncConnection) + assert_type( + await lancedb.connect_catalog_async( + uri="db://analytics", + api_key="secret", + region="us-west-2", + host_override="https://my-server.example", + ), + AsyncCatalog, + ) diff --git a/python/src/catalog.rs b/python/src/catalog.rs index fb2e7e8a0..456d62a3c 100644 --- a/python/src/catalog.rs +++ b/python/src/catalog.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -127,7 +128,8 @@ impl DatabaseNames { } #[pyfunction] -#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))] +#[allow(clippy::too_many_arguments)] +#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))] pub fn connect_catalog( py: Python<'_>, endpoint: String, @@ -136,6 +138,7 @@ pub fn connect_catalog( sql_host_override: Option, read_consistency_interval: Option, oauth_config: Option, + storage_options: Option>, ) -> PyResult> { let interval = read_consistency_interval .map(Duration::try_from_secs_f64) @@ -151,6 +154,9 @@ pub fn connect_catalog( if let Some(config) = client_config { builder = builder.client_config(config.into()); } + if let Some(options) = storage_options { + builder = builder.storage_options(options); + } if let Some(endpoint) = sql_host_override { builder = builder.sql_host_override(endpoint); } diff --git a/rust/lancedb/src/catalog.rs b/rust/lancedb/src/catalog.rs index df80b6de6..dcea8fd90 100644 --- a/rust/lancedb/src/catalog.rs +++ b/rust/lancedb/src/catalog.rs @@ -349,6 +349,18 @@ impl ConnectCatalogBuilder { self.options.client_config = config; self } + /// Set storage options inherited by the catalog's remote database connections. + pub fn storage_options( + mut self, + options: impl IntoIterator, impl Into)>, + ) -> Self { + self.options.storage_options.extend( + options + .into_iter() + .map(|(key, value)| (key.into(), value.into())), + ); + self + } /// Set the SQL service endpoint inherited by database connections. /// /// Required to execute SQL when the catalog endpoint uses HTTPS. The SQL diff --git a/rust/lancedb/src/remote/catalog.rs b/rust/lancedb/src/remote/catalog.rs index 95facd04b..c620cf272 100644 --- a/rust/lancedb/src/remote/catalog.rs +++ b/rust/lancedb/src/remote/catalog.rs @@ -30,6 +30,8 @@ pub struct RemoteCatalogOptions { pub api_key: Option, /// Shared transport and authentication settings. pub client_config: ClientConfig, + /// Storage options supported by remote database connections. + pub storage_options: HashMap, /// SQL service endpoint used by returned database connections. /// Required for SQL when the catalog endpoint uses HTTPS. pub sql_host_override: Option, @@ -391,6 +393,10 @@ mod tests { .await; let mut options = RemoteCatalogOptions { api_key: Some("test-key".into()), + storage_options: HashMap::from([( + "azure_storage_account_name".into(), + "catalog-account".into(), + )]), ..Default::default() }; options.client_config.extra_headers = HashMap::from([ @@ -460,6 +466,10 @@ mod tests { ); assert!(!request.headers.contains_key("x-lancedb-database-prefix")); assert_eq!(request.headers["authorization"], "Bearer refreshed"); + assert_eq!( + request.headers["x-azure-storage-account-name"], + "catalog-account" + ); } assert_eq!( requests[0].line, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index a9d55b511..549baf345 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -385,7 +385,7 @@ impl RemoteDatabase { sql: options.sql_host_override.clone(), }, config, - RemoteOptions::default(), + StorageOptions(options.storage_options.clone()).into(), options.read_consistency_interval, super::client::ParsedDbUrl { db_name: name.unwrap_or("").to_string(), From ced4799ad51f7ee4dd4bdff40c061ef59d8bb014 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 12 Nov 2026 01:21:58 -0800 Subject: [PATCH 8/8] fix(python): preserve typed results for reopened refresh jobs (#4981) Restore typed results for reopened Function and SQL-expression refresh jobs while preserving their handles and cached descriptions. Fixes https://linear.app/lancedb/issue/ENT-3441. --- python/python/lancedb/db.py | 10 +- python/python/lancedb/job.py | 7 ++ python/python/tests/test_remote_db.py | 138 ++++++++++++++++++++++++++ python/src/connection.rs | 11 +- rust/lancedb/src/job.rs | 51 ++++++++++ rust/lancedb/src/remote/job.rs | 23 +++++ 6 files changed, 236 insertions(+), 4 deletions(-) diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 84ebb41a1..e2138520a 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -67,7 +67,7 @@ from .graph import ( PropertyGraph, _definition_json, ) -from .job import AsyncJob, Job, _typed_job +from .job import AsyncJob, Job, _opened_job, _typed_job from .storage_integration import SecretReference, StorageIntegrationInfo from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery @@ -1450,6 +1450,12 @@ class DBConnection(EnforceOverrides): specification, result, failure and event history, so there is no separate connection-level call for any of them. + For a column refresh, ``wait()`` returns a + [RefreshColumnResult][lancedb.functions.RefreshColumnResult], including + when the refresh was started through SQL. Other job types return + ``None`` from ``wait()``; their persisted result is available through + ``job.result`` after ``job.refresh()``. + Raises `JobNotFoundError` when the server has no such job, the way `open_table` does for a missing table. """ @@ -3626,7 +3632,7 @@ class AsyncConnection(object): """Open a server-side job by id. See [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return AsyncJob(await self._inner.open_job(job_id)) + return _opened_job(await self._inner.open_job(job_id)) async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 094a7b8d5..bf9605567 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -17,6 +17,7 @@ from lancedb.background_loop import LOOP from . import _lancedb from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url +from .functions import RefreshColumnResult from .remote.errors import HttpError, RetryError T = TypeVar("T") @@ -692,3 +693,9 @@ def _typed_job( ) -> AsyncJob[T]: """Bind an internal JSON-producing job to its public result model.""" return AsyncJob(inner, result_decoder) + + +def _opened_job(inner: "_lancedb.Job") -> AsyncJob: + if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"): + return _typed_job(inner, RefreshColumnResult.from_json) + return AsyncJob(inner) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index b0098aca3..8fde1209c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2557,6 +2557,144 @@ async def test_remote_job_wait_disconnection_timeout_can_be_resumed(sync): assert exc.value.__cause__.is_transport_error is True +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "job_type", ["function_refresh", "computed_refresh", "refresh_column"] +) +@pytest.mark.parametrize("running", [False, True]) +@pytest.mark.parametrize("rows_failed", [0, 8]) +async def test_reopened_refresh_job_wait_returns_typed_result( + sync, job_type, running, rows_failed +): + terminal_result = { + "rows_assigned": 400 - rows_failed, + "rows_failed": rows_failed, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + "summary": {"future_field": True}, + } + polls = 0 + + def handler(request): + nonlocal polls + assert request.path == "/v1/jobs/describe" + payload = json.loads(request.rfile.read(int(request.headers["Content-Length"]))) + assert payload == {"job_id": "refresh-1"} + polls += 1 + in_progress = running and polls <= 2 + response = { + "job_id": "refresh-1", + "job_type": job_type, + "job_state": "IN_PROGRESS" if in_progress else "DONE", + "creation_ms": 1000, + "spec": {"column": "derived"}, + } + if not in_progress: + response["result"] = terminal_result + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(response).encode()) + + observed = [] + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = job.wait(timeout=timedelta(seconds=5), progress=observed.append) + assert job.wait() == result + job.refresh() + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + assert job.id == "refresh-1" + assert job.spec == {"column": "derived"} + result = await job.wait( + timeout=timedelta(seconds=5), progress=observed.append + ) + assert await job.wait() == result + await job.refresh() + assert job.result == terminal_result + + assert isinstance(result, lancedb.RefreshColumnResult) + assert result == lancedb.RefreshColumnResult.model_validate(terminal_result) + assert result.rows_failed == rows_failed + assert observed[-1]["state"] == "finished" + if running: + assert observed[0]["state"] == "running" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("terminal_result", [None, {}]) +async def test_reopened_refresh_job_rejects_missing_or_invalid_result( + sync, terminal_result +): + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + job.wait() + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("refresh-1") + with pytest.raises(HttpError, match="typed job"): + await job.wait() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +async def test_reopened_unit_job_ignores_additive_result_payload(sync): + terminal_result = {"future_field": True} + + def handler(request): + assert request.path == "/v1/jobs/describe" + request.rfile.read(int(request.headers["Content-Length"])) + request.send_response(200) + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "index-1", + "job_type": "create_index", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + + if sync: + with mock_lancedb_connection(handler) as db: + job = db.open_job("index-1") + assert job.wait() is None + assert job.result == terminal_result + else: + async with mock_lancedb_connection_async(handler) as db: + job = await db.open_job("index-1") + assert await job.wait() is None + assert job.result == terminal_result + + @pytest.mark.parametrize("payload", [b"{", b"{}"]) def test_remote_job_wait_does_not_retry_malformed_description(payload): polls = 0 diff --git a/python/src/connection.rs b/python/src/connection.rs index 0be933cf2..69cf54c99 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -24,7 +24,7 @@ use lancedb::{ connection::NamespaceClientPushdownOperation, database::namespace::LanceNamespaceDatabase, database::{CreateTableMode, Database, ReadConsistency}, - function::GpuClass as LanceGpuClass, + function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, }; use pyo3::{ @@ -854,7 +854,14 @@ impl Connection { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { let job = inner.open_job(&job_id).await.infer_error()?; - Ok(crate::job::Job::new(job)) + match job.job_type().as_deref() { + Some("function_refresh" | "computed_refresh" | "refresh_column") => { + Ok(crate::job::Job::new_typed( + job.into_typed::().infer_error()?, + )) + } + _ => Ok(crate::job::Job::new(job)), + } }) } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index d178542b7..092ece8b5 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -277,6 +277,42 @@ impl Job<()> { } job } + + /// Decode this job's terminal payload as `T` when waiting. + /// + /// Use this after [`crate::Connection::open_job`] when the job's result + /// type is known. The job identity and cached description are preserved. + /// Missing or incompatible payloads are reported by [`Job::wait`]. + /// A job that completed before its handle was created has only a unit + /// result; converting it fails immediately if `T` cannot decode JSON null. + /// + /// ```no_run + /// # async fn reopen( + /// # db: &lancedb::Connection, id: &str, + /// # ) -> lancedb::Result { + /// let job = db.open_job(id).await? + /// .into_typed::()?; + /// job.wait().await + /// # } + /// ``` + pub fn into_typed(self) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + { + let inner = match self.inner { + JobInner::Handle { handle, .. } => JobInner::Handle { + handle, + decode: Arc::new(TerminalResult::decode::), + }, + JobInner::Completed(()) => { + JobInner::Completed(TerminalResult::local(Value::Null).decode::()?) + } + }; + Ok(Job { + inner, + cache: self.cache, + }) + } } impl Job @@ -750,6 +786,21 @@ mod tests { )); } + #[tokio::test] + async fn completed_unit_job_can_be_retyped_as_unit() { + let job = Job::new_done().into_typed::<()>().unwrap(); + job.wait().await.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + } + + #[test] + fn completed_unit_job_rejects_an_incompatible_result_type() { + assert!(matches!( + Job::new_done().into_typed::(), + Err(Error::Runtime { .. }) + )); + } + #[tokio::test] async fn mapped_spawned_job_reuses_outcome() { let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index d27c9c666..5a0afa7e8 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -403,6 +403,29 @@ mod tests { ); } + #[tokio::test] + async fn reopened_job_preserves_its_description_and_decodes_the_terminal_result() { + let description: DescribeJobResponse = serde_json::from_str(REFRESH_JOB).unwrap(); + let job = Job::opened( + Box::new(FixtureRemoteJob(REFRESH_JOB)), + description.into_description(), + ); + let raw_result = job.result(); + let job = job.into_typed::().unwrap(); + + assert_eq!(job.job_type().as_deref(), Some("refresh_function_columns")); + assert_eq!(job.state().as_deref(), Some("finished")); + assert_eq!(job.creation_ms(), Some(1787270400001)); + assert_eq!(job.result(), raw_result); + assert_eq!(job.wait().await.unwrap().rows_assigned, 999_998_800); + assert_eq!(job.wait().await.unwrap().published_version, Some(919)); + + let missing = Job::new(Box::new(FixtureRemoteJob(MISSING_RESULT_JOB))) + .into_typed::() + .unwrap(); + assert!(missing.wait().await.is_err()); + } + /// Five in-progress polls then done: 0.2 + 0.4 + 0.8 + 1 + 1 s of waiting. /// Under the old 5 s cap the same job would have waited 10 s. #[tokio::test(start_paused = true)]