Files
lancedb/python/python/tests/test_function_packaging.py
T
Jack Ye e61252f4dc feat(python): capture Arrow and structured Function globals (#5044)
Function source packaging inlined only scalar literals and tuples of
them. A module-level PyArrow type shared by `output_schema=` and the
Function body, a label map, or a small NumPy weight vector failed at
decoration with an "unsupported global value" error and had to be
redefined inside the body. These globals are now captured:

```python
import numpy as np
import pyarrow as pa
from lancedb import function

OUT_TYPE = pa.struct([pa.field("label", pa.string()), pa.field("score", pa.int32())])
LABELS = {"pick": 0, "place": 1}
WEIGHTS = np.array([0.25, 0.75])


@function(
    input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]),
    output_schema=pa.field("out", OUT_TYPE, nullable=False),
    pip=["numpy"],
)
def judge(x: pa.Array) -> pa.Array:
    score = int(WEIGHTS.sum() * 10)
    rows = [{"label": "pick", "score": LABELS["pick"] + score}] * len(x)
    return pa.array(rows, type=OUT_TYPE)
```

| Captured global | Rebuilt in the artifact as |
| --- | --- |
| `None`, `bool`, `int`, `str`, `bytes`, finite `float` | a literal
(unchanged) |
| tuple, list, dict, set, frozenset of supported values | a literal;
dicts keep insertion order, set elements are sorted by their source |
| PyArrow `DataType`, `Field`, `Schema` | `pa.ipc.read_schema` over the
value's IPC schema bytes, which keeps nullability, metadata, and nested
fields |
| NumPy array or scalar of a bool, integer, float16, float32, or float64
dtype | `np.array(<elements>, dtype=<dtype.str>)` or
`np.dtype(<dtype.str>).type(<item>)` |

- Each value is a copy taken when the decorator runs and rebuilt per
worker process, so values that share an object become separate copies.
Packaging does not depend on hash randomization.
- Each value is limited to 1 MiB of source and 32 levels of nesting.
Cycles and Python-defined Arrow extension types are rejected. The size
limit also applies to the existing literal captures.
- Unsupported values keep the error that names the global, its type, the
supported captures, and the remedy.
- `pyarrow` and `numpy` are imported under private aliases ahead of the
captured globals. The builtins used for empty sets and frozensets are
claimed, so a module that rebinds them fails packaging instead of
silently shadowing them.


Empty NumPy arrays are encoded directly from dtype and shape, so even
`(500_000, 0)` stays compact without expanding nested Python lists.
2026-11-17 00:10:59 -08:00

1513 lines
51 KiB
Python

# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Class Functions, initialization, and the source that travels with a Function."""
from __future__ import annotations
import base64
import importlib
import hashlib
import json
import os
import subprocess
import sys
import textwrap
import types
import warnings
from pathlib import Path
from typing import Annotated, Optional, get_type_hints
import numpy as np
import pyarrow as pa
import pytest
from lancedb import col
from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf
FIXTURES = (
Path(__file__).parents[3]
/ "rust"
/ "lancedb"
/ "tests"
/ "fixtures"
/ "first_class_functions"
/ "v1"
)
def artifact(definition) -> bytes:
return base64.b64decode(definition.registration_request.artifact.content.data)
def bundle_files(definition) -> dict[str, str]:
assert definition.registration_request.artifact.kind == "python_bundle"
return json.loads(artifact(definition))["files"]
@pytest.fixture
def helper_package(tmp_path, monkeypatch):
"""A local package on sys.path, the way a project's own helpers are."""
def write(name: str, files: dict[str, str]):
root = tmp_path / name
for path, source in files.items():
target = root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(textwrap.dedent(source))
monkeypatch.syspath_prepend(str(tmp_path))
for module in [
module for module in sys.modules if module.split(".")[0] == name
]:
del sys.modules[module]
importlib.invalidate_caches()
return importlib.import_module(name)
return write
@function
class scale:
def __init__(
self,
factor: float,
label: str,
offset: float = 0.0,
tags: Optional[list[str]] = None,
retry: Annotated[dict, pa.struct([("attempts", pa.int32())])] = None,
):
self.factor, self.offset = factor, offset
def __call__(self, value: float) -> float:
return value * self.factor + self.offset
class NoCall:
pass
class BadClose:
def __call__(self, value: int) -> int:
return value
def close(self, force):
pass
def test_class_function_declares_inputs_output_and_initialization():
signature = scale.registration_request.signature
assert [(p.name, p.arrow_type) for p in signature.inputs] == [("value", "float64")]
assert [
(field.name, field.arrow_type, field.nullable)
for field in signature.initialization
] == [
("factor", "float64", False),
("label", "utf8", False),
("offset", "float64", True),
("tags", "list<utf8>", True),
(
"retry",
'{"fields":[{"name":"attempts","nullable":true,"type":{"type":"int32"}}],'
'"type":"struct"}',
True,
),
]
# Calling the definition constructs the class, so local tests are ordinary.
assert scale(factor=2.0, label="x")(1.5) == 3.0
assert scale.registration_request.artifact.entrypoint == "scale"
source = artifact(scale).decode()
assert source.startswith("from __future__ import annotations\n")
assert "class scale:" in source and "@function" not in source
def test_function_without_initialization_keeps_its_wire_form():
@function
def double(value: int) -> int:
return value * 2
request = json.loads(double.registration_request.to_canonical_json())
assert "initialization" not in request["signature"]
assert request["artifact"]["kind"] == "python_callable"
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
@pytest.mark.parametrize("decorator", [function, udf])
@pytest.mark.parametrize("explicit_schemas", [False, True])
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize(
("declaration", "statement"),
[
("def", "yield value"),
("def", "yield from [value]"),
("async def", "yield value"),
],
)
def test_generator_functions_are_rejected_at_decoration(
helper_package, decorator, explicit_schemas, class_function, declaration, statement
):
signature = (
"__call__(self, value: int)" if class_function else "generates(value: int)"
)
source = f"{declaration} {signature} -> int:\n {statement}\n"
if class_function:
source = "class generates:\n" + textwrap.indent(source, " ")
module = helper_package("fx_generator", {"__init__.py": source})
options = (
{
"input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]),
"output_schema": pa.int64(),
}
if explicit_schemas
else {}
)
with pytest.raises(TypeError) as error:
decorator(**options)(module.generates)
message = str(error.value)
assert "generator Functions are not supported" in message
assert "return a value" in message
assert "return a list" in message
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
@pytest.mark.parametrize("decorator", [function, udf])
@pytest.mark.parametrize("explicit_name", [False, True])
def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name):
options = {"name": "double"} if explicit_name else {}
with pytest.raises(TypeError, match="lambda.*use a named def"):
decorator(**options)(lambda value: value * 2)
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"])
def test_cached_functions_explain_where_to_keep_caches(
helper_package, class_function, cache_decorator
):
signature = "__call__(self, value: int)" if class_function else "cached(value: int)"
source = (
f"@functools.{cache_decorator}\ndef {signature} -> int:\n return value * 2\n"
)
if class_function:
source = "class cached:\n" + textwrap.indent(source, " ")
module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source})
with pytest.raises(TypeError) as error:
function(module.cached)
message = str(error.value)
assert "decorated wrappers are not supported" in message
assert "inside the function body" in message
assert "class Function with a cache in __init__" in message
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("keyword_only", [False, True])
def test_callable_defaults_explain_class_initialization(
helper_package, class_function, keyword_only
):
parameters = "value: float, " + ("*, " if keyword_only else "")
parameters += "threshold: float = 0.5"
signature = (
f"__call__(self, {parameters})"
if class_function
else f"thresholded({parameters})"
)
source = f"def {signature} -> bool:\n return value >= threshold\n"
if class_function:
source = "class thresholded:\n" + textwrap.indent(source, " ")
module = helper_package("fx_defaults", {"__init__.py": source})
with pytest.raises(TypeError) as error:
function(module.thresholded)
message = str(error.value)
assert "defaults are not supported: 'threshold'" in message
assert "class Function's __init__" in message
assert "binding-time initialization values" in message
def test_function_can_return_a_list_from_a_generator_expression():
@function
def many(value: int) -> list[int]:
return list(item * 2 for item in range(value))
namespace = {}
exec(compile(artifact(many), "user_function.py", "exec"), namespace)
assert namespace["many"](3) == [0, 2, 4]
assert many.registration_request.signature.output.arrow_type == "list<int64>"
@pytest.mark.parametrize("kind", ["function", "class"])
@pytest.mark.parametrize(
("global_value", "value_type"),
[
("float('inf')", "float"),
("{'label': float('nan')}", "float"),
("[1, (2, object())]", "object"),
("{'labels': range(2)}", "range"),
("pa.array([1])", "Int64Array"),
("np.array(['label'])", "ndarray with dtype <U5"),
("np.array([1.0], dtype=np.longdouble)", "ndarray with dtype"),
("np.datetime64('2026-01-01')", "datetime64 with dtype datetime64[D]"),
("np.ma.masked_array([1.0])", "MaskedArray"),
],
)
def test_unsupported_global_names_value_and_remedy(
helper_package, kind, global_value, value_type
):
definition = (
"class uses_global:\n"
" def __call__(self, value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
if kind == "class"
else "def uses_global(value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
)
module = helper_package(
"fx_unsupported_global",
{
"__init__.py": "import numpy as np\nimport pyarrow as pa\n"
f"CAPTURED_VALUE = {global_value}\n" + definition
},
)
with pytest.raises(TypeError) as error:
function(module.uses_global)
message = str(error.value)
assert "CAPTURED_VALUE" in message
assert value_type in message
assert "finite float" in message
assert "inside the function or class body" in message
def test_supported_nested_literal_global_still_packages(helper_package):
module = helper_package(
"fx_literal_global",
{
"__init__.py": "CAPTURED_VALUE = (None, True, 1, 'label', "
"b'bytes', (1.5,))\n"
"def uses_global(value: int) -> int:\n"
" return value + CAPTURED_VALUE[2]\n"
},
)
definition = function(module.uses_global)
namespace = {}
exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
assert namespace["uses_global"](3) == 4
assert namespace["CAPTURED_VALUE"] == module.CAPTURED_VALUE
@pytest.mark.parametrize("kind", ["function", "class"])
def test_arrow_and_structured_globals_are_captured(helper_package, kind):
body = (
" if x is None:\n"
" return (LABELS, EMPTY, ARROW, WEIGHTS, NUMPY)\n"
" rows = [{'label': 'pick', 'score': LABELS['pick']}] * len(x)\n"
" return pa.array(rows, type=OUT_TYPE)\n"
)
definition = (
"class judge:\n def __call__(self, x: pa.Array) -> pa.Array:\n"
+ textwrap.indent(body, " ")
if kind == "class"
else "def judge(x: pa.Array) -> pa.Array:\n" + body
)
module = helper_package(
"fx_structured_global",
{
"__init__.py": textwrap.dedent("""
import numpy as np
import pyarrow as pa
OUT_TYPE = pa.struct(
[pa.field("label", pa.string()), pa.field("score", pa.int32())]
)
LABELS = {
"pick": 0,
"place": 1,
"nested": [None, (1.5, b"x"), {"deep": frozenset({"b", "a"})}],
}
EMPTY = ([], {}, set(), frozenset(), ())
ARROW = {
"field": pa.field(
"score", pa.int32(), nullable=False, metadata={"unit": "pts"}
),
"schema": pa.schema(
[pa.field("label", pa.dictionary(pa.int8(), pa.utf8(), True))],
metadata={"version": "1"},
),
"tensor": pa.fixed_shape_tensor(pa.float32(), [2, 2]),
}
WEIGHTS = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32)
NUMPY = (
np.float32(0.5),
np.True_,
np.uint64(2**64 - 1),
np.array(1.5),
np.zeros((0, 3), dtype=np.int16),
np.array([1.0, -0.0], dtype=">f8"),
)
""")
+ definition
},
)
out_type = module.OUT_TYPE
packaged = function(
input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]),
output_schema=pa.field("out", out_type, nullable=False),
)(module.judge)
source = artifact(packaged).decode()
assert "import numpy as _lancedb_numpy" in source
assert "import pyarrow as _lancedb_pyarrow" in source
namespace = {}
exec(compile(source, "user_function.py", "exec"), namespace)
call = namespace["judge"]() if kind == "class" else namespace["judge"]
result = call(pa.array([1, 2]))
assert result.type == out_type
assert result.to_pylist() == [{"label": "pick", "score": 0}] * 2
assert namespace["OUT_TYPE"] == out_type
assert namespace["LABELS"] == module.LABELS
assert list(namespace["LABELS"]) == list(module.LABELS)
assert namespace["EMPTY"] == module.EMPTY
assert [type(value) for value in namespace["EMPTY"]] == [
type(value) for value in module.EMPTY
]
for key, value in module.ARROW.items():
assert namespace["ARROW"][key].equals(value, check_metadata=True)
assert type(namespace["ARROW"][key]) is type(value)
weights = namespace["WEIGHTS"]
assert weights.dtype == module.WEIGHTS.dtype
assert np.array_equal(weights, module.WEIGHTS)
for captured, original in zip(namespace["NUMPY"], module.NUMPY, strict=True):
assert type(captured) is type(original)
assert captured.dtype == original.dtype
assert np.shape(captured) == np.shape(original)
assert np.array_equal(captured, original)
assert np.signbit(namespace["NUMPY"][-1][1])
@pytest.mark.parametrize("kind", ["function", "class"])
@pytest.mark.parametrize("shape", [(0,), (0, 3), (2, 0, 3), (500_000, 0)])
def test_empty_numpy_captures_preserve_shape_without_expanding(
helper_package, kind, shape
):
definition = (
"class empty_size:\n def __call__(self, value: int) -> int:\n"
" return value + EMPTY.size\n"
if kind == "class"
else "def empty_size(value: int) -> int:\n return value + EMPTY.size\n"
)
module = helper_package(
"fx_empty_numpy_global",
{
"__init__.py": "import numpy as np\n"
f"EMPTY = np.empty({shape!r}, dtype='>i2')\n" + definition
},
)
source = artifact(function(module.empty_size))
assert len(source) < 1024
namespace = {}
exec(compile(source, "user_function.py", "exec"), namespace)
captured = namespace["EMPTY"]
assert captured.shape == shape
assert captured.dtype == module.EMPTY.dtype
assert captured.size == 0
call = namespace["empty_size"]() if kind == "class" else namespace["empty_size"]
assert call(7) == 7
def test_captured_containers_are_copied_when_decorated(helper_package):
module = helper_package(
"fx_captured_copy",
{
"__init__.py": """
SHARED = [1, 2]
CONFIG = {"shared": SHARED, "again": SHARED}
def uses_config(value: int) -> int:
return value + len(CONFIG["shared"]) + len(SHARED)
"""
},
)
definition = function(module.uses_config)
module.SHARED.append(3)
namespace = {}
exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
assert namespace["SHARED"] == [1, 2]
assert namespace["CONFIG"] == {"shared": [1, 2], "again": [1, 2]}
assert namespace["CONFIG"]["shared"] is not namespace["CONFIG"]["again"]
assert namespace["CONFIG"]["shared"] is not namespace["SHARED"]
assert namespace["uses_config"](1) == 5
def test_captured_sets_package_deterministically(tmp_path):
script = tmp_path / "sets.py"
script.write_text(
textwrap.dedent(
"""
import json
from lancedb import function
WORDS = {f"word{index}" for index in range(20)}
MIXED = frozenset({("pair", 1), b"bytes", None, 2.5, "text"})
@function
def known(word: str) -> bool:
return word in WORDS or word in MIXED
print(json.dumps([
known.registration_request.artifact.digest,
list(WORDS),
]))
"""
)
)
runs = []
for seed in ("0", "1", "2", "3"):
result = subprocess.run(
[sys.executable, str(script)],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHASHSEED": seed},
)
assert result.returncode == 0, result.stderr
runs.append(json.loads(result.stdout))
# Hash randomization reorders the client's set; the artifact must not change.
assert len({tuple(order) for _, order in runs}) > 1
assert len({digest for digest, _ in runs}) == 1
@pytest.mark.parametrize(
("global_value", "message"),
[
("list(range(300_000))", "too large to capture"),
("np.zeros(2_000_000)", "too large to capture"),
("'x' * (1024 * 1024)", "too large to capture"),
("functools.reduce(lambda inner, _: [inner], range(40), [])", "32 levels"),
("_cycle()", "contains itself"),
("pa.schema([pa.field('x', pa.list_(_Extension()))])", "defined in Python"),
],
)
def test_captured_value_limits_name_the_global(helper_package, global_value, message):
module = helper_package(
"fx_captured_limits",
{
"__init__.py": textwrap.dedent("""
import functools
import numpy as np
import pyarrow as pa
class _Extension(pa.ExtensionType):
def __init__(self):
super().__init__(pa.int64(), "fx.extension")
def __arrow_ext_serialize__(self):
return b""
@classmethod
def __arrow_ext_deserialize__(cls, storage_type, serialized):
return cls()
def _cycle():
value = []
value.append(value)
return value
""")
+ f"CAPTURED_VALUE = {global_value}\n"
"def uses_global(value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
},
)
with pytest.raises((TypeError, ValueError)) as error:
function(module.uses_global)
assert "CAPTURED_VALUE" in str(error.value)
assert message in str(error.value)
assert "inside the function or class body" in str(error.value)
def test_captured_sets_keep_their_builtins(helper_package):
module = helper_package(
"fx_captured_builtins",
{
"__init__.py": """
STOP = frozenset({"a"})
frozenset = ("shadowed",)
def uses_sets(word: str) -> bool:
return word in STOP or word in frozenset
"""
},
)
with pytest.raises(ValueError, match="cannot package 'frozenset'"):
function(module.uses_sets)
@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"])
@pytest.mark.parametrize("kind", ["function", "class"])
def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package):
if kind == "class":
source = f"""
import pyarrow as pa
class identity:
def __call__(self, value: pa.{annotation}) -> pa.{annotation}:
return value
"""
else:
source = f"""
import pyarrow as pa
def identity(value: pa.{annotation}) -> pa.{annotation}:
return value
"""
module = helper_package("fx_batch_annotations", {"__init__.py": source})
with pytest.raises(TypeError, match="input_schema and output_schema"):
function(module.identity)
def test_array_batch_annotations_accept_explicit_schemas():
@function(
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
output_schema=pa.int64(),
)
def identity(value: pa.Array) -> pa.Array:
return value
signature = identity.registration_request.signature
assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [
("value", "int64", False)
]
assert signature.output.arrow_type == "int64"
assert signature.output.nullable is False
values = pa.array([1, 2, 3])
assert identity(values).equals(values)
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("postponed", [False, True])
@pytest.mark.parametrize(
("annotation", "nullable"),
[
("BlobReader", False),
("Reader", False),
('"Reader"', False),
("Reader | None", True),
("Optional[Reader]", True),
('Optional["Reader"]', True),
("MaybeReader", True),
("lancedb.BlobReader", False),
("lancedb.BlobReader | None", True),
],
)
def test_blob_reader_annotations_resolve_in_the_artifact(
helper_package, monkeypatch, class_function, postponed, annotation, nullable
):
definition = (
f"class read_blob:\n"
f" def __call__(self, video: {annotation}) -> int:\n"
f" return 0\n"
if class_function
else f"def read_blob(video: {annotation}) -> int:\n return 0\n"
)
module = helper_package(
"fx_blob_annotations",
{
"__init__.py": (
("from __future__ import annotations\n" if postponed else "")
+ "import lancedb\n"
"from typing import Optional\n"
"from lancedb import BlobReader, BlobReader as Reader\n"
"from lancedb.functions import function\n"
"MaybeReader = Optional[Reader]\n\n"
f"@function\n{definition}"
)
},
)
request = module.read_blob.registration_request
parameter = request.signature.inputs[0]
assert parameter.arrow_type == "blob_v2"
assert parameter.blob_access == "reader"
assert parameter.nullable is nullable
# Workers provide lance_blob rather than importing the client SDK's reader.
worker = types.ModuleType("lance_blob")
worker.BlobReader = type("BlobReader", (), {})
monkeypatch.setitem(sys.modules, "lance_blob", worker)
namespace = {}
exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace)
packaged = namespace["read_blob"]
if class_function:
packaged = packaged.__call__
assert get_type_hints(packaged) == {
"video": Optional[worker.BlobReader] if nullable else worker.BlobReader,
"return": int,
}
def test_blob_reader_annotation_does_not_shadow_body_globals(
helper_package, monkeypatch
):
module = helper_package(
"fx_blob_annotation_globals",
{
"__init__.py": """
from lancedb import BlobReader
from lancedb.functions import function
_lance_blob_reader = 7
@function
def read_blob(video: BlobReader) -> int:
return _lance_blob_reader
"""
},
)
worker = types.ModuleType("lance_blob")
worker.BlobReader = type("BlobReader", (), {})
monkeypatch.setitem(sys.modules, "lance_blob", worker)
namespace = {}
exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace)
packaged = namespace["read_blob"]
assert get_type_hints(packaged)["video"] is worker.BlobReader
assert packaged(worker.BlobReader()) == 7
@pytest.mark.parametrize(
("init", "message"),
[
("def __init__(self, blob: bytes): pass", "initialization takes booleans"),
("def __init__(self, *args: int): pass", "named and non-variadic"),
("def __init__(self, factor): pass", "missing Function initialization"),
("def __init__(self, value: int): pass", "share names \\['value'\\]"),
],
)
def test_class_function_rejects_unsupported_initialization(init, message):
namespace = {}
exec(
textwrap.dedent(
f"""
class bad:
{init}
def __call__(self, value: int) -> int:
return value
"""
),
namespace,
)
with pytest.raises((TypeError, ValueError), match=message):
function(namespace["bad"])
def test_class_function_requires_call_and_a_plain_close():
with pytest.raises(TypeError, match="synchronous __call__"):
function(NoCall)
with pytest.raises(TypeError, match="close must be a method taking no"):
function(BadClose)
def test_nested_class_and_closure_are_rejected_with_the_reason():
def build():
class nested:
def __call__(self, value: int) -> int:
return value
return nested
with pytest.raises(ValueError, match="defined at module level"):
function(build())
factor = 3
with pytest.raises(ValueError, match="capture closure values"):
@function
def closes_over(value: int) -> int:
return value * factor
@pytest.mark.parametrize(
"module_name",
[
"sys",
"builtins",
"importlib",
"inspect",
"gc",
"ctypes",
"types",
"ctypes.util",
"importlib.metadata",
],
)
@pytest.mark.parametrize("import_style", ["import", "from", "global"])
@pytest.mark.parametrize("class_function", [False, True])
def test_namespace_module_errors_explain_the_rule_and_remedy(
helper_package, module_name, import_style, class_function
):
statement = f"import {module_name} as namespace_module"
body = f"{statement}\nreturn value\n"
preamble = ""
if import_style == "from":
body = f"from {module_name} import __name__\nreturn value\n"
elif import_style == "global":
preamble = statement + "\n"
body = "return str(namespace_module)\n"
if class_function:
definition = "class blocked:\n def __call__(self, value: str) -> str:\n"
source = preamble + definition + textwrap.indent(body, " ")
else:
definition = "def blocked(value: str) -> str:\n"
source = preamble + definition + textwrap.indent(body, " ")
module = helper_package("fx_namespace_import", {"__init__.py": source})
with pytest.raises(ValueError) as error:
function(module.blocked)
message = str(error.value)
assert "imports from namespace-access modules" in message
assert repr(module_name) in message
assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message
assert "including submodules" in message
assert "reconstructed module namespace" in message
assert "importable helper module" in message
assert "code=, pip=, or conda=" in message
assert "dynamic namespace access" not in message
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
def test_udf_namespace_import_error_explains_the_helper_alternative():
with pytest.raises(ValueError, match="ctypes.util.*importable helper module"):
@udf
def probe(value: str) -> str:
import ctypes.util
return str(ctypes.util.find_library(value))
@pytest.mark.parametrize(
"operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"]
)
def test_dynamic_namespace_errors_name_the_operation_and_remedy(
helper_package, operation
):
module = helper_package(
"fx_namespace_operation",
{
"__init__.py": (
f"def blocked(value: str) -> str:\n return str({operation})\n"
)
},
)
with pytest.raises(ValueError) as error:
function(module.blocked)
message = str(error.value)
assert f"dynamic namespace access: ['{operation}']" in message
assert "Reference dependencies explicitly" in message
assert "importable helper module" in message
@pytest.mark.parametrize("ship_source", [False, True])
def test_namespace_access_in_importable_helpers_keeps_its_module_namespace(
helper_package, ship_source
):
helpers = helper_package(
"fx_namespace_helper",
{
"__init__.py": """
import ctypes.util
def module_name():
return ctypes.util.__name__
""",
},
)
entry = helper_package(
"fx_namespace_entry",
{
"__init__.py": """
from fx_namespace_helper import module_name
def probe(value: str) -> str:
return module_name() + value
""",
},
)
options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]}
definition = function(**options)(entry.probe)
if ship_source:
files = bundle_files(definition)
assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"]
source = files["user_function.py"]
else:
source = artifact(definition).decode()
namespace = {}
exec(compile(source, "user_function.py", "exec"), namespace)
assert namespace["probe"]("!") == "ctypes.util!"
def test_binding_passes_initialization_as_constants():
version = FunctionVersion.from_json(
json.dumps(
{
**json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
),
"signature": {
"inputs": [
{"name": "text", "arrow_type": "utf8", "nullable": True}
],
"output": {
"kind": "scalar",
"arrow_type": "list<float32>",
"nullable": False,
},
"initialization": [
{"name": "model", "arrow_type": "utf8", "nullable": False},
{"name": "dimensions", "arrow_type": "int32", "nullable": True},
],
},
}
)
)
application = version(text=col("body"), model="small", dimensions=(512))
assert dict(application.initialization) == {"model": "small", "dimensions": 512}
assert json.loads(application.to_canonical_json())["initialization"] == {
"dimensions": 512,
"model": "small",
}
assert version(text=col("body"), model="small").initialization == {"model": "small"}
with pytest.raises(TypeError, match=r"missing initialization: \['model'\]"):
version(text=col("body"))
with pytest.raises(TypeError, match="takes a constant"):
version(text=col("body"), model=col("model"))
with pytest.raises(ValueError, match="must be finite"):
version(text=col("body"), model="small", dimensions=float("nan"))
with pytest.raises(TypeError, match="takes booleans"):
version(text=col("body"), model=object())
def test_vendored_package_resources_survive_an_isolated_import(
tmp_path, helper_package
):
package = helper_package(
"fx_vendor",
{
"__init__.py": "from .vendor.model import predict",
"vendor/__init__.py": "",
"vendor/model.py": """
import hashlib
import json
from importlib.resources import files
def predict(value):
root = files("fx_vendor")
payload = root.joinpath("label-maps/payload.bin").read_bytes()
metadata = json.loads(root.joinpath("models.json").read_text())
source = root.joinpath("vendor/model.py").read_bytes()
source_digest = hashlib.sha256(source).hexdigest()
assert source_digest == metadata["source_sha256"]
assert hashlib.sha256(payload).hexdigest() == metadata["sha256"]
return value + metadata["offset"]
""",
"models.json": "{}",
},
)
payload = b"\x00\xff\r\nvendored model data"
package_root = Path(package.__file__).parent
(package_root / "label-maps").mkdir()
(package_root / "label-maps/payload.bin").write_bytes(payload)
module_path = package_root / "vendor/model.py"
module_bytes = (
module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
)
module_path.write_bytes(module_bytes)
(package_root / "models.json").write_bytes(
json.dumps(
{
"sha256": hashlib.sha256(payload).hexdigest(),
"source_sha256": hashlib.sha256(module_bytes).hexdigest(),
"offset": 7,
}
).encode()
+ b"\r\n"
)
entry = helper_package(
"fx_vendor_entry",
{
"__init__.py": """
import fx_vendor
from lancedb import function
@function(code=[fx_vendor])
def vendored(value: int) -> int:
return fx_vendor.predict(value)
"""
},
)
vendored = entry.vendored
first_digest = vendored.registration_request.artifact.digest
bundle = json.loads(artifact(vendored))
isolated = tmp_path / "isolated"
isolated.mkdir()
for name, content in bundle["files"].items():
target = isolated / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content.encode("utf-8"))
for name, content in bundle["resources"].items():
target = isolated / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(base64.b64decode(content))
assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n")
result = subprocess.run(
[
sys.executable,
"-I",
"-c",
"import sys; sys.path.insert(0, sys.argv[1]); "
"from user_function import vendored; assert vendored(3) == 10",
str(isolated),
],
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
(package_root / "models.json").write_text('{"offset": 8}')
assert (
function(code=[package])(
vendored._function
).registration_request.artifact.digest
!= first_digest
)
def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
tmp_path, helper_package
):
files = {
"__init__.py": "",
"rate.py": """
class TokenBucket:
def __init__(self, tokens_per_minute):
self.tokens_per_minute = tokens_per_minute
""",
"__pycache__/rate.cpython-312.pyc": "",
"fixtures/data.json": "{}",
"not-a-module.py": "",
}
helper_package("fx_helpers", files)
(tmp_path / "fx_helpers_functions.py").write_text(
textwrap.dedent(
"""
import fx_helpers
from fx_helpers.rate import TokenBucket
from lancedb import function
@function(code=[fx_helpers])
class limited:
def __init__(self, tpm: int):
self.limiter = TokenBucket(tpm)
def __call__(self, value: int) -> int:
return value
"""
)
)
def define():
sys.modules.pop("fx_helpers_functions", None)
importlib.invalidate_caches()
return importlib.import_module("fx_helpers_functions").limited
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
first = define()
assert len(caught) == 1
warning = str(caught[0].message)
assert "fx_helpers/fixtures/data.json" not in warning
assert "fx_helpers/not-a-module.py" in warning
assert "safe relative names" in warning
assert "importable Python module names" in warning
resources = json.loads(artifact(first))["resources"]
assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}"
assert "__pycache__" not in warning
assert ".pyc" not in warning
shipped = bundle_files(first)
assert sorted(shipped) == [
"fx_helpers/__init__.py",
"fx_helpers/rate.py",
"user_function.py",
]
assert (
"from fx_helpers.rate import TokenBucket as TokenBucket"
in (shipped["user_function.py"])
)
# Only the helper changes: a new artifact digest, the same environment.
helper_package(
"fx_helpers", {**files, "rate.py": textwrap.dedent(files["rate.py"]) + "# v2\n"}
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
second = define()
assert len(caught) == 1
assert (
first.registration_request.artifact.digest
!= second.registration_request.artifact.digest
)
assert first.registration_request.runtime == second.registration_request.runtime
def test_code_package_cache_artifacts_do_not_warn(helper_package):
cache = helper_package(
"fx_cache",
{
"__init__.py": "",
"__pycache__/ignored.cpython-312.pyc": "",
"stale.pyo": "",
},
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
@function(code=[cache])
def cache_only(value: int) -> int:
return value
assert not caught
assert sorted(bundle_files(cache_only)) == [
"fx_cache/__init__.py",
"user_function.py",
]
def test_code_package_resources_keep_nonidentifier_directories(helper_package):
resources = helper_package(
"fx_resources",
{
"__init__.py": "",
"label-maps/labels.json": "{}",
},
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
@function(code=[resources])
def resource_boundary(value: int) -> int:
return value
assert not caught
resources = json.loads(artifact(resource_boundary))["resources"]
assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}"
assert sorted(bundle_files(resource_boundary)) == [
"fx_resources/__init__.py",
"user_function.py",
]
def test_code_rejects_submodules_duplicates_and_non_modules(helper_package):
helpers = helper_package("fx_rejects", {"__init__.py": "", "sub.py": ""})
import fx_rejects.sub
for code, message in [
([fx_rejects.sub], "top-level modules"),
([helpers, helpers], "more than once"),
(["fx_rejects"], "imported modules"),
([json], "cannot ship module 'json'"),
]:
with pytest.raises((TypeError, ValueError), match=message):
@function(code=code)
def f(value: int) -> int:
return value
def test_local_module_outside_code_warns_at_registration(tmp_path, helper_package):
"""The worker most likely cannot import a local module that is neither
shipped nor declared, but registration still succeeds: a declared
distribution may install it under another name, and callers may rewrite
the packaged source before registering it."""
helper_package(
"fx_local", {"__init__.py": "def normalize(value):\n return value\n"}
)
def define(name, options):
(tmp_path / f"{name}.py").write_text(
textwrap.dedent(
f"""
from fx_local import normalize
from lancedb import function
@function({options})
def {name}(value: int) -> int:
return normalize(value)
"""
)
)
importlib.invalidate_caches()
return getattr(importlib.import_module(name), name)
with pytest.warns(UserWarning, match=r"local module.*code=\[fx_local\]"):
local = define("fx_uses_local", "")
assert "from fx_local import normalize" in artifact(local).decode()
# A declared package that provides the module is trusted to install it.
with warnings.catch_warnings():
warnings.simplefilter("error")
installed = define("fx_uses_installed", "pip=['fx-local==1.0']")
assert "from fx_local import normalize" in artifact(installed).decode()
def test_local_module_imported_in_function_body_warns_at_registration(
tmp_path, helper_package
):
"""A direct import inside the packaged definition is checked too."""
helper_package(
"fx_body_local",
{"__init__.py": "def normalize(value):\n return value\n"},
)
sys.modules.pop("fx_body_local", None)
def define(name, options):
(tmp_path / f"{name}.py").write_text(
textwrap.dedent(
f"""
from lancedb import function
@function({options})
def {name}(value: int) -> int:
import fx_body_local
return fx_body_local.normalize(value)
"""
)
)
importlib.invalidate_caches()
return getattr(importlib.import_module(name), name)
with pytest.warns(UserWarning, match=r"local module.*code=\[fx_body_local\]"):
local = define("fx_body_uses_local", "")
assert "import fx_body_local" in artifact(local).decode()
with warnings.catch_warnings():
warnings.simplefilter("error")
installed = define("fx_body_uses_installed", "pip=['fx-body-local==1.0']")
assert "import fx_body_local" in artifact(installed).decode()
def test_missing_module_without_declared_package_warns_at_registration(
tmp_path, monkeypatch
):
package = "fx_missing_remote_package_ent3448"
monkeypatch.syspath_prepend(str(tmp_path))
def define(name):
(tmp_path / f"{name}.py").write_text(
textwrap.dedent(
f"""
from lancedb import function
@function(pip=())
def {name}(value: int) -> int:
import {package}.plugin
return value
"""
)
)
importlib.invalidate_caches()
return getattr(importlib.import_module(name), name)
with pytest.warns(UserWarning) as caught:
definition = define("fx_uses_missing_package")
message = str(caught[0].message)
assert f"imports {package!r}" in message
assert "unavailable in the client environment" in message
assert "no declared pip/conda dependencies" in message
assert "Remote availability cannot be verified" in message
assert "confirm that the base image provides it" in message
assert "cannot import" not in message
assert f"import {package}.plugin" in artifact(definition).decode()
with warnings.catch_warnings():
warnings.simplefilter("error", UserWarning)
with pytest.raises(UserWarning, match="Remote availability cannot be verified"):
define("fx_missing_package_as_error")
def test_resolved_or_declared_module_imports_do_not_warn(tmp_path, helper_package):
package = "fx_missing_remote_package_ent3448"
helper_package("fx_declared_code_package", {"__init__.py": ""})
def define(name, body, options, imports=""):
(tmp_path / f"{name}.py").write_text(
textwrap.dedent(
f"""
{imports}
from lancedb import function
@function({options})
def {name}(value: int) -> int:
{body}
return value
"""
)
)
importlib.invalidate_caches()
return getattr(importlib.import_module(name), name)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
define("fx_imports_stdlib", "import os.path", "")
# Distribution names need not match the imported top-level module.
define(
"fx_imports_declared_pip",
f"import {package}.plugin",
"pip=['Pillow>=10']",
)
define(
"fx_imports_declared_conda",
f"import {package}.plugin",
"conda=['numpy']",
)
define(
"fx_imports_shipped_code",
"import fx_declared_code_package",
"code=[fx_declared_code_package]",
"import fx_declared_code_package",
)
assert not caught
MMLB_HELPERS = {
"__init__.py": "",
"rate.py": """
class TokenBucket:
constructed = 0
def __init__(self, tokens_per_minute):
TokenBucket.constructed += 1
self.tokens_per_minute = tokens_per_minute
self.acquired = 0
def acquire(self, tokens):
self.acquired += tokens
""",
"embedding.py": """
from fx_mmlb.rate import TokenBucket
class OpenAIEmbedder:
def __init__(self, model: str, tpm_limit: int, max_attempts: int = 6):
self.model = model
self.limiter = TokenBucket(tpm_limit)
self.max_attempts = max_attempts
def embed(self, texts):
self.limiter.acquire(sum(len(text) for text in texts))
return [[float(len(text))] for text in texts]
""",
}
MMLB_FUNCTIONS = """
import pyarrow as pa
import fx_mmlb
from fx_mmlb.embedding import OpenAIEmbedder
from lancedb import function
TEXT = pa.schema([pa.field("text", pa.string())])
EMBEDDING = pa.list_(pa.field("item", pa.float64(), nullable=False))
@function(code=[fx_mmlb], input_schema=TEXT, output_schema=EMBEDDING)
class openai_embedding_batch(OpenAIEmbedder):
def __call__(self, text: pa.Array) -> pa.Array:
item = pa.field("item", pa.float64(), nullable=False)
return pa.array(self.embed(text.to_pylist()), pa.list_(item))
@function(code=[fx_mmlb])
class openai_embedding(OpenAIEmbedder):
def __call__(self, text: str) -> list[float]:
return self.embed([text])[0]
"""
def test_shared_helpers_construct_state_on_every_path(tmp_path, helper_package):
"""The MMLB rate limiter, shared by a row and a batch Function: both are
initialized through the same helper, so neither path can skip it."""
helper_package("fx_mmlb", MMLB_HELPERS)
(tmp_path / "fx_mmlb_functions.py").write_text(MMLB_FUNCTIONS)
importlib.invalidate_caches()
functions = importlib.import_module("fx_mmlb_functions")
signatures = [
functions.openai_embedding_batch.registration_request.signature,
functions.openai_embedding.registration_request.signature,
]
for signature in signatures:
assert [field.name for field in signature.initialization] == [
"model",
"tpm_limit",
"max_attempts",
]
# Each bundle imports on its own, in a process that has never seen the
# client's modules, the way the worker's image code layer does.
for definition, call in [
(
functions.openai_embedding_batch,
"instance(pa.array(['ab', 'abc'])).to_pylist()",
),
(functions.openai_embedding, "[instance('ab'), instance('abc')]"),
]:
worker = tmp_path / definition.__name__
for path, source in bundle_files(definition).items():
(worker / path).parent.mkdir(parents=True, exist_ok=True)
(worker / path).write_text(source)
probe = textwrap.dedent(
f"""
import sys
sys.path.insert(0, {str(worker)!r})
import pyarrow as pa
import user_function
from fx_mmlb.rate import TokenBucket
cls = getattr(user_function, {definition.__name__!r})
instance = cls(model="small", tpm_limit=1000)
print(repr(({call}, TokenBucket.constructed, instance.limiter.acquired)))
"""
)
result = subprocess.run(
[sys.executable, "-I", "-c", probe],
capture_output=True,
text=True,
cwd=worker,
)
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "([[2.0], [3.0]], 1, 5)"
def test_main_definitions_travel_by_source(tmp_path):
"""Notebook cells and scripts define helpers in __main__, which a worker
cannot import; they are packaged by source, dependencies first."""
script = tmp_path / "notebook.py"
script.write_text(
textwrap.dedent(
"""
import json
import math
from dataclasses import dataclass
from lancedb import function
SCALE = 2
@dataclass
class Settings:
factor: int
def helper(value):
return math.floor(value) * SCALE
class Base:
def run(self, value):
return helper(value) * self.settings.factor
@function
class scaled(Base):
def __init__(self, factor: int):
self.settings = Settings(factor)
def __call__(self, value: float) -> int:
return self.run(value)
print(json.dumps(scaled.registration_request.to_canonical_json()))
"""
)
)
result = subprocess.run(
[sys.executable, str(script)], capture_output=True, text=True
)
assert result.returncode == 0, result.stderr
request = json.loads(json.loads(result.stdout))
assert request["artifact"]["kind"] == "python_callable"
source = base64.b64decode(request["artifact"]["content"]["data"]).decode()
assert source.index("def helper") < source.index("class Base")
assert source.index("class Base") < source.index("class scaled")
assert source.index("class Settings") < source.index("class scaled")
assert "@dataclass" in source
assert "SCALE = 2" in source
namespace = {}
exec(compile(source, "user_function.py", "exec"), namespace)
assert namespace["scaled"](factor=3)(2.7) == 12
def test_main_lambdas_are_rejected(tmp_path):
script = tmp_path / "lambda.py"
script.write_text(
textwrap.dedent(
"""
from lancedb import function
double = lambda value: value * 2
@function
def uses_lambda(value: int) -> int:
return double(value)
"""
)
)
result = subprocess.run(
[sys.executable, str(script)], capture_output=True, text=True
)
assert result.returncode != 0
assert "not lambdas, closures, or nested definitions" in result.stderr
def test_udf_alias_warns_and_packages_like_function(helper_package):
def source(decorator: str) -> str:
return f"""
import lancedb
from lancedb import function, udf
@{decorator}
def double(value: int) -> int:
return value * 2
"""
current = helper_package("fx_alias_current", {"__init__.py": source("function")})
expected = current.double.registration_request.artifact.digest
for name, decorator in (("fx_alias_bare", "udf"), ("fx_alias_attr", "lancedb.udf")):
with pytest.warns(DeprecationWarning, match="lancedb.udf is deprecated"):
module = helper_package(name, {"__init__.py": source(decorator)})
assert isinstance(module.double, FunctionDefinition)
assert "udf" not in artifact(module.double).decode()
assert module.double.registration_request.artifact.digest == expected
def test_udf_definition_alias_warns():
with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"):
from lancedb import UdfDefinition
assert UdfDefinition is FunctionDefinition
with pytest.warns(DeprecationWarning, match="UdfDefinition is deprecated"):
from lancedb.functions import UdfDefinition as module_alias
assert module_alias is FunctionDefinition