mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Python Function declarations reject Arrow map and decimal types before registration. Accept `dict[str, T]`, nullable map values, explicit Arrow maps, and `Annotated[Decimal, pa.decimal128/256(...)]` using the existing canonical JSON representation. Preserve map key/value nullability and decimal precision/scale; reject unsupported map keys, sorted maps, nested Blob values, and a bare Decimal without precision/scale. This is the SDK map/decimal portion of ENT-3414. Server validation and SQL support are separate changes; older servers can still reject these signatures. Nullable scalar output support remains separate in #5030. Validation: 129 Function signature tests passed; 30 documentation tests passed with one existing skip. Ruff format/lint and diff checks passed. Python tests used the existing Python 3.13 environment and prebuilt native extension with this Python source overlaid; no Rust build or remote-server execution was performed.
3175 lines
110 KiB
Python
3175 lines
110 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import contextlib
|
|
import functools
|
|
import importlib.util
|
|
import inspect
|
|
import types
|
|
from datetime import date, datetime, timedelta
|
|
import http.server
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import typing
|
|
import urllib.parse
|
|
import warnings
|
|
from decimal import Decimal
|
|
from typing import Annotated, Optional
|
|
|
|
import pyarrow as pa
|
|
import pytest
|
|
|
|
import lancedb
|
|
from lancedb import BlobReader
|
|
from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection
|
|
from lancedb.functions import (
|
|
FunctionRegistrationRequest,
|
|
FunctionSignature,
|
|
FunctionVersion,
|
|
HuggingFaceModel,
|
|
PythonRuntimeSpec,
|
|
SecretBinding,
|
|
SecretReference,
|
|
FunctionDefinition,
|
|
_canonical_arrow_type,
|
|
_exact_arrow_type,
|
|
_GRAMMAR_PRIMITIVES,
|
|
function,
|
|
)
|
|
from lancedb.secrets import EnvVarSecret
|
|
from lancedb.remote.db import RemoteDBConnection
|
|
from utils import start_server_thread
|
|
|
|
THRESHOLD = 20
|
|
_CACHE = None
|
|
|
|
|
|
FIXTURES = (
|
|
Path(__file__).parents[3]
|
|
/ "rust"
|
|
/ "lancedb"
|
|
/ "tests"
|
|
/ "fixtures"
|
|
/ "first_class_functions"
|
|
/ "v1"
|
|
)
|
|
|
|
|
|
FUNCTION_VERSION = json.loads(
|
|
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
|
)["version"]
|
|
|
|
|
|
@function(
|
|
pip=["numpy>=2"],
|
|
env={"MODE": "test"},
|
|
python_version="3.12",
|
|
)
|
|
def normalize_score(value: float) -> float:
|
|
return value / 100.0
|
|
|
|
|
|
@function(
|
|
pip=["openai==3.7.0"],
|
|
env={"MODE": "test"},
|
|
python_version="3.12",
|
|
)
|
|
def analyze_caption(caption: str) -> str:
|
|
return caption.strip()
|
|
|
|
|
|
def _function_version_with_resolved_environment():
|
|
version = json.loads(
|
|
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
|
)
|
|
version["runtime"] = json.loads(
|
|
normalize_score.registration_request.runtime.to_canonical_json()
|
|
)
|
|
version["resolved_environment"] = {
|
|
"packages": [
|
|
{
|
|
"name": "torch",
|
|
"version": "2.9.0+cu130",
|
|
"source": "https://packages.example/simple",
|
|
},
|
|
{"name": "transformers", "version": "4.57.1"},
|
|
],
|
|
"provenance": {
|
|
"configured_index_urls": ["https://packages.example/simple"],
|
|
"configured_find_links": ["https://downloads.example/wheels"],
|
|
"resolved_indexes": ["https://packages.example/simple"],
|
|
"cuda_toolkit": "12.8",
|
|
"torch_version": "torch==2.9.0+cu130",
|
|
},
|
|
"warnings": [
|
|
"transformers resolved to transformers==4.57.1 but is not pinned "
|
|
"exactly; add transformers==4.57.1 to pin it."
|
|
],
|
|
}
|
|
return version
|
|
|
|
|
|
def _function_version_with_resolved_environments():
|
|
version = json.loads(
|
|
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
|
)
|
|
version["runtime"] = json.loads(
|
|
normalize_score.registration_request.runtime.to_canonical_json()
|
|
)
|
|
version["resolved_environments"] = {
|
|
"linux/amd64": {
|
|
"packages": [
|
|
{
|
|
"name": "torch",
|
|
"version": "2.9.0+cu130",
|
|
"source": "https://packages.example/simple",
|
|
}
|
|
],
|
|
"warnings": ["amd64 environment warning"],
|
|
},
|
|
"linux/arm64": {
|
|
"packages": [],
|
|
"warnings": ["arm64 environment warning"],
|
|
},
|
|
}
|
|
return version
|
|
|
|
|
|
def test_scalar_function_matches_shared_registration_golden_and_remains_callable():
|
|
assert isinstance(normalize_score, FunctionDefinition)
|
|
assert normalize_score(25.0) == 0.25
|
|
assert (
|
|
normalize_score.registration_request.to_canonical_json()
|
|
== (FIXTURES / "remote_function_registration_request.canonical.json")
|
|
.read_text()
|
|
.strip()
|
|
)
|
|
request = json.loads(normalize_score.registration_request.to_canonical_json())
|
|
assert request["artifact"]["adapter"] == {
|
|
"kind": "scalar_to_arrow_batch",
|
|
"version": 1,
|
|
}
|
|
|
|
|
|
def test_refresh_lock_is_a_registration_option_not_part_of_identity():
|
|
default = normalize_score.registration_request
|
|
old_json = default.to_canonical_json()
|
|
assert "refresh_lock" not in json.loads(old_json)
|
|
|
|
refreshed = default.with_refresh_lock(True)
|
|
payload = json.loads(refreshed.to_canonical_json())
|
|
assert payload["refresh_lock"] is True
|
|
assert (
|
|
FunctionRegistrationRequest.from_json(
|
|
refreshed.to_canonical_json()
|
|
).refresh_lock
|
|
is True
|
|
)
|
|
assert refreshed.artifact.digest == default.artifact.digest
|
|
assert refreshed.runtime.digest == default.runtime.digest
|
|
assert default.with_refresh_lock(False).to_canonical_json() == old_json
|
|
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
|
|
default.with_refresh_lock(1)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("exist_ok", [False, True])
|
|
async def test_async_create_function_forwards_refresh_lock(exist_ok):
|
|
calls = []
|
|
|
|
class Inner:
|
|
async def create_function_async(
|
|
self, request_json, namespace_path=None, *, exist_ok=False
|
|
):
|
|
calls.append((json.loads(request_json), namespace_path, exist_ok))
|
|
return object()
|
|
|
|
connection = object.__new__(AsyncConnection)
|
|
connection._inner = Inner()
|
|
await connection.create_function_async(normalize_score)
|
|
await connection.create_function_async(
|
|
normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"]
|
|
)
|
|
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
|
|
await connection.create_function_async(normalize_score, refresh_lock=1)
|
|
|
|
assert len(calls) == 2
|
|
assert "refresh_lock" not in calls[0][0]
|
|
assert calls[0][1:] == (None, False)
|
|
assert calls[1][0]["refresh_lock"] is True
|
|
assert calls[1][1:] == (["team"], exist_ok)
|
|
|
|
|
|
@pytest.mark.parametrize("exist_ok", [False, True])
|
|
def test_sync_create_function_paths_forward_refresh_lock(exist_ok):
|
|
calls = []
|
|
|
|
class AsyncInner:
|
|
async def create_function_async(
|
|
self,
|
|
definition,
|
|
*,
|
|
secrets=None,
|
|
exist_ok=False,
|
|
namespace_path=None,
|
|
refresh_lock=False,
|
|
):
|
|
calls.append(("wrapped", refresh_lock, namespace_path, exist_ok))
|
|
return object()
|
|
|
|
for connection_type in (LanceDBConnection, RemoteDBConnection):
|
|
connection = object.__new__(connection_type)
|
|
connection._conn = AsyncInner()
|
|
connection.create_function_async(
|
|
normalize_score,
|
|
refresh_lock=True,
|
|
exist_ok=exist_ok,
|
|
namespace_path=["team"],
|
|
)
|
|
|
|
class BlockingConnection:
|
|
def create_function_async(
|
|
self,
|
|
definition,
|
|
*,
|
|
secrets=None,
|
|
exist_ok=False,
|
|
namespace_path=None,
|
|
refresh_lock=False,
|
|
):
|
|
calls.append(("blocking", refresh_lock, namespace_path, exist_ok))
|
|
|
|
class ImmediateJob:
|
|
def wait(self):
|
|
return "version"
|
|
|
|
return ImmediateJob()
|
|
|
|
blocking = BlockingConnection()
|
|
assert (
|
|
DBConnection.create_function(
|
|
blocking,
|
|
normalize_score,
|
|
refresh_lock=True,
|
|
exist_ok=exist_ok,
|
|
namespace_path=["team"],
|
|
)
|
|
== "version"
|
|
)
|
|
assert calls == [
|
|
("wrapped", True, ["team"], exist_ok),
|
|
("wrapped", True, ["team"], exist_ok),
|
|
("blocking", True, ["team"], exist_ok),
|
|
]
|
|
|
|
|
|
def test_function_declares_pinned_hugging_face_models():
|
|
model = HuggingFaceModel(
|
|
repo="sentence-transformers/all-MiniLM-L6-v2",
|
|
revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
|
|
)
|
|
|
|
@function(pip=["sentence-transformers==3.3.1"], models=[model])
|
|
def embed_text(value: str) -> list[float]:
|
|
return [1.0]
|
|
|
|
request = json.loads(embed_text.registration_request.to_canonical_json())
|
|
assert request["models"] == [
|
|
{
|
|
"repo": "sentence-transformers/all-MiniLM-L6-v2",
|
|
"revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
|
|
}
|
|
]
|
|
undeclared = json.loads(normalize_score.registration_request.to_canonical_json())
|
|
assert "models" not in undeclared
|
|
|
|
with pytest.raises(ValueError, match="once"):
|
|
function(name="duplicate_model", models=[model, model])(lambda value: value)
|
|
with pytest.raises(ValueError, match="40-character"):
|
|
HuggingFaceModel(repo="owner/model", revision="main")
|
|
with pytest.raises(ValueError, match="reserve"):
|
|
function(
|
|
name="reserved_model_env",
|
|
models=[model],
|
|
env={"HF_HOME": "/tmp/model"},
|
|
)(lambda value: value)
|
|
|
|
|
|
def test_function_execution_controls_match_shared_registration_golden():
|
|
controlled = function(
|
|
pip=["numpy>=2"],
|
|
env={"MODE": "test"},
|
|
python_version="3.12",
|
|
batch_size=2,
|
|
max_concurrency=4,
|
|
row_timeout_seconds=0.75,
|
|
)(normalize_score.__wrapped__)
|
|
assert (
|
|
controlled.registration_request.to_canonical_json()
|
|
== (FIXTURES / "remote_function_controlled_registration_request.canonical.json")
|
|
.read_text()
|
|
.strip()
|
|
)
|
|
|
|
|
|
def test_function_execution_controls_apply_to_vectorized_functions():
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
|
output_schema=pa.int64(),
|
|
batch_size=3,
|
|
row_timeout_seconds=1.25,
|
|
)
|
|
def identity(value: pa.Array) -> pa.Array:
|
|
return value
|
|
|
|
request = json.loads(identity.registration_request.to_canonical_json())
|
|
assert request["batch_size"] == 3
|
|
assert request["row_timeout_seconds"] == 1.25
|
|
|
|
|
|
def test_function_retry_policy_is_part_of_registration():
|
|
policy = lancedb.FunctionRetryPolicy(transient=True, max_attempts=4)
|
|
definition = function(retry_policy=policy)(normalize_score.__wrapped__)
|
|
request = json.loads(definition.registration_request.to_canonical_json())
|
|
assert request["retry_policy"] == {"max_attempts": 4, "transient": True}
|
|
assert lancedb.FunctionRetryPolicy(max_attempts=1).max_attempts == 1
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"options",
|
|
[
|
|
{"max_attempts": 0, "transient": True},
|
|
{"max_attempts": 101, "transient": True},
|
|
{"max_attempts": True},
|
|
{"max_attempts": 3},
|
|
{"transient": True, "initial_backoff_seconds": -1},
|
|
{"transient": True, "max_backoff_seconds": float("inf")},
|
|
{"transient": True, "max_backoff_seconds": 0},
|
|
{"message_pattern": "["},
|
|
{"exception_types": [""]},
|
|
{"transient": True, "typo": 1},
|
|
],
|
|
)
|
|
def test_function_retry_policy_rejects_invalid_options(options):
|
|
with pytest.raises(ValueError):
|
|
lancedb.FunctionRetryPolicy(**options)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("options", "field"),
|
|
[
|
|
({"batch_size": 0}, "batch_size"),
|
|
({"batch_size": 2**32}, "batch_size"),
|
|
({"batch_size": True}, "batch_size"),
|
|
({"max_concurrency": 0}, "max_concurrency"),
|
|
({"max_concurrency": -1}, "max_concurrency"),
|
|
({"max_concurrency": 2**32}, "max_concurrency"),
|
|
({"max_concurrency": True}, "max_concurrency"),
|
|
({"max_concurrency": 1.5}, "max_concurrency"),
|
|
({"row_timeout_seconds": 0}, "row_timeout_seconds"),
|
|
({"row_timeout_seconds": -0.25}, "row_timeout_seconds"),
|
|
({"row_timeout_seconds": float("inf")}, "row_timeout_seconds"),
|
|
({"row_timeout_seconds": True}, "row_timeout_seconds"),
|
|
],
|
|
)
|
|
def test_function_execution_controls_require_their_positive_ranges(options, field):
|
|
def identity(value: int) -> int:
|
|
return value
|
|
|
|
with pytest.raises(ValueError, match=field):
|
|
function(**options)(identity)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"name", ["examples.image_info", "image-info", "image_info.", "image_info-"]
|
|
)
|
|
def test_function_rejects_function_names_with_periods_or_hyphens(name):
|
|
with pytest.raises(ValueError, match="invalid Function name"):
|
|
|
|
@function(name=name)
|
|
def image_info(value: int) -> int:
|
|
return value
|
|
|
|
|
|
@pytest.mark.parametrize("name", ["image_info", "ImageInfo123", "_image_info", "f"])
|
|
def test_function_accepts_function_names_with_letters_digits_and_underscores(name):
|
|
@function(name=name)
|
|
def image_info(value: int) -> int:
|
|
return value
|
|
|
|
assert image_info.registration_request.name == name
|
|
assert image_info(1) == 1
|
|
|
|
|
|
def test_secret_bound_function_matches_its_shared_registration_golden():
|
|
assert analyze_caption(" hello ") == "hello"
|
|
bound = analyze_caption.bind_secrets(
|
|
[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")]
|
|
)
|
|
assert (
|
|
bound.to_canonical_json()
|
|
== (FIXTURES / "remote_function_secret_registration_request.canonical.json")
|
|
.read_text()
|
|
.strip()
|
|
)
|
|
|
|
|
|
def test_a_namespaced_binding_records_the_path_and_the_name():
|
|
"""A binding names the parts, so nothing has to be parsed back out.
|
|
|
|
A root binding carries no path at all: the field is absent rather than an
|
|
empty list, so a binding states a namespace only when it has one.
|
|
"""
|
|
root = EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")
|
|
assert root.secret_namespace_path == []
|
|
|
|
nested = EnvVarSecret(
|
|
secret_name="openai-prod",
|
|
env_variable="OPENAI_API_KEY",
|
|
secret_namespace_path=["prod", "vision"],
|
|
)
|
|
assert nested.secret_namespace_path == ["prod", "vision"]
|
|
assert nested != root
|
|
|
|
bound = analyze_caption.bind_secrets([nested])
|
|
assert list(bound.secret_bindings) == [
|
|
SecretBinding(
|
|
kind="env",
|
|
variable="OPENAI_API_KEY",
|
|
secret_ref=SecretReference(
|
|
name="openai-prod", namespace_path=("prod", "vision")
|
|
),
|
|
)
|
|
]
|
|
|
|
at_root = analyze_caption.bind_secrets([root])
|
|
assert list(at_root.secret_bindings) == [
|
|
SecretBinding(
|
|
kind="env",
|
|
variable="OPENAI_API_KEY",
|
|
secret_ref=SecretReference(name="openai-prod"),
|
|
)
|
|
]
|
|
# A root binding carries no path at all on the wire.
|
|
canonical = json.loads(at_root.to_canonical_json())
|
|
assert canonical["secret_bindings"] == [
|
|
{
|
|
"kind": "env",
|
|
"variable": "OPENAI_API_KEY",
|
|
"secret_ref": {"name": "openai-prod"},
|
|
}
|
|
]
|
|
|
|
|
|
def test_a_namespace_path_is_validated_locally():
|
|
# The charset is the service's, not a delimiter's: a reference is never
|
|
# joined, so a segment cannot make anything parse two ways.
|
|
with pytest.raises(ValueError):
|
|
EnvVarSecret(
|
|
secret_name="openai-prod",
|
|
env_variable="K",
|
|
secret_namespace_path=["with$delim"],
|
|
)
|
|
with pytest.raises(ValueError):
|
|
EnvVarSecret(
|
|
secret_name="openai-prod", env_variable="K", secret_namespace_path=["a/b"]
|
|
)
|
|
# A bare string is a plausible mistake with the wrong meaning.
|
|
with pytest.raises(TypeError):
|
|
EnvVarSecret(
|
|
secret_name="openai-prod", env_variable="K", secret_namespace_path="prod"
|
|
)
|
|
|
|
|
|
def test_an_unbound_request_carries_no_binding_at_all():
|
|
"""Binding is a registration-time decision, so the definition holds none.
|
|
|
|
The decorator declares nothing about secrets, which is what makes the PRD's
|
|
claim true: a Function's source and its registration request are identical
|
|
whether or not a credential is later bound to it.
|
|
"""
|
|
unbound = json.loads(analyze_caption.registration_request.to_canonical_json())
|
|
assert "secret_bindings" not in unbound
|
|
assert "OPENAI_API_KEY" not in json.dumps(unbound)
|
|
|
|
|
|
def test_binding_a_secret_leaves_the_packaged_artifact_untouched():
|
|
"""The artifact is source bytes and nothing else, with or without secrets."""
|
|
bound = analyze_caption.bind_secrets(
|
|
[EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")]
|
|
)
|
|
assert bound.artifact == analyze_caption.registration_request.artifact
|
|
assert bound.artifact.digest == analyze_caption.registration_request.artifact.digest
|
|
|
|
|
|
def test_a_function_declaring_no_secret_is_registered_exactly_as_before():
|
|
"""The compatibility claim: nothing about the no-secret path moves."""
|
|
assert (
|
|
normalize_score.bind_secrets(None).to_canonical_json()
|
|
== normalize_score.registration_request.to_canonical_json()
|
|
)
|
|
assert (
|
|
"secret_bindings"
|
|
not in normalize_score.registration_request.to_canonical_json()
|
|
)
|
|
|
|
|
|
def test_a_function_binds_each_variable_once():
|
|
with pytest.raises(ValueError, match="binds each environment variable once"):
|
|
analyze_caption.bind_secrets(
|
|
[
|
|
EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY"),
|
|
EnvVarSecret(
|
|
secret_name="openai-staging", env_variable="OPENAI_API_KEY"
|
|
),
|
|
]
|
|
)
|
|
|
|
|
|
def test_bindings_may_not_collide_with_plain_configuration():
|
|
"""`env` is stored with the Function; a Secret is not. Refuse, do not pick."""
|
|
with pytest.raises(ValueError, match="must be disjoint"):
|
|
analyze_caption.bind_secrets(
|
|
[EnvVarSecret(secret_name="mode-prod", env_variable="MODE")]
|
|
)
|
|
|
|
|
|
_SECRET_DEBUG_LOG_SOURCE = """
|
|
import pyarrow as pa
|
|
import pyarrow.flight as flight
|
|
|
|
import lancedb
|
|
|
|
|
|
class SecretServer(flight.FlightServerBase):
|
|
def __init__(self):
|
|
super().__init__("grpc://127.0.0.1:0")
|
|
|
|
def do_exchange(self, context, descriptor, reader, writer):
|
|
assert b"SECRET_VALUE_SENTINEL" not in descriptor.command
|
|
parameters = reader.read_all()
|
|
assert parameters.column(0).to_pylist() == ["SECRET_VALUE_SENTINEL"]
|
|
result = pa.table({"status": ["created"]})
|
|
writer.begin(result.schema)
|
|
writer.write_table(result)
|
|
writer.close()
|
|
|
|
|
|
with SecretServer() as server:
|
|
db = lancedb.connect(
|
|
"db://dev",
|
|
api_key="API_KEY_SENTINEL",
|
|
host_override="http://localhost:10024",
|
|
sql_host_override=f"grpc://127.0.0.1:{server.port}",
|
|
)
|
|
db.create_secret("openai-prod", "SECRET_VALUE_SENTINEL")
|
|
"""
|
|
|
|
|
|
def test_a_credential_never_reaches_a_debug_log(tmp_path):
|
|
"""Credential parameters and authentication stay out of Flight debug logs.
|
|
|
|
Runs in a subprocess because the Rust logger reads ``LANCEDB_LOG`` once, at
|
|
import.
|
|
"""
|
|
pytest.importorskip("pyarrow.flight")
|
|
script = tmp_path / "write_secret.py"
|
|
script.write_text(_SECRET_DEBUG_LOG_SOURCE)
|
|
|
|
result = subprocess.run(
|
|
[sys.executable, str(script)],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
env={**os.environ, "LANCEDB_LOG": "debug"},
|
|
)
|
|
output = result.stdout + result.stderr
|
|
|
|
# Without this the test passes when debug logging is simply off.
|
|
assert "Created client for host:" in output, output
|
|
assert "SECRET_VALUE_SENTINEL" not in output
|
|
assert "API_KEY_SENTINEL" not in output
|
|
|
|
|
|
def test_a_credential_value_is_rejected_in_the_binding_position():
|
|
"""The one mistake the typed binding exists to stop."""
|
|
with pytest.raises(TypeError, match="EnvVarSecret"):
|
|
analyze_caption.bind_secrets(["sk-live-0001"])
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("secret", "variable", "message"),
|
|
[
|
|
("openai-prod", "not-a-var", "invalid environment variable name"),
|
|
("openai-prod", "API-TOKEN", "invalid environment variable name"),
|
|
("not a name", "API_TOKEN", "invalid Secret name"),
|
|
("openai$prod", "API_TOKEN", "invalid Secret name"),
|
|
],
|
|
)
|
|
def test_a_binding_validates_both_names_locally(secret, variable, message):
|
|
with pytest.raises(ValueError, match=message):
|
|
EnvVarSecret(secret_name=secret, env_variable=variable)
|
|
|
|
|
|
def test_a_secret_name_admits_what_a_namespace_name_does():
|
|
"""A Secret has to be nameable wherever a namespace already is.
|
|
|
|
LanceDB namespace and table names are `[A-Za-z0-9_.-]` with no rule about
|
|
which character comes first, so a name may lead with `_`, `-` or `.`.
|
|
Anything narrower here would leave Secrets unaddressable inside namespaces
|
|
that already exist -- the reason periods are admitted is the reason the
|
|
edges are too.
|
|
"""
|
|
for name in ["openai.prod.v1", ".hidden", "_internal", "-lead", "trailing."]:
|
|
binding = EnvVarSecret(secret_name=name, env_variable="OPENAI_API_KEY")
|
|
assert binding.secret_name == name
|
|
|
|
for name in ["", "with/slash", "with$delimiter", "a" * 256]:
|
|
with pytest.raises(ValueError, match="invalid Secret name"):
|
|
EnvVarSecret(secret_name=name, env_variable="OPENAI_API_KEY")
|
|
|
|
# A namespace segment follows the same rule, and LanceDB already admits
|
|
# these shapes as namespace names -- so a Secret is addressable inside one.
|
|
for segment in [".hidden", "_internal", "-lead", "trailing."]:
|
|
binding = EnvVarSecret(
|
|
secret_name="openai-prod",
|
|
env_variable="OPENAI_API_KEY",
|
|
secret_namespace_path=[segment],
|
|
)
|
|
assert binding.secret_namespace_path == [segment]
|
|
|
|
for segment in ["", "with/slash", "with$delimiter"]:
|
|
with pytest.raises(ValueError, match="invalid namespace path segment"):
|
|
EnvVarSecret(
|
|
secret_name="openai-prod",
|
|
env_variable="OPENAI_API_KEY",
|
|
secret_namespace_path=[segment],
|
|
)
|
|
|
|
|
|
def _main_function_source(
|
|
*, threshold: int = 20, input_annotation: str = "int", comparison: str = ">="
|
|
) -> str:
|
|
return (
|
|
"from __future__ import annotations\n"
|
|
"from lancedb.functions import function\n"
|
|
f"THRESHOLD = {threshold}\n"
|
|
"\n"
|
|
"@function\n"
|
|
f"def label(value: {input_annotation}) -> str:\n"
|
|
f" return 'big' if value {comparison} THRESHOLD else 'small'\n"
|
|
"\n"
|
|
"assert label.__module__ == '__main__'\n"
|
|
"print(label.registration_request.to_canonical_json())\n"
|
|
)
|
|
|
|
|
|
def _run_main_function(path: Path, source: str) -> dict:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(source)
|
|
result = subprocess.run(
|
|
[sys.executable, str(path)],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
def test_main_function_registration_identity_is_stable_across_processes_and_paths(
|
|
tmp_path,
|
|
):
|
|
source = _main_function_source()
|
|
original_path = tmp_path / "original" / "job.py"
|
|
moved_path = tmp_path / "moved" / "renamed_job.py"
|
|
|
|
original_runs = [_run_main_function(original_path, source) for _ in range(2)]
|
|
moved_run = _run_main_function(moved_path, source)
|
|
|
|
assert len({run["artifact"]["digest"] for run in [*original_runs, moved_run]}) == 1
|
|
assert all(
|
|
run["signature"] == original_runs[0]["signature"]
|
|
for run in [original_runs[1], moved_run]
|
|
)
|
|
assert original_runs[0] == original_runs[1] == moved_run
|
|
|
|
body_change = _run_main_function(
|
|
tmp_path / "changes" / "body.py", _main_function_source(comparison=">")
|
|
)
|
|
global_change = _run_main_function(
|
|
tmp_path / "changes" / "global.py", _main_function_source(threshold=21)
|
|
)
|
|
annotation_change = _run_main_function(
|
|
tmp_path / "changes" / "annotation.py",
|
|
_main_function_source(input_annotation="float"),
|
|
)
|
|
|
|
baseline = original_runs[0]
|
|
assert baseline["signature"] == body_change["signature"]
|
|
assert baseline["signature"] == global_change["signature"]
|
|
assert baseline["signature"] != annotation_change["signature"]
|
|
assert (
|
|
len(
|
|
{
|
|
baseline["artifact"]["digest"],
|
|
body_change["artifact"]["digest"],
|
|
global_change["artifact"]["digest"],
|
|
annotation_change["artifact"]["digest"],
|
|
}
|
|
)
|
|
== 4
|
|
)
|
|
|
|
|
|
def _run_packaged(definition, *args):
|
|
"""Execute the shipped artifact in a fresh namespace, as a worker would."""
|
|
source = base64.b64decode(definition.registration_request.artifact.content.data)
|
|
namespace: dict = {}
|
|
exec(compile(source, "<function>", "exec"), namespace)
|
|
return namespace[definition.registration_request.artifact.entrypoint](*args)
|
|
|
|
|
|
def _execute_registered_array_function_v1(
|
|
request: dict, batch: pa.RecordBatch
|
|
) -> pa.Array:
|
|
"""Exercise adapter-v1 annotation dispatch over a registered artifact."""
|
|
assert request["artifact"]["adapter"] == {
|
|
"kind": "scalar_to_arrow_batch",
|
|
"version": 1,
|
|
}
|
|
source = base64.b64decode(request["artifact"]["content"]["data"])
|
|
namespace = {
|
|
"pa": pa,
|
|
"pyarrow": pa,
|
|
"Array": pa.Array,
|
|
"RecordBatch": pa.RecordBatch,
|
|
"typing": typing,
|
|
}
|
|
exec(compile(source, "<registered-function>", "exec"), namespace)
|
|
function = namespace[request["artifact"]["entrypoint"]]
|
|
parameters = tuple(inspect.signature(function).parameters.values())
|
|
annotations = typing.get_type_hints(function)
|
|
assert parameters and all(
|
|
annotations.get(parameter.name) is pa.Array for parameter in parameters
|
|
)
|
|
assert annotations.get("return") is pa.Array
|
|
result = function(*(batch.column(parameter.name) for parameter in parameters))
|
|
assert isinstance(result, pa.Array)
|
|
return result
|
|
|
|
|
|
def test_function_conda_environment():
|
|
@function(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"])
|
|
def halve(value: float) -> float:
|
|
return value / 2
|
|
|
|
request = json.loads(halve.registration_request.to_canonical_json())
|
|
assert request["runtime"]["environment"] == {
|
|
"kind": "conda",
|
|
"packages": ["numpy", "scipy"],
|
|
"channels": ["conda-forge", "defaults"],
|
|
}
|
|
pip_request = json.loads(normalize_score.registration_request.to_canonical_json())
|
|
assert "channels" not in pip_request["runtime"]["environment"]
|
|
|
|
with pytest.raises(ValueError, match="not both"):
|
|
function(name="both", pip=["numpy"], conda=["numpy"])(lambda value: value)
|
|
with pytest.raises(ValueError, match="requires conda"):
|
|
function(name="channels", conda_channels=["conda-forge"])(lambda value: value)
|
|
|
|
|
|
def test_function_apt_system_packages():
|
|
@function(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"])
|
|
def decode(value: float) -> float:
|
|
return value
|
|
|
|
request = json.loads(decode.registration_request.to_canonical_json())
|
|
assert request["runtime"]["environment"] == {
|
|
"kind": "pip",
|
|
"packages": ["torchcodec"],
|
|
"system_packages": ["libavcodec60", "libavutil58"],
|
|
}
|
|
|
|
@function(conda=["numpy"], apt=["libsndfile1"])
|
|
def conda_decode(value: float) -> float:
|
|
return value
|
|
|
|
request = json.loads(conda_decode.registration_request.to_canonical_json())
|
|
assert request["runtime"]["environment"]["system_packages"] == ["libsndfile1"]
|
|
pip_request = json.loads(normalize_score.registration_request.to_canonical_json())
|
|
assert "system_packages" not in pip_request["runtime"]["environment"]
|
|
with pytest.raises(ValueError, match="trimmed"):
|
|
function(name="padded", apt=[" libsndfile1"])(lambda value: value)
|
|
|
|
|
|
@pytest.mark.parametrize("packages", [{"pip": ["numpy"]}, {"conda": ["numpy"]}])
|
|
def test_function_image(packages):
|
|
image = "ghcr.io/acme/embedder@sha256:" + "a" * 64
|
|
|
|
@function(image=image, **packages)
|
|
def embed(value: float) -> float:
|
|
return value
|
|
|
|
request = json.loads(embed.registration_request.to_canonical_json())
|
|
assert request["runtime"]["environment"]["image"] == image
|
|
pip_request = json.loads(normalize_score.registration_request.to_canonical_json())
|
|
assert "image" not in pip_request["runtime"]["environment"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"image", ["ghcr.io/acme/embedder:latest", "embedder@sha256:" + "a" * 64, ""]
|
|
)
|
|
def test_function_image_requires_digest_reference(image):
|
|
with pytest.raises(ValueError, match="sha256"):
|
|
function(name="pinned", image=image)(lambda value: value)
|
|
|
|
|
|
def test_function_gpu_marker_uses_gpu_runtime():
|
|
with pytest.warns(UserWarning, match="uses a scalar callable"):
|
|
|
|
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
|
|
def double_on_gpu(value: int) -> int:
|
|
return value * 2
|
|
|
|
request = json.loads(double_on_gpu.registration_request.to_canonical_json())
|
|
assert request["runtime"]["kind"] == "python_v2"
|
|
assert request["runtime"]["gpu"] is True
|
|
assert request["runtime"]["gpu_class"] == "a10g"
|
|
|
|
@function(pip=["pyarrow"])
|
|
def cpu_function(value: int) -> int:
|
|
return value
|
|
|
|
cpu_runtime = json.loads(cpu_function.registration_request.to_canonical_json())[
|
|
"runtime"
|
|
]
|
|
assert cpu_runtime["kind"] == "python"
|
|
assert "gpu" not in cpu_runtime
|
|
assert "gpu_class" not in cpu_runtime
|
|
|
|
def identity(value: int) -> int:
|
|
return value
|
|
|
|
for invalid in [None, 0, 1, -1, 1.5, "", "true", "1", "H100"]:
|
|
with pytest.raises(ValueError, match="gpu must be a boolean"):
|
|
function(name="invalid_gpu", gpu=invalid)(identity)
|
|
for invalid in ["H100", "a_b", "-a10g", "a10g-", "a" * 64]:
|
|
with pytest.raises(ValueError, match="gpu_class"):
|
|
function(name="invalid_gpu_class", gpu=True, gpu_class=invalid)(identity)
|
|
with pytest.raises(ValueError, match="requires gpu=True"):
|
|
function(name="gpu_class_without_gpu", gpu_class="a10g")(identity)
|
|
|
|
base_runtime = {
|
|
"kind": "python_v2",
|
|
"python_version": "3.12",
|
|
"environment": {"kind": "pip"},
|
|
}
|
|
runtime = PythonRuntimeSpec.model_validate({**base_runtime, "gpu": True})
|
|
assert runtime.gpu is True
|
|
runtime = PythonRuntimeSpec.model_validate(
|
|
{**base_runtime, "gpu": True, "gpu_class": "a10g"}
|
|
)
|
|
assert runtime.gpu_class == "a10g"
|
|
for invalid in [False, 1, 0, "", "true", "1", "H100"]:
|
|
with pytest.raises(ValueError, match="runtime.gpu must be true"):
|
|
PythonRuntimeSpec.model_validate({**base_runtime, "gpu": invalid})
|
|
with pytest.raises(ValueError, match="gpu_class"):
|
|
PythonRuntimeSpec.model_validate(
|
|
{**base_runtime, "gpu": True, "gpu_class": "H100"}
|
|
)
|
|
|
|
|
|
class _GpuScalarFunction:
|
|
def __call__(self, value: str) -> int:
|
|
return len(value)
|
|
|
|
|
|
class _GpuArrayFunction:
|
|
def __call__(self, value: pa.Array) -> pa.Array:
|
|
return value
|
|
|
|
|
|
def test_gpu_scalar_warning_names_the_vectorized_alternative():
|
|
with pytest.warns(UserWarning, match="model batch is not inferred"):
|
|
|
|
@function(gpu=True)
|
|
def scalar_embedding(value: str) -> list[int]:
|
|
return [len(value)]
|
|
|
|
input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)])
|
|
with pytest.warns(UserWarning, match="uses a scalar callable"):
|
|
class_scalar = function(_GpuScalarFunction, gpu=True)
|
|
with warnings.catch_warnings(record=True) as caught:
|
|
warnings.simplefilter("always")
|
|
|
|
@function(
|
|
gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
|
|
)
|
|
def array_embedding(value: pa.Array) -> pa.Array:
|
|
return value
|
|
|
|
@function(
|
|
gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
|
|
)
|
|
def record_batch_embedding(value: pa.RecordBatch) -> pa.Array:
|
|
return value.column(0)
|
|
|
|
@function
|
|
def cpu_scalar(value: str) -> int:
|
|
return len(value)
|
|
|
|
class_embedding = function(
|
|
_GpuArrayFunction,
|
|
gpu=True,
|
|
input_schema=input_schema,
|
|
output_schema=pa.list_(pa.int64()),
|
|
)
|
|
|
|
assert not caught
|
|
assert array_embedding.registration_request.batch_size is None
|
|
assert record_batch_embedding.registration_request.batch_size is None
|
|
assert cpu_scalar.registration_request.batch_size is None
|
|
assert class_scalar.registration_request.batch_size is None
|
|
assert class_embedding.registration_request.batch_size is None
|
|
|
|
|
|
def test_unknown_runtime_discards_payload_before_known_field_validation():
|
|
for payload in [
|
|
{
|
|
"kind": "python_v3",
|
|
"gpu": {"model": "H100"},
|
|
"gpu_class": "a10g",
|
|
},
|
|
{"kind": "python_v3", "resources": []},
|
|
{
|
|
"kind": "python_v3",
|
|
"environment": {"kind": []},
|
|
"python_version": 3.15,
|
|
},
|
|
]:
|
|
runtime = PythonRuntimeSpec.model_validate(payload)
|
|
assert runtime.to_canonical_json() == '{"kind":"python_v3"}'
|
|
|
|
|
|
def test_function_packages_attribute_access_and_body_imports():
|
|
@function
|
|
def word_norm(body: str) -> float:
|
|
import numpy as np
|
|
|
|
try:
|
|
words = body.split()
|
|
except AttributeError as error:
|
|
raise ValueError(str(error)) from error
|
|
return float(np.linalg.norm([len(w) for w in words]))
|
|
|
|
assert _run_packaged(word_norm, "aa bb") == pytest.approx(8**0.5)
|
|
|
|
|
|
def test_function_packages_module_globals_and_global_caches():
|
|
@function
|
|
def label(value: int) -> str:
|
|
return "big" if value >= THRESHOLD else "small"
|
|
|
|
assert _run_packaged(label, 21) == "big"
|
|
|
|
@function
|
|
def cached(value: int) -> int:
|
|
global _CACHE
|
|
if _CACHE is None:
|
|
_CACHE = 40
|
|
return _CACHE + value
|
|
|
|
assert _run_packaged(cached, 2) == 42
|
|
|
|
|
|
def test_function_annotations_are_not_runtime_names():
|
|
@function
|
|
def identity(value: date) -> date:
|
|
return value
|
|
|
|
assert _run_packaged(identity, date(2026, 8, 25)) == date(2026, 8, 25)
|
|
|
|
|
|
def test_function_nested_scopes_resolve_lexically():
|
|
@function
|
|
def score(value: int) -> int:
|
|
offset = 2
|
|
|
|
def add_offset() -> int:
|
|
return value + offset
|
|
|
|
return add_offset() + sum(v for v in [0])
|
|
|
|
assert _run_packaged(score, 3) == 5
|
|
|
|
|
|
def test_function_resolves_module_globals_before_builtins(tmp_path):
|
|
module_path = tmp_path / "shadowing_udfs.py"
|
|
module_path.write_text(
|
|
"max = 7\n"
|
|
"len = lambda _: 99\n"
|
|
"\n"
|
|
"def uses_literal_shadow(value: int) -> int:\n"
|
|
" def nested() -> int:\n"
|
|
" return max\n"
|
|
" return nested() + value\n"
|
|
"\n"
|
|
"def uses_callable_shadow(value: int) -> int:\n"
|
|
" def nested() -> int:\n"
|
|
" return len([1])\n"
|
|
" return nested() + value\n"
|
|
)
|
|
spec = importlib.util.spec_from_file_location("shadowing_udfs", module_path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
|
|
# The module's `max = 7` is what the interpreter would use, so it ships.
|
|
assert _run_packaged(function(module.uses_literal_shadow), 1) == 8
|
|
# A callable global cannot ship; it must not be silently swapped for the builtin.
|
|
with pytest.raises(TypeError, match="unsupported global value of type function"):
|
|
function(module.uses_callable_shadow)
|
|
|
|
|
|
def test_canonical_arrow_type_prefers_the_compact_grammar():
|
|
golden = json.loads(
|
|
(
|
|
Path(__file__).parents[3]
|
|
/ "rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json"
|
|
).read_text()
|
|
)
|
|
primitives = [
|
|
case["arrow_type"] for case in golden["valid"] if "<" not in case["arrow_type"]
|
|
]
|
|
assert [name for _, name in _GRAMMAR_PRIMITIVES] == primitives
|
|
assert _canonical_arrow_type(pa.list_(pa.field("item", pa.float32(), False))) == (
|
|
"list<float32>"
|
|
)
|
|
assert (
|
|
_canonical_arrow_type(pa.large_list(pa.field("item", pa.float32(), False)))
|
|
== "large_list<float32>"
|
|
)
|
|
for outside in [
|
|
pa.binary(4),
|
|
pa.time32("s"),
|
|
pa.time64("us"),
|
|
pa.list_(pa.float32(), 0),
|
|
]:
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
_canonical_arrow_type(outside)
|
|
|
|
|
|
def test_function_nested_annotations_are_postponed_in_the_artifact():
|
|
@function
|
|
def score(value: int) -> int:
|
|
def identity(item: date) -> date:
|
|
return item
|
|
|
|
identity(date(2026, 8, 25))
|
|
return value
|
|
|
|
assert _run_packaged(score, 3) == 3
|
|
|
|
|
|
def test_function_ships_globals_the_body_deletes():
|
|
@function
|
|
def clear(value: int) -> int:
|
|
global _CACHE
|
|
del _CACHE
|
|
return value
|
|
|
|
assert _run_packaged(clear, 3) == 3
|
|
|
|
|
|
def test_function_rejects_a_module_global_that_does_not_import_as_itself(tmp_path):
|
|
module_path = tmp_path / "fake_module_udfs.py"
|
|
module_path.write_text(
|
|
"import types\n"
|
|
"np = types.ModuleType('numpy')\n"
|
|
"np.sqrt = lambda x: 0\n"
|
|
"\n"
|
|
"def score(value: int) -> int:\n"
|
|
" return int(np.sqrt(value))\n"
|
|
)
|
|
spec = importlib.util.spec_from_file_location("fake_module_udfs", module_path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
with pytest.raises(TypeError, match="does not import as 'numpy'"):
|
|
function(module.score)
|
|
|
|
|
|
def test_function_rejects_a_module_level_namespace_alias(tmp_path):
|
|
module_path = tmp_path / "aliasing_udfs.py"
|
|
module_path.write_text(
|
|
"import builtins as b\n"
|
|
"THRESHOLD = 5\n"
|
|
"\n"
|
|
"def score(value: int) -> int:\n"
|
|
" return value + b.vars(b.__import__('aliasing_udfs'))['THRESHOLD']\n"
|
|
)
|
|
spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
with pytest.raises(ValueError, match="imports from namespace-access modules"):
|
|
function(module.score)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"access",
|
|
[
|
|
"globals()['THRESHOLD']",
|
|
"eval('THRESHOLD')",
|
|
"(lambda g: g()['THRESHOLD'])(globals)",
|
|
"__import__('sys').modules[__name__].THRESHOLD",
|
|
],
|
|
)
|
|
def test_function_rejects_dynamic_namespace_access(access):
|
|
namespace: dict = {}
|
|
exec(
|
|
f"def score(value: int) -> int:\n return value + {access}\n",
|
|
{"THRESHOLD": 5},
|
|
namespace,
|
|
)
|
|
with pytest.raises(ValueError, match="dynamic namespace access"):
|
|
_package_from_text(
|
|
f"def score(value: int) -> int:\n return value + {access}\n"
|
|
)
|
|
|
|
|
|
def _package_from_text(source: str, module_globals: dict | None = None):
|
|
"""Load `source` as a real module file so the packager can inspect it."""
|
|
import tempfile
|
|
|
|
directory = tempfile.mkdtemp()
|
|
path = Path(directory) / "generated_function_module.py"
|
|
path.write_text(source)
|
|
spec = importlib.util.spec_from_file_location(
|
|
f"generated_function_{id(source)}", path
|
|
)
|
|
module = importlib.util.module_from_spec(spec)
|
|
if module_globals:
|
|
module.__dict__.update(module_globals)
|
|
spec.loader.exec_module(module)
|
|
functions = [
|
|
value
|
|
for value in vars(module).values()
|
|
if callable(value) and getattr(value, "__module__", None) == module.__name__
|
|
]
|
|
return function(functions[0])
|
|
|
|
|
|
def test_function_rejects_a_non_standard_builtins_environment():
|
|
def score(value: int) -> int:
|
|
return len([1]) + value
|
|
|
|
score.__globals__ # noqa: B018 -- real function, real globals
|
|
import builtins
|
|
|
|
patched = types.FunctionType(
|
|
score.__code__,
|
|
{"__builtins__": {**vars(builtins), "len": lambda _: 99}},
|
|
"score",
|
|
)
|
|
patched.__annotations__ = score.__annotations__
|
|
assert patched(3) == 102
|
|
with pytest.raises(ValueError, match="non-standard builtins environment"):
|
|
function(patched)
|
|
|
|
class ReportingDict(dict): # reports standard entries, resolves differently
|
|
def __missing__(self, key):
|
|
return vars(builtins)[key]
|
|
|
|
disguised = types.FunctionType(
|
|
score.__code__, {"__builtins__": ReportingDict(len=lambda _: 99)}, "score"
|
|
)
|
|
disguised.__annotations__ = score.__annotations__
|
|
assert disguised(3) == 102
|
|
with pytest.raises(ValueError, match="non-standard builtins environment"):
|
|
function(disguised)
|
|
|
|
hooked = types.FunctionType(
|
|
score.__code__,
|
|
{"__builtins__": {**vars(builtins), "__import__": lambda *a, **k: None}},
|
|
"score",
|
|
)
|
|
hooked.__annotations__ = score.__annotations__
|
|
with pytest.raises(ValueError, match="non-standard builtins environment"):
|
|
function(hooked)
|
|
|
|
|
|
def test_function_recursion_versus_a_rebound_module_name(tmp_path):
|
|
module_path = tmp_path / "rebound_udfs.py"
|
|
module_path.write_text(
|
|
"def fact(value: int) -> int:\n"
|
|
" return 1 if value <= 1 else value * fact(value - 1)\n"
|
|
"\n"
|
|
"def score(value: int) -> int:\n"
|
|
" return score + value\n"
|
|
)
|
|
spec = importlib.util.spec_from_file_location("rebound_udfs", module_path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
assert _run_packaged(function(module.fact), 5) == 120
|
|
raw = module.score
|
|
module.score = 10
|
|
with pytest.raises(ValueError, match="binds that name to another value"):
|
|
function(raw)
|
|
# A wrapper that merely exposes __wrapped__ is not the function.
|
|
module.score = functools.wraps(raw)(lambda value: 41)
|
|
with pytest.raises(ValueError, match="binds that name to another value"):
|
|
function(raw)
|
|
# The decorator's own result is; a subclass of it is not.
|
|
module.fact = function(module.fact)
|
|
assert _run_packaged(module.fact, 4) == 24
|
|
|
|
class Twisted(FunctionDefinition):
|
|
def __call__(self, *args, **kwargs):
|
|
return 41
|
|
|
|
raw_fact = module.fact._function
|
|
module.fact = Twisted(
|
|
raw_fact,
|
|
name=None,
|
|
input_schema=None,
|
|
output_schema=None,
|
|
pip=(),
|
|
env={},
|
|
python_version=None,
|
|
)
|
|
with pytest.raises(ValueError, match="binds that name to another value"):
|
|
function(raw_fact)
|
|
|
|
|
|
def test_canonical_arrow_type_uses_exact_json_for_list_child_properties():
|
|
nullable = pa.list_(pa.float32())
|
|
assert json.loads(_canonical_arrow_type(nullable)) == {
|
|
"type": "list",
|
|
"fields": [
|
|
{
|
|
"name": "item",
|
|
"nullable": True,
|
|
"type": {"type": "float32"},
|
|
}
|
|
],
|
|
}
|
|
named = pa.list_(pa.field("custom", pa.float32(), nullable=False))
|
|
assert json.loads(_canonical_arrow_type(named))["fields"][0]["name"] == "custom"
|
|
for outside in [
|
|
pa.list_(pa.field("item", pa.float32(), nullable=False, metadata={"k": "v"})),
|
|
pa.list_(pa.field("item", pa.float32(), nullable=False), 0),
|
|
pa.list_(
|
|
pa.field("item", pa.float32(), nullable=False, metadata={"k": "v"}), 3
|
|
),
|
|
pa.list_(pa.field("custom", pa.float32(), nullable=False), 3),
|
|
]:
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
_canonical_arrow_type(outside)
|
|
assert (
|
|
_canonical_arrow_type(
|
|
pa.list_(pa.field("item", pa.float32(), nullable=False), 3)
|
|
)
|
|
== "fixed_size_list<float32, 3>"
|
|
)
|
|
fixed = json.loads(_canonical_arrow_type(pa.list_(pa.float32(), 3)))
|
|
assert fixed == {
|
|
"type": "fixed_size_list",
|
|
"fields": [
|
|
{
|
|
"name": "item",
|
|
"nullable": True,
|
|
"type": {"type": "float32"},
|
|
}
|
|
],
|
|
"length": 3,
|
|
}
|
|
large = json.loads(_canonical_arrow_type(pa.large_list(pa.float32())))
|
|
assert large["type"] == "large_list"
|
|
assert large["fields"][0]["nullable"] is True
|
|
|
|
for invalid_struct in [
|
|
pa.struct([]),
|
|
pa.struct([pa.field("a", pa.int32()), pa.field("a", pa.int64())]),
|
|
pa.struct([pa.field("", pa.int32())]),
|
|
]:
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
_canonical_arrow_type(invalid_struct)
|
|
|
|
|
|
def _calls_missing(value: int) -> int:
|
|
return missing(value) # noqa: F821
|
|
|
|
|
|
def _shadows_missing_in_a_comprehension(value: int) -> int:
|
|
return missing(value) + sum(missing for missing in ()) # noqa: F821
|
|
|
|
|
|
def _shadows_missing_in_a_lambda(value: int) -> int:
|
|
return (lambda missing: missing)(value) + missing # noqa: F821
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"target",
|
|
[_calls_missing, _shadows_missing_in_a_comprehension, _shadows_missing_in_a_lambda],
|
|
)
|
|
def test_function_rejects_a_truly_unresolved_global(target):
|
|
with pytest.raises(ValueError, match=r"unresolved global names: \['missing'\]"):
|
|
function(target)
|
|
|
|
|
|
def _arrow_type_from_golden(spec: dict) -> pa.DataType:
|
|
kind = spec["type"]
|
|
if kind in ("list", "large_list", "fixed_size_list"):
|
|
item = _arrow_type_from_golden(spec["fields"][0]["type"])
|
|
field = pa.field("item", item, nullable=False)
|
|
if kind == "list":
|
|
return pa.list_(field)
|
|
if kind == "large_list":
|
|
return pa.large_list(field)
|
|
return pa.list_(field, spec["length"])
|
|
return {
|
|
"null": pa.null(),
|
|
"bool": pa.bool_(),
|
|
"utf8": pa.string(),
|
|
"large_utf8": pa.large_string(),
|
|
"binary": pa.binary(),
|
|
"float16": pa.float16(),
|
|
"float32": pa.float32(),
|
|
"float64": pa.float64(),
|
|
"date32": pa.date32(),
|
|
"date64": pa.date64(),
|
|
}.get(kind) or getattr(pa, kind)()
|
|
|
|
|
|
def test_arrow_type_grammar_matches_the_shared_golden():
|
|
golden = json.loads(
|
|
(
|
|
Path(__file__).parents[3]
|
|
/ "rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json"
|
|
).read_text()
|
|
)
|
|
emitted = {
|
|
case["arrow_type"]: _canonical_arrow_type(_arrow_type_from_golden(case["json"]))
|
|
for case in golden["valid"]
|
|
}
|
|
assert emitted == {
|
|
case["arrow_type"]: case["arrow_type"] for case in golden["valid"]
|
|
}
|
|
assert not set(emitted) & set(golden["invalid"])
|
|
for case in golden["server_only"]:
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
_canonical_arrow_type(_arrow_type_from_golden(case["json"]))
|
|
|
|
|
|
def test_explicit_arrow_schema_is_deterministic():
|
|
input_schema = pa.schema([pa.field("value", pa.float32(), nullable=True)])
|
|
output_schema = pa.field(
|
|
"embedding",
|
|
pa.list_(pa.field("item", pa.float32(), nullable=False), 3),
|
|
nullable=False,
|
|
)
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def explicit(value):
|
|
return [value, value, value]
|
|
|
|
signature = explicit.registration_request.signature
|
|
assert signature.inputs[0].arrow_type == "float32"
|
|
assert signature.inputs[0].nullable is True
|
|
assert signature.output.arrow_type == "fixed_size_list<float32, 3>"
|
|
assert signature.output.nullable is False
|
|
|
|
|
|
def test_timestamp_annotation_and_explicit_schema_serialization():
|
|
for unit in ("s", "ms", "us", "ns"):
|
|
for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"):
|
|
encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone)))
|
|
if unit == "us" and timezone is None:
|
|
assert encoded == {"type": "timestamp"}
|
|
else:
|
|
suffix = timezone if timezone is not None else "-"
|
|
assert encoded == {"type": f"timestamp:{unit}:{suffix}"}
|
|
|
|
with pytest.raises(TypeError, match="reserved for no timezone"):
|
|
_canonical_arrow_type(pa.timestamp("us", tz="-"))
|
|
|
|
@function
|
|
def normalize(
|
|
ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
|
|
) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
|
|
return ts
|
|
|
|
signature = normalize.registration_request.signature
|
|
assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"}
|
|
assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"}
|
|
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
|
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
|
assert round_trip.output.arrow_type == signature.output.arrow_type
|
|
|
|
@function
|
|
def optional_timestamp(
|
|
ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]],
|
|
) -> int:
|
|
return 0
|
|
|
|
optional_input = optional_timestamp.registration_request.signature.inputs[0]
|
|
assert optional_input.nullable is True
|
|
assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"}
|
|
|
|
@function
|
|
def legacy(ts: datetime) -> datetime:
|
|
return ts
|
|
|
|
legacy_signature = legacy.registration_request.signature
|
|
assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"}
|
|
assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"}
|
|
legacy_round_trip = FunctionSignature.from_json(
|
|
legacy_signature.to_canonical_json()
|
|
)
|
|
assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}'
|
|
|
|
input_schema = pa.schema(
|
|
[pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)]
|
|
)
|
|
output_schema = pa.schema(
|
|
[
|
|
pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True),
|
|
pa.field("elapsed", pa.duration("ms"), nullable=False),
|
|
]
|
|
)
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def nested(ts):
|
|
return {"ts": ts, "elapsed": None}
|
|
|
|
nested_signature = nested.registration_request.signature
|
|
assert nested_signature.inputs[0].nullable is True
|
|
assert json.loads(nested_signature.inputs[0].arrow_type) == {
|
|
"type": "timestamp:ms:America/New_York"
|
|
}
|
|
assert nested_signature.output.kind == "named_struct"
|
|
assert nested_signature.output.fields[0].nullable is True
|
|
assert json.loads(nested_signature.output.fields[0].arrow_type) == {
|
|
"type": "timestamp:ns:+08:00"
|
|
}
|
|
assert json.loads(nested_signature.output.fields[1].arrow_type) == {
|
|
"type": "duration:ms"
|
|
}
|
|
|
|
list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False))
|
|
assert json.loads(_canonical_arrow_type(list_type)) == {
|
|
"type": "list",
|
|
"fields": [
|
|
{
|
|
"name": "item",
|
|
"nullable": False,
|
|
"type": {"type": "timestamp:ms:UTC"},
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
def test_duration_annotation_and_explicit_schema_serialization():
|
|
for unit in ("s", "ms", "us", "ns"):
|
|
encoded = json.loads(_canonical_arrow_type(pa.duration(unit)))
|
|
expected = (
|
|
{"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"}
|
|
)
|
|
assert encoded == expected
|
|
|
|
@function
|
|
def elapsed(
|
|
value: Annotated[timedelta, pa.duration("s")],
|
|
) -> Annotated[timedelta, pa.duration("ns")]:
|
|
return value
|
|
|
|
signature = elapsed.registration_request.signature
|
|
assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"}
|
|
assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"}
|
|
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
|
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
|
assert round_trip.output.arrow_type == signature.output.arrow_type
|
|
|
|
@function
|
|
def optional_elapsed(
|
|
value: Optional[Annotated[timedelta, pa.duration("ms")]],
|
|
) -> int:
|
|
return 0
|
|
|
|
optional_input = optional_elapsed.registration_request.signature.inputs[0]
|
|
assert optional_input.nullable is True
|
|
assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"}
|
|
|
|
with pytest.raises(
|
|
TypeError, match="timedelta Function annotations require an explicit unit"
|
|
):
|
|
|
|
@function
|
|
def missing(value: timedelta) -> timedelta:
|
|
return value
|
|
|
|
input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)])
|
|
output_schema = pa.field("result", pa.duration("us"), nullable=False)
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def explicit(elapsed: timedelta) -> timedelta:
|
|
return elapsed
|
|
|
|
explicit_signature = explicit.registration_request.signature
|
|
assert explicit_signature.inputs[0].nullable is True
|
|
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
|
|
"type": "duration:ms"
|
|
}
|
|
assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"}
|
|
explicit_round_trip = FunctionSignature.from_json(
|
|
explicit_signature.to_canonical_json()
|
|
)
|
|
assert explicit_round_trip.output.arrow_type == '{"type":"duration"}'
|
|
|
|
|
|
def test_map_annotation_and_explicit_schema_serialization():
|
|
@function
|
|
def map_round_trip(values: dict[str, int]) -> dict[str, int]:
|
|
return values
|
|
|
|
signature = map_round_trip.registration_request.signature
|
|
expected = {
|
|
"type": "map",
|
|
"fields": [
|
|
{
|
|
"name": "entries",
|
|
"nullable": False,
|
|
"type": {
|
|
"type": "struct",
|
|
"fields": [
|
|
{
|
|
"name": "key",
|
|
"nullable": False,
|
|
"type": {"type": "utf8"},
|
|
},
|
|
{
|
|
"name": "value",
|
|
"nullable": False,
|
|
"type": {"type": "int64"},
|
|
},
|
|
],
|
|
},
|
|
}
|
|
],
|
|
}
|
|
assert json.loads(signature.inputs[0].arrow_type) == expected
|
|
assert json.loads(signature.output.arrow_type) == expected
|
|
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
|
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
|
assert round_trip.output.arrow_type == signature.output.arrow_type
|
|
|
|
@function
|
|
def nullable_values(
|
|
values: dict[str, Optional[int]],
|
|
) -> dict[str, Optional[int]]:
|
|
return values
|
|
|
|
nullable_signature = nullable_values.registration_request.signature
|
|
nullable_map = json.loads(nullable_signature.inputs[0].arrow_type)
|
|
assert nullable_map["fields"][0]["type"]["fields"][1] == {
|
|
"name": "value",
|
|
"nullable": True,
|
|
"type": {"type": "int64"},
|
|
}
|
|
|
|
input_schema = pa.schema(
|
|
[
|
|
pa.field(
|
|
"values",
|
|
pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)),
|
|
nullable=False,
|
|
)
|
|
]
|
|
)
|
|
output_schema = pa.field(
|
|
"result",
|
|
pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)),
|
|
nullable=False,
|
|
)
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def explicit(values):
|
|
return {}
|
|
|
|
explicit_signature = explicit.registration_request.signature
|
|
explicit_input = json.loads(explicit_signature.inputs[0].arrow_type)
|
|
assert explicit_input["fields"][0]["type"]["fields"][1] == {
|
|
"name": "custom",
|
|
"nullable": True,
|
|
"type": {"type": "int64"},
|
|
}
|
|
explicit_output = json.loads(explicit_signature.output.arrow_type)
|
|
assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False
|
|
|
|
|
|
def test_map_rejects_unsupported_boundaries():
|
|
with pytest.raises(TypeError, match="map keys_sorted=true"):
|
|
_canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True))
|
|
with pytest.raises(TypeError, match="map keys must be non-nullable utf8"):
|
|
_canonical_arrow_type(pa.map_(pa.int64(), pa.int64()))
|
|
with pytest.raises(TypeError, match="Blob v2 fields nested under"):
|
|
_canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type))
|
|
with pytest.raises(TypeError, match="map keys must be str"):
|
|
|
|
@function
|
|
def invalid_keys(values: dict[int, int]) -> int:
|
|
return 0
|
|
|
|
|
|
def test_decimal_annotation_and_explicit_schema_serialization():
|
|
@function
|
|
def price(
|
|
amount: Annotated[Decimal, pa.decimal128(10, 2)],
|
|
) -> Annotated[Decimal, pa.decimal256(50, 4)]:
|
|
return Decimal("1.0000")
|
|
|
|
signature = price.registration_request.signature
|
|
assert json.loads(signature.inputs[0].arrow_type) == {
|
|
"type": "decimal128",
|
|
"length": 10002,
|
|
}
|
|
assert json.loads(signature.output.arrow_type) == {
|
|
"type": "decimal256",
|
|
"length": 50004,
|
|
}
|
|
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
|
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
|
assert round_trip.output.arrow_type == signature.output.arrow_type
|
|
assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == {
|
|
"type": "decimal128",
|
|
"length": 9998,
|
|
}
|
|
decimal_map = json.loads(
|
|
_canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2)))
|
|
)
|
|
assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == {
|
|
"type": "decimal128",
|
|
"length": 10002,
|
|
}
|
|
|
|
input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)])
|
|
output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False)
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def explicit(amount: Decimal) -> Decimal:
|
|
return amount
|
|
|
|
explicit_signature = explicit.registration_request.signature
|
|
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
|
|
"type": "decimal128",
|
|
"length": 12002,
|
|
}
|
|
assert json.loads(explicit_signature.output.arrow_type) == {
|
|
"type": "decimal256",
|
|
"length": 60006,
|
|
}
|
|
|
|
with pytest.raises(
|
|
TypeError, match="Decimal Function annotations require precision and scale"
|
|
):
|
|
|
|
@function
|
|
def missing(amount: Decimal) -> Decimal:
|
|
return amount
|
|
|
|
|
|
def test_nullable_scalar_output_annotation_and_explicit_schema():
|
|
input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
|
|
|
|
@function(input_schema=input_schema)
|
|
def optional_annotation(value: int) -> Optional[int]:
|
|
return None if value == 0 else value * 2
|
|
|
|
@function(input_schema=input_schema)
|
|
def optional_union(value: int) -> int | None:
|
|
return None if value == 0 else value * 2
|
|
|
|
@function(
|
|
input_schema=input_schema,
|
|
output_schema=pa.field("result", pa.int64(), nullable=True),
|
|
)
|
|
def explicit_schema(value: int):
|
|
return None if value == 0 else value * 2
|
|
|
|
for definition in (optional_annotation, optional_union, explicit_schema):
|
|
signature = definition.registration_request.signature
|
|
assert (signature.output.kind, signature.output.arrow_type) == (
|
|
"scalar",
|
|
"int64",
|
|
)
|
|
assert signature.output.nullable is True
|
|
assert json.loads(signature.to_canonical_json())["output"] == {
|
|
"kind": "scalar",
|
|
"arrow_type": "int64",
|
|
"nullable": True,
|
|
}
|
|
assert (
|
|
FunctionSignature.from_json(signature.to_canonical_json()).output.nullable
|
|
is True
|
|
)
|
|
|
|
|
|
def test_blob_fields_use_the_scalar_function_semantic_type():
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
|
|
output_schema=lancedb.blob("result", nullable=False),
|
|
)
|
|
def copy_blob(image):
|
|
return image
|
|
|
|
signature = copy_blob.registration_request.signature
|
|
assert signature.inputs[0].arrow_type == "blob_v2"
|
|
assert signature.output.kind == "scalar"
|
|
assert signature.output.arrow_type == "blob_v2"
|
|
|
|
|
|
def test_blob_input_access_is_inferred_from_annotations():
|
|
@function
|
|
def read_blob(video: BlobReader, timestamp_s: float) -> bytes:
|
|
video.seek(int(timestamp_s))
|
|
return video.read(4)
|
|
|
|
@function
|
|
def read_bytes(video: bytes) -> int:
|
|
return len(video)
|
|
|
|
reader = read_blob.registration_request.signature
|
|
assert reader.inputs[0].arrow_type == "blob_v2"
|
|
assert reader.inputs[0].blob_access == "reader"
|
|
assert reader.inputs[1].blob_access is None
|
|
assert reader.output.arrow_type == "binary"
|
|
eager = read_bytes.registration_request.signature.inputs[0]
|
|
assert eager.arrow_type == "binary"
|
|
assert eager.blob_access == "bytes"
|
|
encoded = json.loads(read_blob.registration_request.to_canonical_json())
|
|
assert encoded["signature"]["inputs"][0]["blob_access"] == "reader"
|
|
|
|
|
|
def test_nullable_blob_reader_and_explicit_blob_bytes():
|
|
@function
|
|
def nullable(video: Optional[BlobReader]) -> int:
|
|
return 0 if video is None else video.size()
|
|
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("video", nullable=False)]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
def eager(video: bytes) -> int:
|
|
return len(video)
|
|
|
|
parameter = nullable.registration_request.signature.inputs[0]
|
|
assert parameter.nullable is True
|
|
assert parameter.blob_access == "reader"
|
|
parameter = eager.registration_request.signature.inputs[0]
|
|
assert parameter.arrow_type == "blob_v2"
|
|
assert parameter.blob_access == "bytes"
|
|
|
|
|
|
def test_blob_reader_rejects_an_incompatible_explicit_schema():
|
|
def read(video: BlobReader) -> int:
|
|
return video.size()
|
|
|
|
with pytest.raises(TypeError, match="requires a Blob V2 field"):
|
|
function(
|
|
read,
|
|
input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
|
|
|
|
def test_whole_named_struct_function_can_include_a_blob_result_field():
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
|
|
output_schema=pa.field(
|
|
"payload",
|
|
pa.struct(
|
|
[
|
|
pa.field("mime_type", pa.string(), nullable=False),
|
|
lancedb.blob("image", nullable=False),
|
|
]
|
|
),
|
|
nullable=False,
|
|
),
|
|
)
|
|
def inspect_blob(image):
|
|
return {"mime_type": "image/png", "image": image}
|
|
|
|
output = inspect_blob.registration_request.signature.output
|
|
assert output.kind == "named_struct"
|
|
assert [(field.name, field.arrow_type) for field in output.fields] == [
|
|
("mime_type", "utf8"),
|
|
("image", "blob_v2"),
|
|
]
|
|
|
|
|
|
def test_struct_blob_signature_fields_preserve_exact_metadata_and_nullability():
|
|
nested_input = pa.field(
|
|
"payload",
|
|
pa.struct(
|
|
[
|
|
pa.field("mime_type", pa.string(), nullable=False),
|
|
pa.field(
|
|
"nested",
|
|
pa.struct([lancedb.blob("image", nullable=True)]),
|
|
nullable=True,
|
|
),
|
|
]
|
|
),
|
|
nullable=True,
|
|
)
|
|
nested_output = pa.field(
|
|
"result",
|
|
pa.struct(
|
|
[
|
|
pa.field("mime_type", pa.string(), nullable=False),
|
|
pa.field(
|
|
"nested",
|
|
pa.struct([lancedb.blob("image", nullable=True)]),
|
|
nullable=False,
|
|
),
|
|
]
|
|
),
|
|
nullable=False,
|
|
)
|
|
|
|
@function(input_schema=pa.schema([nested_input]), output_schema=nested_output)
|
|
def copy_payload(payload):
|
|
return payload
|
|
|
|
signature = copy_payload.registration_request.signature
|
|
input_type = json.loads(signature.inputs[0].arrow_type)
|
|
assert input_type["fields"][1]["nullable"] is True
|
|
input_blob = input_type["fields"][1]["type"]["fields"][0]
|
|
assert input_blob["nullable"] is True
|
|
assert input_blob["metadata"] == {"ARROW:extension:name": "lance.blob.v2"}
|
|
|
|
assert signature.output.kind == "named_struct"
|
|
nested_result = next(
|
|
field for field in signature.output.fields if field.name == "nested"
|
|
)
|
|
output_type = json.loads(nested_result.arrow_type)
|
|
output_blob = output_type["fields"][0]
|
|
assert output_blob["nullable"] is True
|
|
assert output_blob["metadata"] == {"ARROW:extension:name": "lance.blob.v2"}
|
|
|
|
|
|
def test_struct_blob_signature_supports_multiple_struct_levels():
|
|
recursive = pa.field(
|
|
"value",
|
|
pa.struct(
|
|
[
|
|
pa.field(
|
|
"level_1",
|
|
pa.struct(
|
|
[
|
|
pa.field(
|
|
"level_2",
|
|
pa.struct([lancedb.blob("image", nullable=False)]),
|
|
nullable=False,
|
|
)
|
|
]
|
|
),
|
|
nullable=False,
|
|
)
|
|
]
|
|
),
|
|
nullable=False,
|
|
)
|
|
|
|
@function(
|
|
input_schema=pa.schema([recursive]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
def blob_size(value):
|
|
return len(value["level_1"]["level_2"]["image"])
|
|
|
|
encoded = json.loads(blob_size.registration_request.signature.inputs[0].arrow_type)
|
|
blob = encoded["fields"][0]["type"]["fields"][0]["type"]["fields"][0]
|
|
assert blob["metadata"]["ARROW:extension:name"] == "lance.blob.v2"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data_type",
|
|
[
|
|
pa.list_(lancedb.blob("item", nullable=False)),
|
|
pa.large_list(lancedb.blob("item", nullable=False)),
|
|
pa.list_(pa.struct([lancedb.blob("image", nullable=False)])),
|
|
],
|
|
)
|
|
def test_blob_output_accepts_list_ancestors(data_type):
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("video", nullable=False)]),
|
|
output_schema=pa.field("frames", data_type, nullable=False),
|
|
)
|
|
def extract_frames(video: bytes) -> list:
|
|
return [video]
|
|
|
|
output = extract_frames.registration_request.signature.output
|
|
assert json.loads(output.arrow_type) == _exact_arrow_type(
|
|
data_type, collection_blobs=True
|
|
)
|
|
assert "lance.blob.v2" in output.arrow_type
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data_type",
|
|
[
|
|
pa.map_(pa.string(), lancedb.blob("value", nullable=False).type),
|
|
pa.list_(lancedb.blob("item", nullable=False), 2),
|
|
pa.list_(pa.list_(lancedb.blob("item", nullable=False), 2)),
|
|
],
|
|
)
|
|
def test_blob_output_rejects_map_and_fixed_size_list_ancestors(data_type):
|
|
with pytest.raises(TypeError, match="nested under collection types"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]),
|
|
output_schema=pa.field("frames", data_type, nullable=False),
|
|
)
|
|
def frames(id: int) -> dict:
|
|
return {}
|
|
|
|
|
|
def test_blob_output_named_struct_accepts_list_ancestor():
|
|
frames_type = pa.list_(lancedb.blob("item", nullable=False))
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("id", pa.int64(), nullable=False)]),
|
|
output_schema=pa.schema(
|
|
[
|
|
pa.field("frames", frames_type, nullable=False),
|
|
pa.field("count", pa.int64(), nullable=False),
|
|
]
|
|
),
|
|
)
|
|
def extract_frames(id: int) -> dict:
|
|
return {"frames": [], "count": 0}
|
|
|
|
output = extract_frames.registration_request.signature.output
|
|
assert output.kind == "named_struct"
|
|
assert [field.name for field in output.fields] == ["frames", "count"]
|
|
assert json.loads(output.fields[0].arrow_type) == _exact_arrow_type(
|
|
frames_type, collection_blobs=True
|
|
)
|
|
assert "lance.blob.v2" in output.fields[0].arrow_type
|
|
assert output.fields[1].arrow_type == "int64"
|
|
assert output.fields[1].nullable is False
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data_type",
|
|
[
|
|
pa.list_(lancedb.blob("item", nullable=False)),
|
|
pa.large_list(lancedb.blob("item", nullable=False)),
|
|
pa.list_(lancedb.blob("item", nullable=False), 2),
|
|
pa.map_(pa.string(), lancedb.blob("value", nullable=False).type),
|
|
],
|
|
)
|
|
def test_blob_signature_rejects_collection_ancestors(data_type):
|
|
with pytest.raises(
|
|
TypeError,
|
|
match="Blob v2 fields nested under collection types are not supported",
|
|
):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", data_type, nullable=False)]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
def blob_size(value):
|
|
return len(value)
|
|
|
|
|
|
def test_blob_signature_rejects_collection_below_a_struct():
|
|
nested = pa.field(
|
|
"value",
|
|
pa.struct(
|
|
[
|
|
pa.field(
|
|
"images",
|
|
pa.list_(lancedb.blob("item", nullable=False)),
|
|
nullable=False,
|
|
)
|
|
]
|
|
),
|
|
nullable=False,
|
|
)
|
|
with pytest.raises(
|
|
TypeError,
|
|
match="Blob v2 fields nested under collection types are not supported",
|
|
):
|
|
|
|
@function(
|
|
input_schema=pa.schema([nested]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
def blob_size(value):
|
|
return len(value["images"])
|
|
|
|
|
|
def test_blob_fields_support_vectorized_pyarrow_arrays():
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=True)]),
|
|
output_schema=lancedb.blob("result", nullable=False),
|
|
)
|
|
def copy_blobs(image: pa.Array) -> pa.Array:
|
|
return pa.array(
|
|
[value.as_py() if value.is_valid else b"" for value in image],
|
|
type=pa.large_binary(),
|
|
)
|
|
|
|
values = pa.array([b"large blob", b"", None], type=pa.large_binary())
|
|
request = json.loads(copy_blobs.registration_request.to_canonical_json())
|
|
batch = pa.RecordBatch.from_arrays([values], names=["image"])
|
|
result = _execute_registered_array_function_v1(request, batch)
|
|
assert isinstance(result, pa.LargeBinaryArray)
|
|
assert result.to_pylist() == [b"large blob", b"", b""]
|
|
|
|
signature = copy_blobs.registration_request.signature
|
|
assert signature.inputs[0].arrow_type == "blob_v2"
|
|
assert signature.inputs[0].nullable is True
|
|
assert signature.output.arrow_type == "blob_v2"
|
|
assert signature.output.nullable is False
|
|
assert copy_blobs.registration_request.artifact.adapter.kind == (
|
|
"scalar_to_arrow_batch"
|
|
)
|
|
assert copy_blobs.registration_request.artifact.adapter.version == 1
|
|
|
|
source = base64.b64decode(
|
|
copy_blobs.registration_request.artifact.content.data
|
|
).decode("utf-8")
|
|
assert "def copy_blobs(image: pa.Array) -> pa.Array:" in source
|
|
|
|
|
|
def test_documented_blob_array_identity_executes_packaged_artifact():
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
|
|
output_schema=lancedb.blob("copy", nullable=False),
|
|
)
|
|
def copy_blobs(image: pa.Array) -> pa.Array:
|
|
return image
|
|
|
|
values = pa.array([b"large blob", b""], type=pa.large_binary())
|
|
request = json.loads(copy_blobs.registration_request.to_canonical_json())
|
|
result = _execute_registered_array_function_v1(
|
|
request,
|
|
pa.RecordBatch.from_arrays([values], names=["image"]),
|
|
)
|
|
assert result.equals(values)
|
|
|
|
|
|
def test_named_struct_function_can_include_a_blob_result_field():
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
|
|
output_schema=pa.schema(
|
|
[
|
|
lancedb.blob("thumbnail", nullable=False),
|
|
pa.field("width", pa.int32(), nullable=False),
|
|
]
|
|
),
|
|
)
|
|
def inspect_blob(image):
|
|
return {"thumbnail": image, "width": 1}
|
|
|
|
output = inspect_blob.registration_request.signature.output
|
|
assert output.kind == "named_struct"
|
|
assert [(field.name, field.arrow_type) for field in output.fields] == [
|
|
("thumbnail", "blob_v2"),
|
|
("width", "int32"),
|
|
]
|
|
|
|
|
|
def test_named_struct_function_preserves_nullable_result_fields():
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
|
output_schema=pa.schema(
|
|
[
|
|
pa.field("result", pa.int64(), nullable=True),
|
|
pa.field("failure_code", pa.int32(), nullable=False),
|
|
]
|
|
),
|
|
)
|
|
def nullable_result(value):
|
|
return {"result": value, "failure_code": 0}
|
|
|
|
output = nullable_result.registration_request.signature.output
|
|
assert [(field.name, field.nullable) for field in output.fields] == [
|
|
("result", True),
|
|
("failure_code", False),
|
|
]
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
|
|
output_schema=pa.schema(
|
|
[
|
|
pa.field("result", pa.int64(), nullable=True),
|
|
pa.field("failure_code", pa.int32(), nullable=True),
|
|
]
|
|
),
|
|
)
|
|
def all_nullable(value):
|
|
return {"result": value, "failure_code": None}
|
|
|
|
assert all(
|
|
field.nullable
|
|
for field in all_nullable.registration_request.signature.output.fields
|
|
)
|
|
|
|
|
|
def test_metadata_marked_blob_field_uses_the_semantic_type():
|
|
extension = lancedb.blob("image", nullable=False).type
|
|
storage = (
|
|
extension.storage_type if isinstance(extension, pa.ExtensionType) else extension
|
|
)
|
|
metadata_blob = pa.field(
|
|
"image",
|
|
storage,
|
|
nullable=False,
|
|
metadata={"ARROW:extension:name": "lance.blob.v2"},
|
|
)
|
|
|
|
@function(
|
|
input_schema=pa.schema([metadata_blob]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
def blob_size(image):
|
|
return len(image)
|
|
|
|
assert blob_size.registration_request.signature.inputs[0].arrow_type == "blob_v2"
|
|
|
|
|
|
def test_blob_marker_rejects_invalid_storage_layout():
|
|
malformed = pa.field(
|
|
"image",
|
|
pa.int64(),
|
|
nullable=False,
|
|
metadata={"ARROW:extension:name": "lance.blob.v2"},
|
|
)
|
|
|
|
with pytest.raises(TypeError, match="requires a supported Blob storage layout"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([malformed]),
|
|
output_schema=pa.field("size", pa.int64(), nullable=False),
|
|
)
|
|
def blob_size(image):
|
|
return len(image)
|
|
|
|
|
|
def test_nested_non_blob_extension_is_not_silently_unwrapped():
|
|
class TestExtension(pa.ExtensionType):
|
|
def __init__(self):
|
|
super().__init__(pa.int64(), "test.function.extension")
|
|
|
|
def __arrow_ext_serialize__(self):
|
|
return b""
|
|
|
|
@classmethod
|
|
def __arrow_ext_deserialize__(cls, storage_type, serialized):
|
|
return cls()
|
|
|
|
nested = pa.field(
|
|
"value",
|
|
pa.struct([pa.field("extended", TestExtension(), nullable=False)]),
|
|
nullable=False,
|
|
)
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([nested]),
|
|
output_schema=pa.field("result", pa.int64(), nullable=False),
|
|
)
|
|
def extension_value(value):
|
|
return value["extended"]
|
|
|
|
|
|
def test_explicit_large_utf8_schemas_use_the_canonical_function_name():
|
|
input_schema = pa.schema([pa.field("text", pa.large_string(), nullable=True)])
|
|
output_schema = pa.field("result", pa.large_string(), nullable=False)
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def preserve(text):
|
|
return text
|
|
|
|
signature = preserve.registration_request.signature
|
|
assert signature.inputs[0].arrow_type == "large_utf8"
|
|
assert signature.inputs[0].nullable is True
|
|
assert signature.output.arrow_type == "large_utf8"
|
|
assert signature.output.nullable is False
|
|
|
|
nested = pa.struct([pa.field("text", pa.large_string(), nullable=True)])
|
|
assert json.loads(_canonical_arrow_type(nested)) == {
|
|
"type": "struct",
|
|
"fields": [
|
|
{
|
|
"name": "text",
|
|
"nullable": True,
|
|
"type": {"type": "large_utf8"},
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
def test_large_binary_schemas_use_the_canonical_function_name():
|
|
payload = pa.field("data", pa.large_binary(), nullable=True)
|
|
|
|
@function(
|
|
input_schema=pa.schema([payload]),
|
|
output_schema=pa.field("result", pa.large_binary(), nullable=False),
|
|
)
|
|
def preserve(data):
|
|
return data
|
|
|
|
signature = preserve.registration_request.signature
|
|
assert signature.inputs[0].arrow_type == "large_binary"
|
|
assert signature.output.arrow_type == "large_binary"
|
|
cells = pa.large_list(pa.field("item", pa.struct([payload]), nullable=True))
|
|
assert json.loads(_canonical_arrow_type(cells))["fields"][0]["type"] == {
|
|
"type": "struct",
|
|
"fields": [
|
|
{"name": "data", "nullable": True, "type": {"type": "large_binary"}}
|
|
],
|
|
}
|
|
|
|
|
|
def test_nested_struct_output_uses_canonical_exact_json():
|
|
token = pa.struct(
|
|
[
|
|
pa.field("position", pa.int32(), nullable=False),
|
|
pa.field("value", pa.string(), nullable=False),
|
|
pa.field("length", pa.int32(), nullable=False),
|
|
]
|
|
)
|
|
analysis = pa.struct(
|
|
[
|
|
pa.field("normalized_text", pa.string(), nullable=False),
|
|
pa.field("has_content", pa.bool_(), nullable=False),
|
|
pa.field(
|
|
"metrics",
|
|
pa.struct(
|
|
[
|
|
pa.field("character_count", pa.int64(), nullable=False),
|
|
pa.field("word_count", pa.int32(), nullable=False),
|
|
pa.field("average_word_length", pa.float64(), nullable=False),
|
|
]
|
|
),
|
|
nullable=False,
|
|
),
|
|
pa.field(
|
|
"diagnostics",
|
|
pa.struct(
|
|
[
|
|
pa.field("status", pa.string(), nullable=False),
|
|
pa.field(
|
|
"normalization",
|
|
pa.struct(
|
|
[
|
|
pa.field("changed", pa.bool_(), nullable=False),
|
|
pa.field(
|
|
"original_length", pa.int64(), nullable=False
|
|
),
|
|
]
|
|
),
|
|
nullable=False,
|
|
),
|
|
]
|
|
),
|
|
nullable=False,
|
|
),
|
|
pa.field(
|
|
"token_preview",
|
|
pa.list_(pa.field("item", token, nullable=False)),
|
|
nullable=False,
|
|
),
|
|
]
|
|
)
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]),
|
|
output_schema=pa.field("analysis", analysis, nullable=False),
|
|
)
|
|
def analyze(text):
|
|
return {"normalized_text": text}
|
|
|
|
output = analyze.registration_request.signature.output
|
|
assert output.kind == "named_struct"
|
|
assert [field.name for field in output.fields] == [
|
|
"normalized_text",
|
|
"has_content",
|
|
"metrics",
|
|
"diagnostics",
|
|
"token_preview",
|
|
]
|
|
metrics = json.loads(output.fields[2].arrow_type)
|
|
assert metrics == {
|
|
"type": "struct",
|
|
"fields": [
|
|
{
|
|
"name": "character_count",
|
|
"nullable": False,
|
|
"type": {"type": "int64"},
|
|
},
|
|
{
|
|
"name": "word_count",
|
|
"nullable": False,
|
|
"type": {"type": "int32"},
|
|
},
|
|
{
|
|
"name": "average_word_length",
|
|
"nullable": False,
|
|
"type": {"type": "float64"},
|
|
},
|
|
],
|
|
}
|
|
preview = json.loads(output.fields[4].arrow_type)
|
|
assert preview["type"] == "list"
|
|
assert preview["fields"][0]["type"]["type"] == "struct"
|
|
assert [field["name"] for field in preview["fields"][0]["type"]["fields"]] == [
|
|
"position",
|
|
"value",
|
|
"length",
|
|
]
|
|
|
|
|
|
def test_annotation_and_explicit_schema_validation_fail_closed():
|
|
with pytest.raises(TypeError, match="missing Function annotations"):
|
|
|
|
@function
|
|
def missing(value):
|
|
return value
|
|
|
|
with pytest.raises(TypeError, match="unsupported Function annotation"):
|
|
|
|
@function
|
|
def unsupported(value: set[str]) -> str:
|
|
return ""
|
|
|
|
with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"):
|
|
|
|
@function(input_schema=pa.schema([pa.field("value", pa.int64())]))
|
|
def partial_schema(value):
|
|
return value
|
|
|
|
with pytest.raises(ValueError, match="exactly match callable parameters"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("other", pa.int64())]),
|
|
output_schema=pa.int64(),
|
|
)
|
|
def wrong_name(value):
|
|
return value
|
|
|
|
with pytest.raises(ValueError, match="output must be non-nullable"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64())]),
|
|
output_schema=pa.field(
|
|
"result",
|
|
pa.struct([pa.field("value", pa.int64(), nullable=False)]),
|
|
nullable=True,
|
|
),
|
|
)
|
|
def nullable_struct(value):
|
|
return {"value": value}
|
|
|
|
with pytest.raises(
|
|
ValueError, match="Blob v2 Function output must be non-nullable"
|
|
):
|
|
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
|
|
output_schema=lancedb.blob("result", nullable=True),
|
|
)
|
|
def nullable_blob(image):
|
|
return image
|
|
|
|
for invalid_field in [
|
|
pa.field("", pa.int32(), nullable=False),
|
|
pa.field("result", pa.int32(), nullable=False, metadata={"k": "v"}),
|
|
]:
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64())]),
|
|
output_schema=pa.schema([invalid_field]),
|
|
)
|
|
def invalid_explicit_field(value):
|
|
return value
|
|
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
|
|
@function(
|
|
input_schema=pa.schema(
|
|
[pa.field("value", pa.int64(), metadata={"k": "v"})]
|
|
),
|
|
output_schema=pa.int64(),
|
|
)
|
|
def input_field_metadata(value):
|
|
return value
|
|
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64())]),
|
|
output_schema=pa.field(
|
|
"result", pa.int64(), nullable=False, metadata={"k": "v"}
|
|
),
|
|
)
|
|
def scalar_output_field_metadata(value):
|
|
return value
|
|
|
|
struct_type = pa.struct([pa.field("value", pa.int64(), nullable=False)])
|
|
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("value", pa.int64())]),
|
|
output_schema=pa.field(
|
|
"result", struct_type, nullable=False, metadata={"k": "v"}
|
|
),
|
|
)
|
|
def struct_output_field_metadata(value):
|
|
return {"value": value}
|
|
|
|
for input_schema, output_schema in [
|
|
(
|
|
pa.schema([pa.field("value", pa.int64())], metadata={"k": "v"}),
|
|
pa.int64(),
|
|
),
|
|
(
|
|
pa.schema([pa.field("value", pa.int64())]),
|
|
pa.schema(
|
|
[pa.field("result", pa.int64(), nullable=False)],
|
|
metadata={"k": "v"},
|
|
),
|
|
),
|
|
]:
|
|
with pytest.raises(TypeError, match="schema metadata"):
|
|
|
|
@function(input_schema=input_schema, output_schema=output_schema)
|
|
def schema_metadata(value):
|
|
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"
|
|
with pytest.raises(NotImplementedError, match=message):
|
|
db.create_function(normalize_score)
|
|
with pytest.raises(NotImplementedError, match=message):
|
|
db.create_function_async(normalize_score)
|
|
with pytest.raises(NotImplementedError, match=message):
|
|
db.get_function("normalize_score", version=FUNCTION_VERSION)
|
|
with pytest.raises(NotImplementedError, match=message):
|
|
db.get_function("normalize_score")
|
|
with pytest.raises(NotImplementedError, match=message):
|
|
list(db.list_functions())
|
|
with pytest.raises(NotImplementedError, match=message):
|
|
db.drop_function("normalize_score", version=FUNCTION_VERSION)
|
|
|
|
|
|
class _RawFunctionCatalog:
|
|
def __init__(self, definition, *, encode=False):
|
|
self.definition = json.dumps(definition) if encode else definition
|
|
self.requested_versions = []
|
|
|
|
async def get_function(self, _name, version=None, namespace_path=None):
|
|
self.requested_versions.append(version)
|
|
return self.definition
|
|
|
|
def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None):
|
|
return self
|
|
|
|
def __aiter__(self):
|
|
return self
|
|
|
|
async def __anext__(self):
|
|
if self.definition is None:
|
|
raise StopAsyncIteration
|
|
definition, self.definition = self.definition, None
|
|
return definition
|
|
|
|
def num_page_results(self):
|
|
return int(self.definition is not None)
|
|
|
|
def page_token(self):
|
|
return None
|
|
|
|
|
|
def test_function_version_reads_requested_and_resolved_environments():
|
|
legacy = json.loads(
|
|
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
|
)
|
|
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
|
|
assert legacy_version.runtime is None
|
|
assert legacy_version.resolved_environment is None
|
|
assert legacy_version.environment.requested is None
|
|
assert legacy_version.environment.resolved is None
|
|
|
|
payload = _function_version_with_resolved_environment()
|
|
version = FunctionVersion.from_json(json.dumps(payload))
|
|
assert version.environment.requested is version.runtime
|
|
assert version.environment.resolved is version.resolved_environment
|
|
assert version.runtime.kind == "python"
|
|
resolved = version.resolved_environment
|
|
assert resolved.packages[0].version == "2.9.0+cu130"
|
|
assert resolved.packages[0].source == "https://packages.example/simple"
|
|
assert resolved.packages[1].source is None
|
|
assert resolved.provenance.torch_version == "torch==2.9.0+cu130"
|
|
assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"])
|
|
|
|
encoded = json.loads(version.to_canonical_json())
|
|
assert encoded["runtime"]["kind"] == "python"
|
|
assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130"
|
|
assert "source" not in encoded["resolved_environment"]["packages"][1]
|
|
assert (
|
|
encoded["resolved_environment"]["provenance"]["torch_version"]
|
|
== "torch==2.9.0+cu130"
|
|
)
|
|
assert FunctionVersion.from_json(version.to_canonical_json()) == version
|
|
|
|
invalid = json.loads(json.dumps(payload))
|
|
del invalid["resolved_environment"]["packages"]
|
|
with pytest.raises(ValueError):
|
|
FunctionVersion.from_json(json.dumps(invalid))
|
|
|
|
|
|
def test_function_version_reads_resolved_environments_by_platform():
|
|
legacy = json.loads(
|
|
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
|
)
|
|
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
|
|
assert legacy_version.resolved_environment is None
|
|
assert legacy_version.resolved_environments == {}
|
|
assert legacy_version.environment_report == {}
|
|
|
|
payload = _function_version_with_resolved_environments()
|
|
version = FunctionVersion.from_json(json.dumps(payload))
|
|
assert version.resolved_environment is None
|
|
assert version.resolved_environments == version.environment_report
|
|
assert set(version.environment_report) == {"linux/amd64", "linux/arm64"}
|
|
assert (
|
|
version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130"
|
|
)
|
|
assert version.environment_report["linux/arm64"].packages == ()
|
|
assert version.environment_report["linux/arm64"].warnings == (
|
|
"arm64 environment warning",
|
|
)
|
|
|
|
encoded = json.loads(version.to_canonical_json())
|
|
assert "resolved_environment" not in encoded
|
|
assert (
|
|
encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"]
|
|
== "2.9.0+cu130"
|
|
)
|
|
assert encoded["resolved_environments"]["linux/arm64"]["packages"] == []
|
|
assert FunctionVersion.from_json(version.to_canonical_json()) == version
|
|
|
|
missing_platform = json.loads(json.dumps(payload))
|
|
del missing_platform["resolved_environments"]["linux/arm64"]
|
|
missing_version = FunctionVersion.from_json(json.dumps(missing_platform))
|
|
assert "linux/arm64" not in missing_version.environment_report
|
|
assert "linux/amd64" in missing_version.environment_report
|
|
|
|
empty_map = json.loads(json.dumps(payload))
|
|
empty_map["resolved_environments"] = {}
|
|
empty_version = FunctionVersion.from_json(json.dumps(empty_map))
|
|
assert empty_version.resolved_environments == {}
|
|
assert "resolved_environments" not in json.loads(empty_version.to_canonical_json())
|
|
|
|
invalid = json.loads(json.dumps(payload))
|
|
del invalid["resolved_environments"]["linux/amd64"]["packages"]
|
|
with pytest.raises(ValueError):
|
|
FunctionVersion.from_json(json.dumps(invalid))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_registration_job_emits_server_environment_warnings_once():
|
|
payload = _function_version_with_resolved_environment()
|
|
|
|
class InnerJob:
|
|
async def wait(self):
|
|
return json.dumps(payload)
|
|
|
|
class Inner:
|
|
async def create_function_async(
|
|
self, request_json, namespace_path=None, *, exist_ok=False
|
|
):
|
|
assert "refresh_lock" not in json.loads(request_json)
|
|
return InnerJob()
|
|
|
|
connection = object.__new__(AsyncConnection)
|
|
connection._inner = Inner()
|
|
job = await connection.create_function_async(normalize_score)
|
|
with pytest.warns(UserWarning) as recorded:
|
|
version = await job.wait()
|
|
assert [str(w.message) for w in recorded] == list(
|
|
payload["resolved_environment"]["warnings"]
|
|
)
|
|
assert version.environment.resolved.warnings == tuple(
|
|
payload["resolved_environment"]["warnings"]
|
|
)
|
|
with warnings.catch_warnings(record=True) as caught:
|
|
warnings.simplefilter("always")
|
|
assert await job.wait() is not None
|
|
assert caught == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_registration_job_emits_per_platform_environment_warnings():
|
|
payload = _function_version_with_resolved_environments()
|
|
|
|
class InnerJob:
|
|
async def wait(self):
|
|
return json.dumps(payload)
|
|
|
|
class Inner:
|
|
async def create_function_async(
|
|
self, request_json, namespace_path=None, *, exist_ok=False
|
|
):
|
|
return InnerJob()
|
|
|
|
connection = object.__new__(AsyncConnection)
|
|
connection._inner = Inner()
|
|
job = await connection.create_function_async(normalize_score)
|
|
with pytest.warns(UserWarning) as recorded:
|
|
version = await job.wait()
|
|
assert [str(w.message) for w in recorded] == [
|
|
"amd64 environment warning",
|
|
"arm64 environment warning",
|
|
]
|
|
assert version.environment_report["linux/arm64"].warnings == (
|
|
"arm64 environment warning",
|
|
)
|
|
with warnings.catch_warnings(record=True) as caught:
|
|
warnings.simplefilter("always")
|
|
assert await job.wait() is not None
|
|
assert caught == []
|
|
|
|
|
|
def test_blocking_create_function_emits_server_environment_warnings():
|
|
payload = _function_version_with_resolved_environment()
|
|
|
|
class InnerJob:
|
|
async def wait(self):
|
|
return json.dumps(payload)
|
|
|
|
class Inner:
|
|
async def create_function_async(
|
|
self, request_json, namespace_path=None, *, exist_ok=False
|
|
):
|
|
return InnerJob()
|
|
|
|
connection = object.__new__(RemoteDBConnection)
|
|
connection._conn = AsyncConnection(Inner())
|
|
with pytest.warns(UserWarning) as recorded:
|
|
version = DBConnection.create_function(connection, normalize_score)
|
|
assert [str(w.message) for w in recorded] == list(
|
|
payload["resolved_environment"]["warnings"]
|
|
)
|
|
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_catalog_readback_does_not_replay_registration_warnings():
|
|
payload = _function_version_with_resolved_environment()
|
|
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
|
|
with warnings.catch_warnings(record=True) as caught:
|
|
warnings.simplefilter("always")
|
|
version = await connection.get_function("embed")
|
|
listed = [item async for item in connection.list_functions()]
|
|
assert caught == []
|
|
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
|
|
assert listed[0].environment.resolved == version.resolved_environment
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_catalog_readback_does_not_replay_per_platform_warnings():
|
|
payload = _function_version_with_resolved_environments()
|
|
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
|
|
with warnings.catch_warnings(record=True) as caught:
|
|
warnings.simplefilter("always")
|
|
version = await connection.get_function("embed")
|
|
listed = [item async for item in connection.list_functions()]
|
|
assert caught == []
|
|
assert version.environment_report == listed[0].environment_report
|
|
|
|
|
|
def _assert_execution_control_encoding(version):
|
|
encoded = json.loads(version.to_canonical_json())
|
|
assert type(encoded["batch_size"]) is int
|
|
assert type(encoded["row_timeout_seconds"]) is float
|
|
assert type(encoded["result_stability"]) is str
|
|
return encoded
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_catalog_path_preserves_execution_controls():
|
|
definition = json.loads(
|
|
(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",
|
|
)
|
|
catalog = _RawFunctionCatalog(definition, encode=True)
|
|
connection = AsyncConnection(catalog)
|
|
|
|
latest = await connection.get_function("embed")
|
|
integer = await connection.get_function("embed", version=1)
|
|
exact = await connection.get_function("embed", version="1")
|
|
await connection.get_function("embed", version="001")
|
|
listed = [item async for item in connection.list_functions(page_limit=32)]
|
|
assert len(listed) == 1
|
|
for version in [latest, integer, exact, *listed]:
|
|
assert _assert_execution_control_encoding(version) == definition
|
|
assert catalog.requested_versions == [None, "1", "1", "001"]
|
|
with pytest.raises(TypeError, match="int, str, or None"):
|
|
await connection.get_function("embed", version=True)
|
|
with pytest.raises(TypeError, match="int, str, or None"):
|
|
await connection.get_function("embed", version=1.5)
|
|
|
|
|
|
def test_sync_catalog_path_preserves_execution_controls():
|
|
definition = json.loads(
|
|
(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",
|
|
)
|
|
connection = object.__new__(RemoteDBConnection)
|
|
catalog = _RawFunctionCatalog(FunctionVersion(**definition))
|
|
connection._conn = catalog
|
|
|
|
latest = connection.get_function("embed")
|
|
integer = connection.get_function("embed", version=1)
|
|
exact = connection.get_function("embed", version="1")
|
|
connection.get_function("embed", version="001")
|
|
listed = list(connection.list_functions(page_limit=32))
|
|
assert len(listed) == 1
|
|
for version in [latest, integer, exact, *listed]:
|
|
assert _assert_execution_control_encoding(version) == definition
|
|
assert catalog.requested_versions == [None, "1", "1", "001"]
|
|
with pytest.raises(TypeError, match="int, str, or None"):
|
|
connection.get_function("embed", version=True)
|
|
with pytest.raises(TypeError, match="int, str, or None"):
|
|
connection.get_function("embed", version=1.5)
|
|
|
|
|
|
def test_sync_drop_function_emits_server_warnings_without_changing_bool_api():
|
|
class _DropConnection:
|
|
async def drop_function(self, name, *, version, namespace_path=None):
|
|
return True
|
|
|
|
async def _drop_function_with_warnings(
|
|
self, name, *, version, namespace_path=None
|
|
):
|
|
return True, [
|
|
'materialized view "pinned" references Function "embed" version "1"'
|
|
]
|
|
|
|
connection = object.__new__(RemoteDBConnection)
|
|
connection._conn = _DropConnection()
|
|
|
|
with pytest.warns(UserWarning, match="references Function"):
|
|
assert connection.drop_function("embed", version="1") is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_drop_function_emits_server_warnings_without_changing_bool_api():
|
|
class _Inner:
|
|
async def _drop_function_with_warnings(
|
|
self, name, version, namespace_path=None
|
|
):
|
|
return True, [
|
|
'materialized view "pinned" references Function "embed" version "1"'
|
|
]
|
|
|
|
async def drop_function(self, name, version, namespace_path=None):
|
|
return True
|
|
|
|
connection = object.__new__(AsyncConnection)
|
|
connection._inner = _Inner()
|
|
|
|
with pytest.warns(UserWarning, match="references Function"):
|
|
assert await connection.drop_function("embed", version="1") is True
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def _mock_remote_function_catalog():
|
|
state = {"requests": [], "version": None}
|
|
|
|
class Handler(http.server.BaseHTTPRequestHandler):
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
def _write_response(self, status, response):
|
|
encoded = json.dumps(response).encode()
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(encoded)))
|
|
self.end_headers()
|
|
self.wfile.write(encoded)
|
|
|
|
def do_POST(self):
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
body = json.loads(self.rfile.read(length) or b"{}")
|
|
state["requests"].append((self.path, body))
|
|
status = 200
|
|
# `{id}` is the Function name, so match on the shape rather than on
|
|
# one name: these tests register more than one Function.
|
|
parts = self.path.strip("/").split("/")
|
|
function_action = (
|
|
(urllib.parse.unquote(parts[2]), parts[3])
|
|
if len(parts) == 4 and parts[0] == "v1" and parts[1] == "function"
|
|
else (None, None)
|
|
)
|
|
secret_action = (
|
|
(urllib.parse.unquote(parts[2]), parts[3])
|
|
if len(parts) == 4 and parts[0] == "v1" and parts[1] == "secret"
|
|
else (None, None)
|
|
)
|
|
if function_action[1] == "create":
|
|
*namespace_path, name = function_action[0].split("$")
|
|
state["version"] = {
|
|
"name": name,
|
|
**({"namespace_path": namespace_path} if namespace_path else {}),
|
|
"version": FUNCTION_VERSION,
|
|
"object_id": "fixture",
|
|
"location": "memory:///fixture",
|
|
"metadata": {},
|
|
"disabled": False,
|
|
"image": json.loads(
|
|
(
|
|
FIXTURES / "remote_function_version.canonical.json"
|
|
).read_text()
|
|
)["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
|
|
}
|
|
response = {"job_id": "job-register"}
|
|
status = 202
|
|
elif self.path == "/v1/jobs/describe":
|
|
assert body == {"job_id": "job-register"}
|
|
response = {
|
|
"job_id": "job-register",
|
|
"job_type": "create_function",
|
|
"job_state": "DONE",
|
|
"result": state["version"],
|
|
}
|
|
# A namespaced Function's id is its namespace path and name joined
|
|
# by `$`, so the name is the last segment of it.
|
|
elif (
|
|
function_action[1] == "describe"
|
|
and function_action[0].split("$")[-1] == "normalize_score"
|
|
):
|
|
assert body == {"version": FUNCTION_VERSION}
|
|
response = state["version"]
|
|
elif (
|
|
function_action[1] == "drop"
|
|
and function_action[0].split("$")[-1] == "normalize_score"
|
|
):
|
|
assert body == {"version": FUNCTION_VERSION}
|
|
response = {"dropped": True}
|
|
elif secret_action[1] in ("create", "alter"):
|
|
# The Secret is the path identifier, so the body is the value.
|
|
assert set(body) == {"value"}
|
|
assert secret_action[0] == "openai-prod"
|
|
response = {}
|
|
elif secret_action[1] == "drop":
|
|
assert secret_action[0] == "openai-prod"
|
|
assert body == {}
|
|
response = {}
|
|
else:
|
|
status = 404
|
|
response = {"error": "not found"}
|
|
self._write_response(status, response)
|
|
|
|
def do_GET(self):
|
|
url = urllib.parse.urlsplit(self.path)
|
|
query = {
|
|
key: values[-1]
|
|
for key, values in urllib.parse.parse_qs(url.query).items()
|
|
}
|
|
state["requests"].append((url.path, query))
|
|
if url.path == "/v1/namespace/$/secret/list":
|
|
if "page_token" not in query:
|
|
self._write_response(
|
|
200,
|
|
{"secrets": [{"name": "openai-prod"}], "page_token": "next"},
|
|
)
|
|
else:
|
|
assert query["page_token"] == "next"
|
|
self._write_response(200, {"secrets": [{"name": "hf-prod"}]})
|
|
return
|
|
parts = url.path.strip("/").split("/")
|
|
if parts[:2] != ["v1", "namespace"] or parts[3:] != ["function", "list"]:
|
|
self._write_response(404, {"error": "not found"})
|
|
return
|
|
assert query["include_definition"] == "true"
|
|
if "page_token" not in query:
|
|
response = {
|
|
"functions": [
|
|
{
|
|
"name": "normalize_score",
|
|
"version": FUNCTION_VERSION,
|
|
"definition": state["version"],
|
|
}
|
|
],
|
|
"page_token": "next",
|
|
}
|
|
else:
|
|
assert query["page_token"] == "next"
|
|
response = {"functions": []}
|
|
self._write_response(200, response)
|
|
|
|
with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server:
|
|
thread = start_server_thread(server)
|
|
try:
|
|
yield f"http://127.0.0.1:{server.server_address[1]}", state
|
|
finally:
|
|
server.shutdown()
|
|
thread.join()
|
|
|
|
|
|
def test_building_a_binding_contacts_no_server():
|
|
"""A binding is a local value: it says nothing about whether the Secret exists.
|
|
|
|
Existence is the server's answer at registration, where a mistyped name is a
|
|
clear error rather than a client-side check that was already stale.
|
|
"""
|
|
with _mock_remote_function_catalog() as (_host, state):
|
|
binding = EnvVarSecret(secret_name="openai-prod", env_variable="OPENAI_API_KEY")
|
|
assert binding.secret_name == "openai-prod"
|
|
assert binding.env_variable == "OPENAI_API_KEY"
|
|
|
|
assert state["requests"] == []
|
|
|
|
|
|
def test_vectorized_blob_function_executes_packaged_artifact_and_publishes(tmp_path):
|
|
@function(
|
|
input_schema=pa.schema([lancedb.blob("image", nullable=True)]),
|
|
output_schema=lancedb.blob("copy", nullable=False),
|
|
)
|
|
def copy_blobs(image: pa.Array) -> pa.Array:
|
|
assert isinstance(image, pa.LargeBinaryArray)
|
|
return pa.array(
|
|
[
|
|
b"missing" if value.as_py() is None else b"copy:" + value.as_py()
|
|
for value in image
|
|
],
|
|
type=pa.large_binary(),
|
|
)
|
|
|
|
registration = json.loads(copy_blobs.registration_request.to_canonical_json())
|
|
|
|
local = lancedb.connect(tmp_path)
|
|
source = local.create_table(
|
|
"blob_input",
|
|
schema=pa.schema(
|
|
[pa.field("id", pa.int64()), lancedb.blob("image", nullable=True)]
|
|
),
|
|
)
|
|
source.add(
|
|
pa.Table.from_arrays(
|
|
[
|
|
pa.array([0, 1, 2], type=pa.int64()),
|
|
pa.array([b"large blob", b"", None], type=pa.large_binary()),
|
|
],
|
|
names=["id", "image"],
|
|
)
|
|
)
|
|
input_hits = (
|
|
source.search()
|
|
.with_row_id(True)
|
|
.limit(3)
|
|
.to_arrow()
|
|
.sort_by([("id", "ascending")])
|
|
)
|
|
hydrated = source.fetch_blobs("image", input_hits)
|
|
assert isinstance(hydrated, pa.LargeBinaryArray)
|
|
result = _execute_registered_array_function_v1(
|
|
registration,
|
|
pa.RecordBatch.from_arrays([hydrated], names=["image"]),
|
|
)
|
|
assert result.to_pylist() == [b"copy:large blob", b"copy:", b"missing"]
|
|
|
|
published = local.create_table(
|
|
"blob_output",
|
|
schema=pa.schema(
|
|
[pa.field("id", pa.int64()), lancedb.blob("copy", nullable=False)]
|
|
),
|
|
)
|
|
published.add(
|
|
pa.Table.from_arrays(
|
|
[pa.array(range(len(result)), type=pa.int64()), result],
|
|
names=["id", "copy"],
|
|
)
|
|
)
|
|
output_hits = (
|
|
published.search()
|
|
.with_row_id(True)
|
|
.limit(3)
|
|
.to_arrow()
|
|
.sort_by([("id", "ascending")])
|
|
)
|
|
assert published.fetch_blobs("copy", output_hits).to_pylist() == [
|
|
b"copy:large blob",
|
|
b"copy:",
|
|
b"missing",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("declared_list", "physical_list", "array_type", "declared_name"),
|
|
[
|
|
(pa.list_, pa.list_, pa.ListArray, "list"),
|
|
(pa.large_list, pa.large_list, pa.LargeListArray, "large_list"),
|
|
],
|
|
ids=["list", "large_list"],
|
|
)
|
|
def test_blob_list_output_fresh_artifact_survives_local_reopen(
|
|
tmp_path, declared_list, physical_list, array_type, declared_name
|
|
):
|
|
input_type = physical_list(pa.int64())
|
|
item = lancedb.blob("item", nullable=True)
|
|
|
|
@function(
|
|
input_schema=pa.schema([pa.field("frames", input_type, nullable=False)]),
|
|
output_schema=pa.field("frames", declared_list(item), nullable=False),
|
|
)
|
|
def extract_frames(frames: pa.Array) -> pa.Array:
|
|
output_type = (
|
|
pa.large_list(pa.large_binary())
|
|
if isinstance(frames, pa.LargeListArray)
|
|
else pa.list_(pa.large_binary())
|
|
)
|
|
return pa.array([[b"abc", None, b""], []], type=output_type)
|
|
|
|
request = json.loads(extract_frames.registration_request.to_canonical_json())
|
|
declared = json.loads(request["signature"]["output"]["arrow_type"])
|
|
assert declared["type"] == declared_name
|
|
item_field = declared["fields"][0]
|
|
assert item_field["metadata"]["ARROW:extension:name"] == "lance.blob.v2"
|
|
|
|
result = _execute_registered_array_function_v1(
|
|
request,
|
|
pa.RecordBatch.from_arrays(
|
|
[pa.array([[0], [1]], type=input_type)],
|
|
names=["frames"],
|
|
),
|
|
)
|
|
assert isinstance(result, array_type)
|
|
assert result.type == physical_list(pa.large_binary())
|
|
assert result.offsets.to_pylist() == [0, 3, 3]
|
|
assert result.values.to_pylist() == [b"abc", None, b""]
|
|
assert result.to_pylist() == [[b"abc", None, b""], []]
|
|
|
|
db = lancedb.connect(tmp_path)
|
|
table = db.create_table(
|
|
"fresh_artifact_frames",
|
|
schema=pa.schema(
|
|
[
|
|
pa.field("id", pa.int64(), nullable=False),
|
|
pa.field("frames", declared_list(item), nullable=False),
|
|
]
|
|
),
|
|
)
|
|
table.add(
|
|
pa.Table.from_arrays(
|
|
[pa.array([1, 2], type=pa.int64()), result],
|
|
names=["id", "frames"],
|
|
)
|
|
)
|
|
|
|
reopened = lancedb.connect(tmp_path).open_table("fresh_artifact_frames")
|
|
reopened_item = reopened.schema.field("frames").type.value_field
|
|
assert reopened_item.type.extension_name == "lance.blob.v2"
|
|
assert reopened.blob_columns() == []
|
|
hits = reopened.search().limit(2).to_arrow().sort_by([("id", "ascending")])
|
|
lists = hits["frames"].combine_chunks()
|
|
assert isinstance(lists, array_type)
|
|
assert lists.offsets.to_pylist() == [0, 3, 3]
|
|
|
|
rows = lists.to_pylist()
|
|
assert rows[1] == []
|
|
assert [None if value is None else value["size"] for value in rows[0]] == [
|
|
3,
|
|
None,
|
|
0,
|
|
]
|
|
|
|
|
|
def test_a_function_namespace_path_must_be_a_list_of_segments():
|
|
"""A bare string is refused rather than read as a sequence of one-character
|
|
segments, and nothing reaches the service."""
|
|
with _mock_remote_function_catalog() as (host, state):
|
|
db = lancedb.connect(
|
|
"db://dev",
|
|
api_key="fake",
|
|
host_override=host,
|
|
client_config={"retry_config": {"retries": 0}},
|
|
)
|
|
with pytest.raises(TypeError):
|
|
list(db.list_functions(namespace_path="analytics"))
|
|
|
|
assert state["requests"] == []
|
|
|
|
|
|
def test_one_explicit_schema_infers_the_other_from_annotations():
|
|
@function(input_schema=pa.schema([pa.field("value", pa.int64())]))
|
|
def explicit_input(value) -> float:
|
|
return float(value or 0)
|
|
|
|
@function(output_schema=pa.field("result", pa.float32(), nullable=False))
|
|
def explicit_output(value: Optional[int]):
|
|
return float(value or 0)
|
|
|
|
for fn in (explicit_input, explicit_output):
|
|
signature = fn.registration_request.signature
|
|
assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [
|
|
("value", "int64", True)
|
|
]
|
|
assert explicit_input.registration_request.signature.output.arrow_type == "float64"
|
|
assert explicit_output.registration_request.signature.output.arrow_type == "float32"
|