fix(python): reject Expr inputs on unregistered Function definitions (#5125)

`FunctionDefinition.__call__` ran the decorated Python callable with any
value it was given, so `my_function(value=col("value"))` executed user
code against an `Expr` or silently returned one, with errors such as
`float() argument must be a string or a real number, not 'Expr'`. A
column reference is not a local value: it binds only on a registered
`FunctionVersion`.

An unregistered definition now rejects `Expr` positional and keyword
arguments with `TypeError` before the callable runs, and names the
supported path: `create_function`/`create_function_async`, then
`col(...)` on the returned version. Plain Python and Arrow arguments,
and the class `__init__`/`__call__` lifecycle, are unchanged.

The Function authoring guide's batch example did not register either: a
`pyarrow.Array` annotation carries no element types, so `score_batch`
raised `TypeError` for missing `input_schema` and `output_schema`, and
the page claimed one `pa.RecordBatch` parameter could read several
columns. The example now passes both schemas, shows one `pa.Array`
parameter per input column for multi-column functions, and states that
`input_schema` matches parameters one to one, so a `RecordBatch`
parameter binds one input column. The GPU class example on the same page
had the same missing-schema defect and is fixed too.

Compatibility: code that passed `col(...)` to an unregistered definition
now gets `TypeError` instead of running user code against an `Expr`.
That call was never a supported binding and produced no usable result;
no supported call changes.
This commit is contained in:
Xuanwo
2026-11-20 20:34:49 +08:00
committed by GitHub
parent 3c9851966c
commit 56638a9e71
4 changed files with 103 additions and 7 deletions
+26 -2
View File
@@ -3182,6 +3182,12 @@ class FunctionDefinition:
remote application or build the declared remote runtime, and it does not
need the private implementation attribute.
Arguments to this call are Python and Arrow values. An
[Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column
binding that only a registered
[FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this
call rejects it with ``TypeError`` instead of running the callable.
Remote execution adapts the callable to the internal Arrow batch ABI
described by the registration artifact. By default it invokes the callable
once per row. A callable whose parameters are all annotated as
@@ -3451,6 +3457,16 @@ class FunctionDefinition:
return self._request._copy(update={"secret_bindings": resolved})
def __call__(self, *args, **kwargs):
from lancedb.expr import Expr
if any(isinstance(value, Expr) for value in (*args, *kwargs.values())):
raise TypeError(
"a FunctionDefinition runs locally on Python and Arrow values; "
"an Expr input binds only on a registered FunctionVersion. "
"Register the definition with create_function or "
"create_function_async, then bind col(...) on the returned "
"version."
)
return self._function(*args, **kwargs)
@@ -3541,7 +3557,12 @@ def function(
it takes one ``pyarrow.RecordBatch``. These batch annotations require both
``input_schema`` and ``output_schema`` explicitly: the annotations do not
specify Arrow element types or fields. This also applies to a class's
``__call__`` method. A decorated class is the same callable with state:
``__call__`` method. Each ``input_schema`` field names one parameter, so
several input columns take one ``pyarrow.Array`` parameter each, while a
single ``pyarrow.RecordBatch`` parameter binds one input column and
receives it as a batch. The
[Function authoring guide](https://lancedb.com/docs/curation/create-function#batch)
has the worked examples. A decorated class is the same callable with state:
each remote instance calls ``__init__`` once, calls
``__call__`` for every row or batch of every input it processes, and calls
``close()``, if defined, once when it retires. Load models, open clients,
@@ -3803,7 +3824,10 @@ def function(
remote environment, resolve Secrets, or run the remote Arrow adapter or
sandbox. A registered ``FunctionVersion`` call is different: it binds
``col(...)`` inputs and returns a remote
[FunctionApplication][lancedb.functions.FunctionApplication].
[FunctionApplication][lancedb.functions.FunctionApplication]. Passing an
[Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the
callable runs, because a column reference binds only on a registered
version.
```python
scaled = scale(factor=2.0)
@@ -20,6 +20,7 @@ from typing import Annotated, Optional, get_type_hints
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pytest
from lancedb import col
@@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas():
assert identity(values).equals(values)
def test_batch_functions_take_one_array_parameter_per_input_column():
@function(
input_schema=pa.schema(
[
pa.field("value", pa.float64(), nullable=False),
pa.field("weight", pa.float64(), nullable=False),
]
),
output_schema=pa.float64(),
)
def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array:
return pc.multiply(value, weight)
signature = weighted_score.registration_request.signature
assert [parameter.name for parameter in signature.inputs] == ["value", "weight"]
result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0]))
assert result.to_pylist() == [3.0, 8.0]
@pytest.mark.parametrize(
"invoke",
[
lambda definition: definition(col("value")),
lambda definition: definition(value=col("value")),
lambda definition: definition(value=col("value") * 2),
],
ids=["positional", "keyword", "derived"],
)
def test_definition_calls_reject_expr_inputs_before_user_code(invoke):
@function
def double(value: float) -> float:
raise AssertionError("user code ran")
with pytest.raises(TypeError, match="registered FunctionVersion"):
invoke(double)
def test_class_definition_binds_initialization_only_on_a_version():
with pytest.raises(TypeError, match="registered FunctionVersion"):
scale(factor=col("factor"), label="x")
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("postponed", [False, True])
@pytest.mark.parametrize(