mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
fix(python): preserve the requested package index on Function inspection (#5220)
Python callers inspecting a pinned Function version lose the explicit primary package index URL even when the server includes it. Preserve `runtime.environment.build.index_url` through `get_function` and canonical JSON. The requested build view contains only the explicit primary URL. Extra indexes, other sources, and service defaults can still apply when that view is absent. Compare the server's `runtime_digest` with the authored runtime's digest for identity. The inspection view can omit inputs to that digest. Typed registration rejects nonempty build settings before issuing a request. The existing decorator options and `refresh_lock` use the same registration path. Loopback Flight tests exercised sync and async pinned reads with a primary index plus an extra index, and with only an extra index. They also verified that typed submission rejects unsupported settings before sending a request and still submits ordinary decorator definitions with `refresh_lock`. A separate local replay verified pinned readback against a published version with a credential-free primary index. The focused suites passed 547 Python and 129 Rust tests, with three Rust tests marked ignored.
This commit is contained in:
@@ -690,6 +690,10 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.functions.PythonEnvironmentSpec
|
||||
|
||||
::: lancedb.functions.RequestedPythonEnvironment
|
||||
|
||||
::: lancedb.functions.PythonEnvironmentBuild
|
||||
|
||||
::: lancedb.functions.function
|
||||
|
||||
::: lancedb.functions.FunctionDefinition
|
||||
@@ -724,6 +728,8 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.functions.PythonRuntimeSpec
|
||||
|
||||
::: lancedb.functions.RequestedPythonRuntime
|
||||
|
||||
::: lancedb.GpuClass
|
||||
|
||||
::: lancedb.functions.FunctionVersionRef
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -681,6 +681,39 @@ impl<'de> Deserialize<'de> for RowTimeoutSeconds {
|
||||
}
|
||||
}
|
||||
|
||||
// Function inspection includes this build setting alongside the SDK's authored
|
||||
// runtime spec. Keep it on the readback model so registration keeps its own wire shape.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct RequestedPythonRuntime {
|
||||
spec: PythonRuntimeSpec,
|
||||
index_url: Option<String>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for RequestedPythonRuntime {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
|
||||
let document = Value::deserialize(deserializer)?;
|
||||
let index_url = document
|
||||
.pointer("/environment/build/index_url")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned);
|
||||
let spec: PythonRuntimeSpec =
|
||||
serde_json::from_value(document).map_err(de::Error::custom)?;
|
||||
let index_url = spec.environment().and(index_url);
|
||||
Ok(Self { spec, index_url })
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for RequestedPythonRuntime {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
let Some(index_url) = &self.index_url else {
|
||||
return self.spec.serialize(serializer);
|
||||
};
|
||||
let mut document = serde_json::to_value(&self.spec).map_err(serde::ser::Error::custom)?;
|
||||
document["environment"]["build"] = serde_json::json!({"index_url": index_url});
|
||||
document.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
/// One immutable Function object revision and its executable artifact.
|
||||
///
|
||||
/// The Function is named by its parts, `name` and `namespace_path`, the way a
|
||||
@@ -764,7 +797,7 @@ pub struct FunctionVersion {
|
||||
/// [`Self::resolved_environment`] when the caller needs actual package
|
||||
/// versions.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
runtime: Option<PythonRuntimeSpec>,
|
||||
runtime: Option<RequestedPythonRuntime>,
|
||||
/// Actual installed distributions, provenance, and registration warnings.
|
||||
///
|
||||
/// This is the single-platform compatibility field. `None` on a
|
||||
@@ -838,7 +871,8 @@ impl FunctionVersion {
|
||||
|
||||
/// Digest of canonical runtime inputs, when provided by the server.
|
||||
///
|
||||
/// Includes Python version, environment sources, variables, and GPU settings.
|
||||
/// Compare it with the digest of a locally authored runtime. The runtime
|
||||
/// projection on this version can omit inputs needed to reproduce the digest.
|
||||
/// 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> {
|
||||
@@ -885,12 +919,21 @@ impl FunctionVersion {
|
||||
self.result_stability.as_deref()
|
||||
}
|
||||
|
||||
/// The runtime specification requested at registration, when exposed by the
|
||||
/// server.
|
||||
/// Runtime metadata requested at registration and exposed by the server.
|
||||
///
|
||||
/// This is the requested configuration, not evidence of what was installed.
|
||||
/// This view can omit input needed to reproduce [`Self::runtime_digest`].
|
||||
/// Read the explicit primary package index with [`Self::requested_index_url`],
|
||||
/// and inspect installed distributions with [`Self::resolved_environment`].
|
||||
pub fn runtime(&self) -> Option<&PythonRuntimeSpec> {
|
||||
self.runtime.as_ref()
|
||||
self.runtime.as_ref().map(|runtime| &runtime.spec)
|
||||
}
|
||||
|
||||
/// Explicit primary package index URL requested for this Function version.
|
||||
///
|
||||
/// An absent value can still accompany extra indexes, other sources, or
|
||||
/// service defaults. For build provenance, see [`ResolvedEnvironmentProvenance`].
|
||||
pub fn requested_index_url(&self) -> Option<&str> {
|
||||
self.runtime.as_ref()?.index_url.as_deref()
|
||||
}
|
||||
|
||||
/// Actual installed distributions and registration warnings for a
|
||||
@@ -1083,6 +1126,7 @@ pub struct FunctionRegistrationRequest {
|
||||
pub name: String,
|
||||
pub artifact: FunctionArtifactRequest,
|
||||
pub signature: FunctionSignature,
|
||||
#[serde(deserialize_with = "deserialize_registration_runtime")]
|
||||
pub runtime: PythonRuntimeSpec,
|
||||
/// Maximum rows in one execution batch; the executor may use fewer.
|
||||
#[serde(
|
||||
@@ -1144,8 +1188,25 @@ pub struct FunctionRegistrationRequest {
|
||||
pub refresh_lock: bool,
|
||||
}
|
||||
|
||||
fn deserialize_registration_runtime<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<PythonRuntimeSpec, D::Error> {
|
||||
let document = Value::deserialize(deserializer)?;
|
||||
match document.pointer("/environment/build") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Object(build)) if build.is_empty() => {}
|
||||
Some(_) => {
|
||||
return Err(de::Error::custom(
|
||||
"runtime.environment.build is unsupported in typed Function registration",
|
||||
));
|
||||
}
|
||||
}
|
||||
serde_json::from_value(document).map_err(de::Error::custom)
|
||||
}
|
||||
|
||||
impl FunctionRegistrationRequest {
|
||||
/// Decode a registration request supplied by an SDK language binding.
|
||||
/// Nonempty environment build settings are rejected by this typed API.
|
||||
pub fn from_json(json: &str) -> Result<Self> {
|
||||
from_json(json)
|
||||
}
|
||||
@@ -1960,6 +2021,84 @@ mod tests {
|
||||
assert!(FunctionVersion::from_json(&document.to_string()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_version_exposes_the_explicit_primary_index() {
|
||||
const VERSION: &str = include_str!(
|
||||
"../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json"
|
||||
);
|
||||
const PRIMARY: &str = "https://primary.example/simple/";
|
||||
const EXTRA: &str = "https://extra.example/simple/";
|
||||
const DIGEST: &str = "sha256:requested-runtime";
|
||||
let mut document: Value = serde_json::from_str(VERSION).unwrap();
|
||||
document["runtime"] = serde_json::json!({
|
||||
"kind": "python",
|
||||
"python_version": "3.12",
|
||||
"environment": {"kind": "pip", "packages": ["example==1.0"]},
|
||||
});
|
||||
document["runtime_digest"] = serde_json::json!(DIGEST);
|
||||
document["resolved_environment"] = serde_json::json!({
|
||||
"packages": [],
|
||||
"provenance": {"configured_index_urls": [EXTRA]},
|
||||
});
|
||||
|
||||
let legacy = FunctionVersion::from_json(&document.to_string()).unwrap();
|
||||
assert_eq!(legacy.requested_index_url(), None);
|
||||
let legacy_json = legacy.to_canonical_json().unwrap();
|
||||
for (build, index) in [
|
||||
(Value::Null, None),
|
||||
(serde_json::json!({}), None),
|
||||
(serde_json::json!({"extra_index_urls": [EXTRA]}), None),
|
||||
(serde_json::json!({"index_url": 1}), None),
|
||||
(serde_json::json!("invalid-build"), None),
|
||||
(
|
||||
serde_json::json!({"index_url": PRIMARY, "extra_index_urls": [EXTRA]}),
|
||||
Some(PRIMARY),
|
||||
),
|
||||
] {
|
||||
document["runtime"]["environment"]["build"] = build;
|
||||
let version = FunctionVersion::from_json(&document.to_string()).unwrap();
|
||||
assert_eq!(version.requested_index_url(), index);
|
||||
assert_eq!(version.runtime_digest(), Some(DIGEST));
|
||||
let canonical = version.to_canonical_json().unwrap();
|
||||
if let Some(index) = index {
|
||||
let mut expected: Value = serde_json::from_str(&legacy_json).unwrap();
|
||||
expected["runtime"]["environment"]["build"] =
|
||||
serde_json::json!({"index_url": index});
|
||||
assert_eq!(serde_json::from_str::<Value>(&canonical).unwrap(), expected);
|
||||
} else {
|
||||
assert_eq!(canonical, legacy_json);
|
||||
}
|
||||
assert_eq!(FunctionVersion::from_json(&canonical).unwrap(), version);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_registration_rejects_environment_build_settings() {
|
||||
const REQUEST: &str = include_str!(
|
||||
"../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json"
|
||||
);
|
||||
let mut document: Value = serde_json::from_str(REQUEST).unwrap();
|
||||
let expected = FunctionRegistrationRequest::from_json(REQUEST).unwrap();
|
||||
for build in [Value::Null, serde_json::json!({})] {
|
||||
document["runtime"]["environment"]["build"] = build;
|
||||
assert_eq!(
|
||||
FunctionRegistrationRequest::from_json(&document.to_string()).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
for build in [
|
||||
serde_json::json!({"index_url": "https://primary.example/simple/"}),
|
||||
serde_json::json!({"extra_index_urls": ["https://extra.example/simple/"]}),
|
||||
serde_json::json!("invalid-build"),
|
||||
] {
|
||||
document["runtime"]["environment"]["build"] = build;
|
||||
let error = FunctionRegistrationRequest::from_json(&document.to_string()).unwrap_err();
|
||||
assert!(error.to_string().contains(
|
||||
"runtime.environment.build is unsupported in typed Function registration"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_version_preserves_requested_and_resolved_environments() {
|
||||
const VERSION: &str = include_str!(
|
||||
|
||||
@@ -3406,6 +3406,11 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
version_json["row_timeout_seconds"] = serde_json::json!(8.0);
|
||||
version_json["result_stability"] = serde_json::json!("input_and_context");
|
||||
version_json["runtime"] = request_json["runtime"].clone();
|
||||
let requested_index_url = "https://requested.example/simple/";
|
||||
version_json["runtime"]["environment"]["build"] = serde_json::json!({
|
||||
"index_url": requested_index_url,
|
||||
"find_links": ["https://downloads.example/wheels"],
|
||||
});
|
||||
version_json["resolved_environment"] = serde_json::json!({
|
||||
"packages": [
|
||||
{
|
||||
@@ -3551,6 +3556,7 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
assert_eq!(described.row_timeout_seconds(), Some(8.0));
|
||||
assert_eq!(described.result_stability(), Some("input_and_context"));
|
||||
assert_eq!(described.runtime().unwrap().kind(), "python");
|
||||
assert_eq!(described.requested_index_url(), Some(requested_index_url));
|
||||
assert_eq!(
|
||||
described
|
||||
.resolved_environment()
|
||||
@@ -3570,6 +3576,14 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
assert_eq!(described_json["max_concurrency"], 4);
|
||||
assert_eq!(described_json["row_timeout_seconds"], 8.0);
|
||||
assert_eq!(described_json["result_stability"], "input_and_context");
|
||||
assert_eq!(
|
||||
described_json["runtime"]["environment"]["build"],
|
||||
serde_json::json!({"index_url": requested_index_url})
|
||||
);
|
||||
assert_eq!(
|
||||
described_json["resolved_environment"]["provenance"]["configured_index_urls"],
|
||||
serde_json::json!(["https://packages.example/simple"])
|
||||
);
|
||||
let latest = db
|
||||
.get_function_latest("embed", &["team".into()])
|
||||
.await
|
||||
|
||||
Reference in New Issue
Block a user