Merge main and align cosine patch with Lance 16.0.0-beta.2

This commit is contained in:
Gatefixer
2026-11-26 11:30:15 +00:00
29 changed files with 655 additions and 141 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.32"
version = "0.42.0-beta.35"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+2 -2
View File
@@ -45,7 +45,7 @@ repository = "https://github.com/lancedb/lancedb"
[project.optional-dependencies]
pylance = [
# Keep the minimum in the bundled Lance major and compatible with tests below.
"pylance>=15.0.0b3",
"pylance>=16.0.0b2",
]
# A library only needs the OpenTelemetry API; the application supplies and
# configures the SDK (the actual exporter/reader). See
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.1.0b2",
"pylance==16.0.0b2",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+111 -21
View File
@@ -405,6 +405,54 @@ class PythonEnvironmentSpec(_RemoteValue):
image: Optional[str] = None
system_packages: tuple[str, ...] = ()
@model_validator(mode="before")
@classmethod
def _validate_registration_build(cls, value):
if isinstance(value, Mapping):
build = value.get("build")
if build is not None and (not isinstance(build, Mapping) or build):
raise TypeError(
"runtime.environment.build is unsupported "
"in typed Function registration"
)
return value
class PythonEnvironmentBuild(_RemoteValue):
"""Explicit primary package index URL reported on a Function version."""
index_url: str
class RequestedPythonEnvironment(PythonEnvironmentSpec):
"""Python environment metadata reported on a Function version.
``build`` contains only the explicitly requested primary package index URL.
An omitted ``build`` can still accompany extra indexes, other sources, or
service defaults. See
[ResolvedEnvironmentProvenance][lancedb.functions.ResolvedEnvironmentProvenance]
for the sources reported by the build.
"""
build: Optional[PythonEnvironmentBuild] = None
@model_validator(mode="before")
@classmethod
def _validate_registration_build(cls, value):
# Inspection accepts an authored model or a wire document with a build field.
if isinstance(value, PythonEnvironmentSpec) and not isinstance(value, cls):
return value._known_dict()
return value
@field_validator("build", mode="before")
@classmethod
def _read_primary_index(cls, build):
if isinstance(build, PythonEnvironmentBuild):
return build
if isinstance(build, Mapping) and isinstance(build.get("index_url"), str):
return {"index_url": build["index_url"]}
return None
_HUGGING_FACE_MODEL_REPO = re.compile(
r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$"
@@ -543,10 +591,11 @@ class PythonRuntimeSpec(_RemoteValue):
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.
order is preserved. Compare an authored runtime's digest with
``runtime_digest`` on [FunctionVersion][lancedb.functions.FunctionVersion].
A version's projected runtime fields can omit inputs from that digest.
This identity covers declared inputs; the installed contents of unpinned
dependencies and the deployment's default base image can vary.
"""
if self.kind not in {"python", "python_v2"}:
raise ValueError(f"cannot digest unknown runtime kind {self.kind!r}")
@@ -567,6 +616,25 @@ class PythonRuntimeSpec(_RemoteValue):
return f"sha256:{hashlib.sha256(encoded).hexdigest()}"
class RequestedPythonRuntime(PythonRuntimeSpec):
"""Requested runtime metadata available during Function version inspection.
The build view contains only an explicit primary package index URL. Other
sources can be present even when the build view is absent. Compare the
server's ``FunctionVersion.runtime_digest`` with the digest of an authored
runtime. The inspection view can omit inputs needed to reproduce that digest.
"""
environment: Optional[RequestedPythonEnvironment] = None
@model_validator(mode="before")
@classmethod
def _discard_unknown_runtime_payload(cls, value):
if isinstance(value, PythonRuntimeSpec) and not isinstance(value, cls):
value = value._known_dict()
return super()._discard_unknown_runtime_payload(value)
class FunctionImage(_RemoteValue):
"""A complete OCI Function image identified by its exact manifest digest.
@@ -685,12 +753,12 @@ class FunctionEnvironment(NamedTuple):
and
[FunctionVersion.resolved_environment][lancedb.functions.FunctionVersion.resolved_environment].
It adds no wire field and performs no second parse. ``requested`` is the
runtime specification supplied at registration; ``resolved`` is measured
data and is ``None`` when unknown. For per-platform multiarchitecture
server's view of the runtime requested at registration. ``resolved`` is
measured data and is ``None`` when unknown. For per-platform multiarchitecture
measurements, use ``FunctionVersion.environment_report``.
"""
requested: Optional[PythonRuntimeSpec]
requested: Optional[RequestedPythonRuntime]
resolved: Optional[ResolvedEnvironment]
@@ -745,16 +813,16 @@ class FunctionVersion(_RemoteValue):
catalog. They are ``None`` for versions registered before the
corresponding declaration.
``runtime`` is the runtime specification requested at registration. It is
not evidence of what was installed. ``resolved_environment`` is measured
data for a single-platform image: actual package names and complete
versions, optional per-package source, provenance, and registration
warnings. ``resolved_environments`` is the corresponding map for a
multiarchitecture image, keyed by OCI ``os/architecture``. It is never
flattened into an aggregate package list. ``None`` or an empty map means
unknown data, not an empty installed environment. ``environment`` is a
convenience view with ``requested`` and ``resolved`` members over the same
fields.
``runtime`` contains the requested runtime fields exposed by the SDK.
The canonical runtime identity comes from ``runtime_digest``.
``resolved_environment`` is measured data for a single-platform image:
actual package names and complete versions, optional per-package source,
provenance, and registration warnings. ``resolved_environments`` is the
corresponding map for a multiarchitecture image, keyed by OCI
``os/architecture``. It is never flattened into an aggregate package list.
``None`` or an empty map means the measurement is unknown. ``environment``
is a convenience view with ``requested`` and ``resolved`` members over the
same fields.
"""
name: str
@@ -778,7 +846,7 @@ class FunctionVersion(_RemoteValue):
total_gpu_count: Optional[_UInt32] = None
row_timeout_seconds: Optional[float] = None
result_stability: Optional[str] = None
runtime: Optional[PythonRuntimeSpec] = None
runtime: Optional[RequestedPythonRuntime] = None
resolved_environment: Optional[ResolvedEnvironment] = None
resolved_environments: Mapping[str, ResolvedEnvironment] = Field(
default_factory=dict
@@ -957,9 +1025,10 @@ class FunctionRegistrationRequest(_RemoteValue):
Credential values deliberately have no field here. The only secret-shaped
thing a client sends is ``secret_bindings``: the name of a Secret the
database already holds, which the remote service resolves at execution.
``refresh_lock`` is a per-registration action, not part of the Function's
source or runtime identity; its false default is omitted from canonical
JSON.
``refresh_lock`` is a per-registration action that leaves the Function's
source and runtime identities unchanged. Its false default is omitted from
canonical JSON. The typed registration API accepts authored runtimes and
rejects nonempty ``runtime.environment.build`` settings.
"""
name: str
@@ -997,6 +1066,24 @@ class FunctionRegistrationRequest(_RemoteValue):
def _validate_refresh_lock(cls, value):
return _validate_refresh_lock(value)
@field_validator("runtime", mode="before")
@classmethod
def _require_authored_runtime(cls, runtime):
if isinstance(runtime, RequestedPythonRuntime) or (
isinstance(runtime, PythonRuntimeSpec)
and isinstance(runtime.environment, RequestedPythonEnvironment)
):
raise TypeError(
"Function version runtime metadata is for inspection only; "
"register an authored @function definition"
)
return runtime
def to_canonical_json(self) -> str:
"""Encode the authored request for Function registration."""
self._require_authored_runtime(self.runtime)
return super().to_canonical_json()
def with_refresh_lock(self, refresh_lock: bool) -> FunctionRegistrationRequest:
"""Return this request with the registration-time refresh action set."""
refresh_lock = _validate_refresh_lock(refresh_lock)
@@ -4148,7 +4235,10 @@ __all__ = [
"OutputMapping",
"PythonEnvironmentSpec",
"PythonAdapterSpec",
"PythonEnvironmentBuild",
"PythonRuntimeSpec",
"RequestedPythonEnvironment",
"RequestedPythonRuntime",
"ResolvedEnvironment",
"ResolvedEnvironmentProvenance",
"ResolvedPackage",
@@ -33,6 +33,7 @@ from lancedb.functions import (
FunctionSignature,
FunctionVersion,
HuggingFaceModel,
PythonEnvironmentBuild,
PythonRuntimeSpec,
SecretBinding,
SecretReference,
@@ -2640,6 +2641,52 @@ def test_function_version_reads_requested_and_resolved_environments():
FunctionVersion.from_json(json.dumps(invalid))
@pytest.mark.asyncio
@pytest.mark.parametrize(
"build",
[
{},
{"build": None},
{"build": {}},
{"build": {"index_url": None}},
{"build": {"index_url": 1}},
{"build": "invalid-build"},
{
"build": {
"index_url": "https://requested.example/simple/",
"find_links": ["https://downloads.example/wheels"],
},
},
],
)
async def test_get_pinned_function_preserves_only_the_requested_index_url(build):
payload = _function_version_with_resolved_environment()
payload["runtime"]["environment"].update(build)
catalog = _RawFunctionCatalog(payload, encode=True)
connection = AsyncConnection(catalog)
version = await connection.get_function(payload["name"], version=1)
assert catalog.requested_versions == ["1"]
assert version.version == "1"
requested = version.runtime.environment.build
raw_build = build.get("build")
index_url = raw_build.get("index_url") if isinstance(raw_build, dict) else None
canonical = version.to_canonical_json()
encoded = json.loads(canonical)["runtime"]["environment"]
if not isinstance(index_url, str):
assert requested is None
assert "build" not in encoded
else:
assert isinstance(requested, PythonEnvironmentBuild)
assert requested.index_url == index_url
assert encoded["build"] == {"index_url": index_url}
assert version.resolved_environment.provenance.configured_index_urls == (
"https://packages.example/simple",
)
assert FunctionVersion.from_json(canonical) == version
def test_function_version_reads_resolved_environments_by_platform():
legacy = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
+125 -13
View File
@@ -8,7 +8,22 @@ import pyarrow as pa
import pytest
import lancedb
from lancedb.functions import BlobWriter, function
from lancedb.functions import (
BlobWriter,
FunctionDefinition,
FunctionRegistrationRequest,
FunctionVersion,
function,
)
def _stored_function_version():
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
return json.loads(fixture.read_text())
@pytest.mark.asyncio
@@ -16,12 +31,7 @@ from lancedb.functions import BlobWriter, function
@pytest.mark.parametrize("exist_ok", [None, False, True])
async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
stored = json.loads(fixture.read_text())
stored = _stored_function_version()
result = pa.table({"definition": [json.dumps(stored)]})
@function(name=stored["name"])
@@ -66,12 +76,7 @@ async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, ex
@pytest.mark.asyncio
async def test_blob_writer_paths_round_trip_through_function_registration():
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
stored = json.loads(fixture.read_text())
stored = _stored_function_version()
expected_paths = [[{"field": "item"}], [{"field": "variants"}, "item"]]
output_schema = pa.schema(
[
@@ -131,3 +136,110 @@ async def test_blob_writer_paths_round_trip_through_function_registration():
application = version(text=lancedb.col("text")).rename(columns={"item": "payload"})
assert json.loads(application.to_canonical_json())["output"] == expected_output
assert application.columns == {"item": "payload"}
@pytest.mark.asyncio
@pytest.mark.parametrize("with_primary", [False, True])
async def test_function_index_inspection_is_separate_from_registration(with_primary):
flight = pytest.importorskip("pyarrow.flight")
primary = "https://primary.example/simple/"
extra = "https://extra.example/simple/"
stored = _stored_function_version()
name = stored["name"]
def scale(value: float) -> float:
return 2 * value
authored = function(name=name, pip=["example==1.0"], python_version="3.12")(scale)
request = authored.registration_request
expected_runtime = {
"kind": "python",
"python_version": "3.12",
"environment": {"kind": "pip", "packages": ["example==1.0"]},
}
stored["runtime"] = json.loads(request.runtime.to_canonical_json())
build = {"extra_index_urls": [extra]}
if with_primary:
build["index_url"] = primary
stored["runtime"]["environment"]["build"] = build
stored["runtime_digest"] = "sha256:" + "1" * 64
stored["resolved_environment"] = {
"packages": [],
"provenance": {"configured_index_urls": [extra]},
}
class FunctionServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(
pa.table({"definition": [json.dumps(stored)]})
)
class IndexedDefinition(FunctionDefinition):
def bind_secrets(self, secrets):
payload = json.loads(super().bind_secrets(secrets).to_canonical_json())
payload["runtime"]["environment"]["build"] = build
return FunctionRegistrationRequest.from_json(json.dumps(payload))
definition = IndexedDefinition(
scale,
name=name,
input_schema=None,
output_schema=None,
pip=("example==1.0",),
env={},
python_version="3.12",
)
with FunctionServer() as server:
options = {
"api_key": "test-key",
"host_override": "http://127.0.0.1:1",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
db = lancedb.connect("db://analytics", **options)
async_db = await lancedb.connect_async("db://analytics", **options)
message = r"runtime\.environment\.build is unsupported"
with pytest.raises(TypeError, match=message):
db.create_function(definition)
with pytest.raises(TypeError, match=message):
await async_db.create_function_async(definition)
assert server.requests == []
version = db.get_function(name, version=1)
assert await async_db.get_function(name, version="1") == version
assert all(
f"DESCRIBE FUNCTION \"{name}\" WITH (version = '1')".encode() in ticket
for ticket in server.requests
)
assert len(server.requests) == 2
assert version.runtime_digest == stored["runtime_digest"]
assert version.resolved_environment.provenance.configured_index_urls == (extra,)
canonical = version.to_canonical_json()
encoded = json.loads(canonical)
assert FunctionVersion.from_json(canonical) == version
if with_primary:
assert version.runtime.environment.build.index_url == primary
assert encoded["runtime"]["environment"]["build"] == {"index_url": primary}
else:
assert version.runtime.environment.build is None
assert "build" not in encoded["runtime"]["environment"]
with pytest.raises(TypeError, match="runtime metadata is for inspection only"):
FunctionRegistrationRequest.model_validate(
{**request.model_dump(), "runtime": version.runtime}
)
with pytest.raises(TypeError, match="runtime metadata is for inspection only"):
request.model_copy(update={"runtime": version.runtime}).to_canonical_json()
job = await async_db.create_function_async(authored, refresh_lock=True)
assert await job.wait() == version
_, marker, body = server.requests[-1].partition(b" FROM '{")
assert marker
sent, _ = json.JSONDecoder().raw_decode("{" + body.decode(errors="replace"))
assert sent["refresh_lock"] is True
assert sent["runtime"] == expected_runtime
+10 -10
View File
@@ -1911,8 +1911,8 @@ requires-dist = [
{ name = "pyarrow", marker = "extra == 'tests'", specifier = ">=16" },
{ 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.1.0b2" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=16.0.0b2" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==16.0.0b2" },
{ 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" },
@@ -3649,20 +3649,20 @@ crypto = [
[[package]]
name = "pylance"
version = "15.1.0b2"
version = "16.0.0b2"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
{ name = "pyarrow" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_vSWFg/pylance-15.1.0b2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:297f8d3059be999ade63b04d9ce592b71f3c6d5d7fd70cdbb3d2f6a65bc310f2" },
{ url = "https://pypi.fury.io/lance-format/-/ver_28KJav/pylance-15.1.0b2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:414bfef47bd01a159f392a8e8e099fee7c9ab1be2c847ca2cd224f623fdd277e" },
{ url = "https://pypi.fury.io/lance-format/-/ver_7FE7R/pylance-15.1.0b2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:841c44301b060aeb4309bc64c8b60be17b5a12c4801aca2a7f6ded1dd2e414e9" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2jMYDF/pylance-15.1.0b2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5979250018dc7ccabb8193f9f4c01b3c581d48adedd7a73b9ebfcc0104bb7d19" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1XQt8E/pylance-15.1.0b2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd67e0ada56f9574c12a4300e0ceccb16830d2b16ebc7dabaf1ced38cc7d8593" },
{ url = "https://pypi.fury.io/lance-format/-/ver_H8fyY/pylance-15.1.0b2-cp310-abi3-win_amd64.whl", hash = "sha256:120ed03b30176db76fa1c25223531a59abb77e5a80a9c85923914ad161132904" },
{ url = "https://pypi.fury.io/lance-format/-/ver_zdLur/pylance-15.1.0b2-cp310-abi3-win_arm64.whl", hash = "sha256:5eebf0d2eba1d32ab3ef43c1d69614e265bf7e428480601a4287e3fb33290292" },
{ url = "https://pypi.fury.io/lance-format/-/ver_ZecaD/pylance-16.0.0b2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:f3e5b62af3f7deb3a300a0db8403c773aea1c09b9994133f6c0ec27a7f8dd8f1" },
{ url = "https://pypi.fury.io/lance-format/-/ver_24wBy9/pylance-16.0.0b2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c3c49dc4d9d7b8b6a7dca52f256214e842268c22b5de99e4ec66387964947534" },
{ url = "https://pypi.fury.io/lance-format/-/ver_Ku99Z/pylance-16.0.0b2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:07da197567e65e9337b748f3f23e5dd0bcc449e8102c77c4725f4cab38c0ac0d" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1ap2tM/pylance-16.0.0b2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:6d52963f7a11995008dc4918709557e1e92411112143b9a9b60fc984a94689ce" },
{ url = "https://pypi.fury.io/lance-format/-/ver_fHVmi/pylance-16.0.0b2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6da78f342c182b28c4761ed95d2659cb03c315f3442f48d0b15e2fbb2f785319" },
{ url = "https://pypi.fury.io/lance-format/-/ver_o64X/pylance-16.0.0b2-cp310-abi3-win_amd64.whl", hash = "sha256:4937c4101e6ad28872117f3709f38104f1e20f53fd36146f434e8c04e36cbfc6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_11mfKl/pylance-16.0.0b2-cp310-abi3-win_arm64.whl", hash = "sha256:32af551a7a8cc278dc06acf0e4bcbed9623c3b8fd854c3bed2f5ebd30d574f5d" },
]
[[package]]