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
+30 -5
View File
@@ -517,11 +517,36 @@ def probe_library(name: str) -> str:
return native_diagnostics.find_library(name)
```
Captured literal globals support `None`, booleans, integers, strings, bytes,
finite floats, and tuples of these values. Construct other objects, including
PyArrow types and schemas, inside the Function or helper module instead. Values
used only in the decorator's `input_schema` or `output_schema` are not captured
globals and can be defined outside the Function.
Captured globals are copied into the Function's source. They can be `None`,
booleans, integers, strings, bytes, and finite floats; 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. The copy is taken when the decorator runs and rebuilt in
each worker process, so later changes on either side are not shared. NumPy
values need `numpy` in the remote environment; declare it with `pip=` or
`conda=`. Each value is limited to 1 MiB of source and 32 levels of nesting;
load larger data inside the Function, for example from a table or a package
resource shipped with `code=`. Construct other objects inside the Function or
helper module instead. Values used only in the decorator's `input_schema` or
`output_schema` are not captured globals and can be defined outside the
Function.
```python
import pyarrow as pa
from lancedb import function
LABELS = {"pick": 0, "place": 1}
RESULT = pa.struct([pa.field("label", pa.string()), pa.field("id", pa.int32())])
@function(
input_schema=pa.schema([pa.field("action", pa.string(), nullable=False)]),
output_schema=pa.field("result", RESULT, nullable=False),
)
def label(action: pa.Array) -> pa.Array:
rows = [{"label": name, "id": LABELS[name]} for name in action.to_pylist()]
return pa.array(rows, type=RESULT)
```
Annotate a blob input with `lancedb.BlobReader` for lazy, seekable access, or
with `bytes` to materialize its contents before the Function runs. Reader