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.
This commit is contained in:
Jack Ye
2026-11-17 00:10:59 -08:00
committed by GitHub
parent ff9dc7a2be
commit e61252f4dc
3 changed files with 502 additions and 37 deletions
+210 -27
View File
@@ -1859,24 +1859,42 @@ def _is_function_decorator(node: ast.expr) -> bool:
)
def _literal_source(value: Any, name: str) -> str:
if value is None or type(value) in (bool, int, str, bytes):
return repr(value)
if type(value) is float and math.isfinite(value):
return repr(value)
if type(value) is tuple:
children = ", ".join(_literal_source(child, name) for child in value)
if len(value) == 1:
children += ","
return f"({children})"
raise TypeError(
# A captured value is inlined into the artifact source; larger data belongs in a
# table or a package resource.
_MAX_CAPTURED_SOURCE = 1024 * 1024
# Far below CPython's parser nesting limit.
_MAX_CAPTURED_DEPTH = 32
_CAPTURE_REMEDY = "Define this value inside the function or class body instead."
def _unsupported_capture(name: str, kind: str) -> TypeError:
return TypeError(
"Function source references an unsupported global value of type "
f"{type(value).__name__} in {name!r}. Only None, bool, int, str, bytes, "
"finite float, and tuples of these literals can be captured. "
"Define this value inside the function or class body instead."
f"{kind} in {name!r}. Captured globals can be None, bool, int, str, "
"bytes, or finite float values; tuples, lists, dicts, sets, or frozensets "
"of supported values; PyArrow data types, fields, or schemas; or NumPy "
"arrays or scalars of bool, integer, float16, float32, or float64 dtypes. "
+ _CAPTURE_REMEDY
)
def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType]:
"""The first extension type within `data_type` whose class is defined in
Python. IPC carries only its name, so it deserializes as the storage type
wherever that class is not registered."""
if isinstance(data_type, pa.ExtensionType):
return data_type
if isinstance(data_type, pa.BaseExtensionType):
return _python_extension_type(data_type.storage_type)
if isinstance(data_type, pa.DictionaryType):
return _python_extension_type(data_type.value_type)
for index in range(data_type.num_fields):
found = _python_extension_type(data_type.field(index).type)
if found is not None:
return found
return None
_DYNAMIC_NAMESPACE_ACCESS = frozenset(
{"globals", "locals", "vars", "eval", "exec", "compile", "__import__"}
)
@@ -2175,7 +2193,7 @@ class _SourcePackager:
The module holds the definition plus exactly the module-level names it
references: modules as imports, importable classes and functions as
imports, literals inline, and functions and classes defined in
imports, captured values inline, and functions and classes defined in
``__main__`` by source, recursively, dependencies first.
"""
@@ -2183,6 +2201,7 @@ class _SourcePackager:
self._code_modules = code_modules
self._requirements = requirements
self._imports: dict[str, str] = {}
self._support_imports: dict[str, str] = {}
self._definitions: list[str] = []
self._packaged: set[int] = set()
self._names: dict[str, Any] = {}
@@ -2191,8 +2210,13 @@ class _SourcePackager:
def package(self, target: Any, signature: FunctionSignature) -> str:
entry = self._definition(target, entry=True, signature=signature)
parts = [_SOURCE_HEADER]
if self._imports:
parts.extend(["", *(self._imports[name] for name in sorted(self._imports))])
# Captured values are rebuilt with the support modules, so those come first.
imports = [
*(self._support_imports[alias] for alias in sorted(self._support_imports)),
*(self._imports[name] for name in sorted(self._imports)),
]
if imports:
parts.extend(["", *imports])
for definition in self._definitions:
parts.extend(["", definition])
parts.extend(["", entry, ""])
@@ -2313,8 +2337,8 @@ class _SourcePackager:
def _global_source(self, name: str, value: Any) -> str:
"""One module-level line that rebinds `name` to `value` in the artifact:
an import for modules and importable classes/functions, a literal
otherwise."""
an import for modules and importable classes/functions, a captured
copy otherwise."""
if value is BlobReader:
return f"from lance_blob import BlobReader as {name}"
if isinstance(value, types.ModuleType):
@@ -2347,7 +2371,149 @@ class _SourcePackager:
if imported is value:
self._require_importable(module_name)
return f"from {module_name} import {qualname} as {name}"
return f"{name} = {_literal_source(value, name)}"
return f"{name} = {self._captured_source(name, value)}"
def _captured_source(self, name: str, value: Any) -> str:
"""An expression that rebuilds a copy of the global `name`.
Literals and containers are written as Python literals, with set
elements sorted by their source so the artifact does not depend on hash
randomization. Arrow values are rebuilt from Arrow's IPC schema encoding
and NumPy values from their dtype and elements.
"""
remaining = _MAX_CAPTURED_SOURCE
enclosing: set[int] = set()
def too_large() -> ValueError:
return ValueError(
f"Function global {name!r} is too large to capture: its source "
f"exceeds {_MAX_CAPTURED_SOURCE} characters. Load large data inside "
"the function or class body instead, for example from a table or a "
"package resource shipped with code=."
)
def charge(source: str, nested: Sequence[str] = ()) -> str:
nonlocal remaining
remaining -= len(source) - sum(map(len, nested))
if remaining < 0:
raise too_large()
return source
def emit(value: Any) -> str:
if value is None or type(value) in (bool, int, str, bytes):
return charge(repr(value))
if type(value) is float and math.isfinite(value):
return charge(repr(value))
if isinstance(value, (pa.DataType, pa.Field, pa.Schema)):
return charge(self._arrow_source(name, value))
numpy = sys.modules.get("numpy")
if numpy is not None and (
type(value) is numpy.ndarray or isinstance(value, numpy.generic)
):
return emit_numpy(numpy, value)
if type(value) in (tuple, list, dict, set, frozenset):
return emit_container(value)
raise _unsupported_capture(name, type(value).__name__)
def emit_numpy(numpy: types.ModuleType, value: Any) -> str:
# These convert to exact Python values; longdouble stays a NumPy scalar.
if value.dtype.kind not in "biuf" or value.dtype.type is numpy.longdouble:
raise _unsupported_capture(
name, f"{type(value).__name__} with dtype {value.dtype}"
)
# Every element takes at least one character; check before tolist().
if value.size > remaining:
raise too_large()
alias = self._support_module("numpy")
dtype = repr(value.dtype.str)
if isinstance(value, numpy.generic):
item = emit(value.item())
return charge(f"{alias}.dtype({dtype}).type({item})", (item,))
if value.size == 0:
return charge(
f"{alias}.array([], dtype={dtype}).reshape({value.shape!r})"
)
elements = emit(value.tolist())
source = f"{alias}.array({elements}, dtype={dtype})"
return charge(source, (elements,))
def emit_container(value: Any) -> str:
if id(value) in enclosing:
raise ValueError(
f"Function global {name!r} contains itself and cannot be "
"captured. " + _CAPTURE_REMEDY
)
if len(enclosing) == _MAX_CAPTURED_DEPTH:
raise ValueError(
f"Function global {name!r} nests containers more than "
f"{_MAX_CAPTURED_DEPTH} levels deep and cannot be captured. "
+ _CAPTURE_REMEDY
)
enclosing.add(id(value))
if type(value) is dict:
entries = [(emit(key), emit(child)) for key, child in value.items()]
children = [part for entry in entries for part in entry]
listed = ", ".join(f"{key}: {child}" for key, child in entries)
source = f"{{{listed}}}"
else:
children = [emit(child) for child in value]
if type(value) in (set, frozenset):
listed = ", ".join(sorted(children))
else:
listed = ", ".join(children)
if type(value) is tuple:
source = f"({listed},)" if len(children) == 1 else f"({listed})"
elif type(value) is list:
source = f"[{listed}]"
elif type(value) is set:
source = (
f"{{{listed}}}" if children else f"{self._builtin('set')}()"
)
else:
items = f"{{{listed}}}" if children else ""
source = f"{self._builtin('frozenset')}({items})"
enclosing.remove(id(value))
return charge(source, children)
return emit(value)
def _arrow_source(
self, name: str, value: Union[pa.DataType, pa.Field, pa.Schema]
) -> str:
if isinstance(value, pa.Schema):
schema, suffix = value, ""
elif isinstance(value, pa.Field):
schema, suffix = pa.schema([value]), ".field(0)"
else:
schema, suffix = pa.schema([pa.field("", value)]), ".field(0).type"
for data_type in schema.types:
extension = _python_extension_type(data_type)
if extension is not None:
raise TypeError(
f"Function global {name!r} uses the Arrow extension type "
f"{extension.extension_name!r}, which is defined in Python and "
"cannot be captured. " + _CAPTURE_REMEDY
)
alias = self._support_module("pyarrow")
# Schema IPC keeps nullability, metadata, and nested fields exactly.
data = schema.serialize().to_pybytes()
return f"{alias}.ipc.read_schema({alias}.py_buffer({data!r})){suffix}"
def _support_module(self, module: str) -> str:
"""The artifact's private alias for a module that rebuilds captured
values."""
alias = f"_lancedb_{module}"
if alias not in self._support_imports:
self._require_importable(module)
self._claim(alias, ("support", module))
self._support_imports[alias] = f"import {module} as {alias}"
return alias
def _builtin(self, name: str) -> str:
"""A builtin called by captured source, which the artifact must not
rebind."""
self._claim(name, ("builtin", name))
return name
def _require_importable(self, module_name: str) -> None:
"""Warn about an import the Function's environment may not be able to
@@ -3015,8 +3181,11 @@ def function(
- modules, and classes and functions importable from an installed
package, become imports; the package must be declared in ``pip`` or
``conda``;
- literals (``None``, ``bool``, ``int``, ``str``, ``bytes``, finite
``float``, and tuples containing only these literals) are inlined;
- values are copied into the source: ``None``, ``bool``, ``int``,
``str``, ``bytes``, and finite ``float``; tuples, lists, dicts, sets,
and frozensets of supported values; PyArrow data types, fields, and
schemas; and NumPy arrays and scalars of ``bool``, integer,
``float16``, ``float32``, and ``float64`` dtypes;
- functions and classes defined in ``__main__``, such as notebook cells,
are packaged by source, together with what they reference;
- modules and packages listed in ``code`` are shipped as Python source and
@@ -3034,13 +3203,27 @@ def function(
image. Warnings follow normal Python warning filters and may be promoted
to errors. Declare every third-party import in ``pip`` or ``conda`` even
when it happens to be installed on the registration host.
Other global values, including Arrow types and schemas, lists, dictionaries,
sets, and NumPy arrays, cannot be captured as literals. Define them inside
the function or class body instead.
Closures, lambdas, nested definitions, mutable module-level objects, and a
non-standard ``__builtins__`` are rejected where they can be seen and
Closures, lambdas, nested definitions, other mutable module-level objects,
and a non-standard ``__builtins__`` are rejected where they can be seen and
otherwise unsupported.
**Captured values.** A captured value is copied when the decorator runs
and rebuilt in every worker process. Later changes on the client do not
reach the Function, changes a worker makes stay in that process, and
globals that share an object on the client become separate copies.
Dictionaries keep their insertion order and set elements are written in a
canonical order, so the same values always package to the same source.
Floats, including NumPy elements, must be finite. Arrow values are rebuilt
from Arrow's IPC schema encoding, which preserves nullability, metadata,
and nested fields; extension types defined in Python cannot be captured.
NumPy values keep their dtype and shape and need ``numpy`` in the remote
environment, so declare it in ``pip`` or ``conda``. Each captured value is
limited to 1 MiB of source and 32 levels of nesting, and cannot contain
itself. Load larger data inside the function or class body, for example
from a table or a package resource shipped with ``code``. Define other
values, such as instances of your own classes, inside the function or
class body as well.
**Namespace restrictions.** The packaged source cannot import ``sys``,
``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``,
including submodules such as ``ctypes.util`` and ``importlib.metadata``.
+262 -5
View File
@@ -9,6 +9,7 @@ import base64
import importlib
import hashlib
import json
import os
import subprocess
import sys
import textwrap
@@ -17,6 +18,7 @@ import warnings
from pathlib import Path
from typing import Annotated, Optional, get_type_hints
import numpy as np
import pyarrow as pa
import pytest
@@ -234,10 +236,15 @@ def test_function_can_return_a_list_from_a_generator_expression():
@pytest.mark.parametrize(
("global_value", "value_type"),
[
("pa.struct([('label', pa.string())])", "StructType"),
("(1, (pa.int64(),))", "DataType"),
("{'label': 1}", "dict"),
("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(
@@ -254,8 +261,8 @@ def test_unsupported_global_names_value_and_remedy(
module = helper_package(
"fx_unsupported_global",
{
"__init__.py": f"import pyarrow as pa\nCAPTURED_VALUE = {global_value}\n"
+ definition
"__init__.py": "import numpy as np\nimport pyarrow as pa\n"
f"CAPTURED_VALUE = {global_value}\n" + definition
},
)
with pytest.raises(TypeError) as error:
@@ -284,6 +291,256 @@ def test_supported_nested_literal_global_still_packages(helper_package):
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):