diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 122a73019..dfd2752b8 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -449,7 +449,9 @@ and then call the returned instance; call `close()` if the class defines it. Thi path uses the current Python environment and does not create a registered `FunctionVersion`, build the declared remote runtime, resolve Secrets, or execute the remote Arrow adapter. A registered `FunctionVersion` call instead binds -`col(...)` inputs and returns a remote `FunctionApplication`. +`col(...)` inputs and returns a remote `FunctionApplication`. Passing an `Expr` +such as `col("value")` to a definition raises `TypeError` before the callable +runs; bind it on the registered `FunctionVersion` instead. ```python from lancedb import function diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 0342849b4..109846bea 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -98,10 +98,12 @@ is not a substitute for `lancedb.blob`. ## Batch: once per call, many rows at a time {#batch} -A function is called once per batch instead of once per row when its -parameters are annotated `pyarrow.Array`, or when it takes a single -`pyarrow.RecordBatch` parameter to read more than one column together. The -same doubling logic, vectorized over a whole batch at once: +A function is called once per batch instead of once per row when all of its +parameters are annotated `pyarrow.Array`. Those annotations say that a whole +column arrives in one call, but not which Arrow type the column holds, so a +batch function also passes `input_schema` and `output_schema`; every field of +`input_schema` matches a parameter by name and by order. The same doubling +logic, vectorized over a whole batch at once: ```python Python icon="python" @@ -111,6 +113,8 @@ from lancedb import function @function( pip=["numpy==2.2.0"], + input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]), + output_schema=pa.float64(), batch_size=32, max_concurrency=4, row_timeout_seconds=90, @@ -120,6 +124,27 @@ def score_batch(value: pa.Array) -> pa.Array: ``` +Read several columns in one call by taking one `pa.Array` parameter per +column, with one schema field for each: + +```python +@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) +``` + +A single `pyarrow.RecordBatch` parameter is also a batch function, but it does +not read several columns at once: `input_schema` declares one field per +parameter, so a `RecordBatch` parameter binds one input column and receives +that column as a batch. A schema with more fields than the callable has +parameters is rejected at decoration. + Batching amortizes per-call overhead across many rows, which matters most once a function also does something with real fixed cost per call -- loading a model, opening a connection, making a network round trip. @@ -185,6 +210,8 @@ gpu_class = next( gpu=True, gpu_class=gpu_class, pip=["torch==2.12.0", "sentence-transformers==5.7.0"], + input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]), + output_schema=pa.list_(pa.float32(), 384), ) class embed_text: def __init__(self, model_name: str = "all-MiniLM-L6-v2"): diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2d369e3ec..43226fdf3 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -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) diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 874dd809f..8d2d282a9 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -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(