Merge main updates into gatekeeper/fix-4911-1

This commit is contained in:
Gatefixer
2026-11-14 13:32:49 +00:00
46 changed files with 3716 additions and 202 deletions
+5 -1
View File
@@ -117,7 +117,7 @@ class PyExpr:
def expr_col(name: str) -> PyExpr: ...
def expr_lit(
value: Union[bool, int, float, str, bytes, date, datetime, Decimal],
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
) -> PyExpr: ...
def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ...
@@ -663,6 +663,8 @@ class Table:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
supervisor_resources: Optional[dict[str, int]] = None,
planning_workers: Optional[dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -683,6 +685,8 @@ class Table:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
supervisor_resources: Optional[dict[str, int]] = None,
planning_workers: Optional[dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
+18 -5
View File
@@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func
__all__ = ["Expr", "col", "lit", "func"]
_NOT_LITERAL = object()
_STR_TO_PA_TYPE: dict = {
"bool": pa.bool_(),
"boolean": pa.bool_(),
@@ -92,9 +94,16 @@ class Expr:
# for dict keys / set membership.
__hash__ = None # type: ignore[assignment]
def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None:
def __init__(
self,
inner: PyExpr,
*,
column_path: str | None = None,
literal_value: object = _NOT_LITERAL,
) -> None:
self._inner = inner
self._column_path = column_path
self._literal_value = literal_value
def __bool__(self) -> bool:
# An Expr describes a predicate that the query engine evaluates per row,
@@ -301,14 +310,16 @@ def col(name: str) -> Expr:
return Expr(expr_col(name), column_path=name)
def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr:
def lit(
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
) -> Expr:
"""Create a literal (constant) value expression.
Parameters
----------
value:
A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``,
``datetime``, or ``Decimal``.
``datetime``, ``Decimal``, or ``None`` for SQL NULL.
Examples
--------
@@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) ->
>>> col("price") * lit(1.1)
Expr((price * 1.1))
"""
if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)):
if value is not None and not isinstance(
value, (bool, int, float, str, bytes, date, datetime, Decimal)
):
raise TypeError(f"Unsupported literal type: {type(value).__name__}")
return Expr(expr_lit(value))
return Expr(expr_lit(value), literal_value=value)
def func(name: str, *args: ExprLike) -> Expr:
+77 -26
View File
@@ -158,11 +158,15 @@ def _validate_literal(value):
"Function integer literal is outside the canonical JSON range"
)
elif isinstance(value, Mapping):
if not all(isinstance(key, str) for key in value):
raise TypeError("Function literal object keys must be strings")
for child in value.values():
_validate_literal(child)
elif isinstance(value, (list, tuple)):
for child in value:
_validate_literal(child)
elif value is not None and not isinstance(value, (bool, str)):
raise TypeError(f"unsupported Function literal type: {type(value).__name__}")
return value
@@ -193,7 +197,7 @@ class _RemoteValue(BaseModel):
known = {}
for name, field in self.__class__.model_fields.items():
value = getattr(self, name)
if value is None:
if value is None and not field.is_required():
continue
if not field.is_required():
default_factory = field.default_factory
@@ -312,7 +316,11 @@ class FunctionResultField(_OpenRemoteValue):
class FunctionOutput(_OpenRemoteValue):
"""Scalar or ordered named-struct output; unknown kinds remain decodable."""
"""Scalar or ordered named-struct output; unknown kinds remain decodable.
A scalar output may be nullable. A named-struct output has no top-level
nullability; its fields carry their own flags.
"""
kind: str
arrow_type: Optional[str] = None
@@ -622,10 +630,17 @@ class FunctionVersion(_RemoteValue):
return _validate_row_timeout(value)
def __call__(self, **arguments: Any) -> FunctionApplication:
"""Bind this exact version to named table columns.
"""Bind this exact version to named table columns and constant inputs.
Every input must be a direct [lancedb.col][lancedb.expr.col]
reference. A Function that declares initialization fields takes their
reference or [lancedb.lit][lancedb.expr.lit] constant. Constants support
integers, strings, booleans, and null; floating-point, binary and
temporal literals are not in the canonical Function input contract.
The Enterprise service must support literal bindings and validates
constants against this exact version's input signature. To change a
constant, redeclare the column using the same Function version.
A Function that declares initialization fields takes their
values as further keyword arguments; they are constants of this
binding, fixed for every row, and every instance the binding runs is
created with them. A non-nullable field without a default must be
@@ -654,7 +669,7 @@ class FunctionVersion(_RemoteValue):
... "embedding": embed(text=col("body"), model="small", dimensions=512)
... })
"""
from lancedb.expr import Expr
from lancedb.expr import Expr, _NOT_LITERAL
parameters = tuple(parameter.name for parameter in self.signature.inputs)
fields = {field.name: field for field in self.signature.initialization}
@@ -678,17 +693,27 @@ class FunctionVersion(_RemoteValue):
bindings = []
for parameter in parameters:
value = arguments[parameter]
if not isinstance(value, Expr) or value._column_path is None:
if isinstance(value, Expr) and value._literal_value is not _NOT_LITERAL:
bindings.append(
ApplicationInput(
parameter=parameter,
kind="literal",
value=value._literal_value,
)
)
elif isinstance(value, Expr) and value._column_path is not None:
bindings.append(
ApplicationInput(
parameter=parameter,
kind="column",
value={"path": value._column_path},
)
)
else:
raise TypeError(
f"Function input {parameter!r} must be a direct col(...) reference"
f"Function input {parameter!r} must be a direct col(...) reference "
"or lit(...) constant"
)
bindings.append(
ApplicationInput(
parameter=parameter,
kind="column",
value={"path": value._column_path},
)
)
initialization = {}
for name in fields:
if name in arguments:
@@ -872,6 +897,18 @@ class InputBinding(_RemoteValue):
nullable: bool
class LiteralInputBinding(_RemoteValue):
"""Constant supplied to a Function parameter for every input row."""
parameter: str
value: Any
@field_validator("value")
@classmethod
def _validate_value(cls, value):
return _validate_literal(value)
class OutputMapping(_RemoteValue):
"""One stable result-field mapping."""
@@ -896,6 +933,7 @@ class FunctionBinding(_RemoteValue):
binding_id: str
function: FunctionVersionRef
inputs: tuple[InputBinding, ...]
literal_inputs: tuple[LiteralInputBinding, ...] = ()
outputs: tuple[OutputMapping, ...]
assignment: Optional[AssignmentMapping] = None
input_schema: Optional[Mapping[str, Any]] = None
@@ -903,6 +941,13 @@ class FunctionBinding(_RemoteValue):
initialization: Optional[str] = None
"""Standard base64 of the validated one-row Arrow IPC initialization stream."""
@model_validator(mode="after")
def _validate_input_parameters(self):
parameters = [input.parameter for input in (*self.inputs, *self.literal_inputs)]
if len(parameters) != len(set(parameters)):
raise ValueError("Function binding input parameters must be unique")
return self
def initialization_row(self) -> Optional[dict[str, Any]]:
"""The initialization values this binding creates instances with."""
if self.initialization is None:
@@ -1399,12 +1444,12 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp
"output_schema must be a PyArrow DataType, Field, or Schema"
)
_validate_exact_arrow_field(field)
if field.nullable:
raise ValueError("Function output must be non-nullable")
if field.nullable and _is_blob_v2_field(field):
raise ValueError("Blob v2 Function output must be non-nullable")
return FunctionOutput(
kind="scalar",
arrow_type=_canonical_arrow_field(field, collection_blobs=True),
nullable=False,
nullable=field.nullable,
)
if not fields:
@@ -1504,9 +1549,9 @@ def _infer_signature(
output = _function_output(output_schema)
else:
output_type, output_nullable = _annotation_type(annotations["return"])
if output_nullable:
raise ValueError("Function output must be non-nullable")
output = _function_output(pa.field("result", output_type, nullable=False))
output = _function_output(
pa.field("result", output_type, nullable=output_nullable)
)
if inputs is not None:
return FunctionSignature(inputs=inputs, output=output)
@@ -2650,9 +2695,13 @@ def function(
``None`` for a null value. PyArrow fields are nullable unless declared
otherwise, so most columns need ``Optional``. For Arrow types annotations
cannot express precisely, pass ``input_schema``, ``output_schema``, or
both; the one omitted is inferred. Scalar outputs must be non-nullable.
Every named-struct field may be nullable; Enterprise preserves the
struct's validity when the result is expanded into sibling columns.
both; the one omitted is inferred. A scalar output is non-nullable by
default; annotate the return as ``Optional[T]`` or ``T | None``, or pass a
nullable ``output_schema`` field, to declare a nullable scalar. The
deployment must accept nullable scalar outputs; an older server rejects
the registration. Every named-struct field may be nullable; Enterprise
preserves the struct's validity when the result is expanded into sibling
columns.
**Large values.** A ``bytes`` parameter receives the whole value, which
is held in memory with its row and counts against the server's per-row
@@ -2757,9 +2806,10 @@ def function(
Required for batch annotations. When omitted, inputs are inferred from
the parameter annotations.
output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional
Explicit scalar or named-struct output. Scalar outputs must be
non-nullable. Required for batch annotations. When omitted, the output
is inferred from the return annotation.
Explicit scalar or named-struct output. A scalar field's ``nullable``
flag is preserved; a top-level named-struct field and a Blob v2 output
must be non-nullable. Required for batch annotations. When omitted, the
output is inferred from the return annotation.
pip : sequence of str, optional
Pip requirements for the remote environment. Syntax is validated at
decoration time, including extras and environment markers. Named direct
@@ -2970,6 +3020,7 @@ __all__ = [
"FunctionVersionRef",
"HuggingFaceModel",
"InputBinding",
"LiteralInputBinding",
"OutputMapping",
"PythonEnvironmentSpec",
"PythonAdapterSpec",
+8
View File
@@ -1164,6 +1164,8 @@ class RemoteTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1183,6 +1185,8 @@ class RemoteTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1205,6 +1209,8 @@ class RemoteTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1225,6 +1231,8 @@ class RemoteTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
+64
View File
@@ -3258,6 +3258,8 @@ class Table(ABC):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3315,6 +3317,17 @@ class Table(ABC):
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -3367,6 +3380,8 @@ class Table(ABC):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3423,6 +3438,17 @@ class Table(ABC):
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -5632,6 +5658,8 @@ class LanceTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5654,6 +5682,8 @@ class LanceTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5676,6 +5706,8 @@ class LanceTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5700,6 +5732,8 @@ class LanceTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -8109,6 +8143,8 @@ class AsyncTable:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8166,6 +8202,17 @@ class AsyncTable:
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -8213,6 +8260,8 @@ class AsyncTable:
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8351,6 +8400,8 @@ class AsyncTable:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8407,6 +8458,17 @@ class AsyncTable:
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -8471,6 +8533,8 @@ class AsyncTable:
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8,7 +8,7 @@ from types import MappingProxyType
import pytest
from lancedb import col
from lancedb import col, lit
import lancedb.functions as functions
from lancedb.functions import (
FunctionApplication,
@@ -58,6 +58,7 @@ def assert_no_secret_values(value):
def test_public_function_values_are_in_api_reference():
assert "LiteralInputBinding" in functions.__all__
docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md"
rendered = docs.read_text()
for name in functions.__all__:
@@ -286,6 +287,67 @@ def test_function_version_binding_validates_names_and_direct_columns():
version(text=col("text").lower())
@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1])
def test_function_version_binds_direct_literals_without_changing_identity(constant):
value = job_result("remote_function_job.json")
value["signature"]["inputs"].append(
{
"name": "option",
"arrow_type": "bool"
if type(constant) is bool
else "utf8"
if isinstance(constant, str)
else "uint64"
if constant == 2**64 - 1
else "int64",
"nullable": True,
}
)
version = FunctionVersion.from_json(json.dumps(value))
expression = lit(constant)
application = version(text=col("body"), option=expression)
encoded = json.loads(application.to_canonical_json())
assert encoded["inputs"] == [
{"parameter": "text", "kind": "column", "value": {"path": "body"}},
{"parameter": "option", "kind": "literal", "value": constant},
]
assert application.function.version == version.version
assert application.function.object_id == version.object_id
assert application.function.manifest_digest == version.image.manifest_digest
assert FunctionApplication.from_json(application.to_canonical_json()) == application
if constant is None:
assert expression.to_sql() == "NULL"
if type(constant) is int:
assert expression.to_sql() == str(constant)
def test_function_literals_reject_expressions_and_unsupported_values():
version = FunctionVersion.from_json(
json.dumps(job_result("remote_function_job.json"))
)
with pytest.raises(TypeError, match="direct col"):
version(text=lit(16) + lit(8))
with pytest.raises(ValueError, match="floating-point Function literals"):
version(text=lit(1.5))
with pytest.raises(TypeError, match="unsupported Function literal type"):
version(text=lit(b"data"))
def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters():
value = json.loads((FIXTURES / "remote_function_binding.json").read_text())
value["inputs"] = value["inputs"][:1]
value["literal_inputs"] = [{"parameter": "body", "value": None}]
binding = FunctionBinding.from_json(json.dumps(value))
assert binding.literal_inputs[0].value is None
assert json.loads(binding.to_canonical_json())["literal_inputs"] == [
{"parameter": "body", "value": None}
]
assert FunctionBinding.from_json(binding.to_canonical_json()) == binding
value["literal_inputs"][0]["parameter"] = "title"
with pytest.raises(ValueError, match="input parameters must be unique"):
FunctionBinding.from_json(json.dumps(value))
def test_function_version_keeps_named_struct_outputs_in_one_application():
value = job_result("remote_function_job.json")
value["name"] = "text_features"
@@ -28,6 +28,7 @@ import lancedb
from lancedb import BlobReader
from lancedb.db import AsyncConnection
from lancedb.functions import (
FunctionSignature,
FunctionVersion,
HuggingFaceModel,
PythonRuntimeSpec,
@@ -1214,6 +1215,42 @@ def test_explicit_arrow_schema_is_deterministic():
assert signature.output.nullable is False
def test_nullable_scalar_output_annotation_and_explicit_schema():
input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
@function(input_schema=input_schema)
def optional_annotation(value: int) -> Optional[int]:
return None if value == 0 else value * 2
@function(input_schema=input_schema)
def optional_union(value: int) -> int | None:
return None if value == 0 else value * 2
@function(
input_schema=input_schema,
output_schema=pa.field("result", pa.int64(), nullable=True),
)
def explicit_schema(value: int):
return None if value == 0 else value * 2
for definition in (optional_annotation, optional_union, explicit_schema):
signature = definition.registration_request.signature
assert (signature.output.kind, signature.output.arrow_type) == (
"scalar",
"int64",
)
assert signature.output.nullable is True
assert json.loads(signature.to_canonical_json())["output"] == {
"kind": "scalar",
"arrow_type": "int64",
"nullable": True,
}
assert (
FunctionSignature.from_json(signature.to_canonical_json()).output.nullable
is True
)
def test_blob_fields_use_the_scalar_function_semantic_type():
@function(
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
@@ -1848,12 +1885,6 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
def unsupported(value: set[str]) -> str:
return ""
with pytest.raises(ValueError, match="output must be non-nullable"):
@function
def nullable_output(value: int) -> Optional[int]:
return value
with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"):
@function(input_schema=pa.schema([pa.field("value", pa.int64())]))
@@ -1873,10 +1904,25 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
@function(
input_schema=pa.schema([pa.field("value", pa.int64())]),
output_schema=pa.field("result", pa.int64(), nullable=True),
output_schema=pa.field(
"result",
pa.struct([pa.field("value", pa.int64(), nullable=False)]),
nullable=True,
),
)
def nullable_explicit(value):
return value
def nullable_struct(value):
return {"value": value}
with pytest.raises(
ValueError, match="Blob v2 Function output must be non-nullable"
):
@function(
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
output_schema=lancedb.blob("result", nullable=True),
)
def nullable_blob(image):
return image
for invalid_field in [
pa.field("", pa.int32(), nullable=False),
+128
View File
@@ -2076,6 +2076,23 @@ def test_remote_create_index_async_returns_job():
"gpu_count": 2,
}
},
{
"supervisor_resources": {
"cpu_millis": 2000,
"memory_bytes": 4 * 1024**3,
"ephemeral_storage_bytes": 10 * 1024**3,
},
"planning_workers": {
"resources": {
"cpu_millis": 1000,
"memory_bytes": 2 * 1024**3,
"ephemeral_storage_bytes": 5 * 1024**3,
},
"max_workers": 4,
"rows_per_worker": 100_000,
"fragments_per_worker": 8,
},
},
{"gpu_class": "a10g", "gpu_count": 2},
{
"retry_policy": {"transient": True, "max_attempts": 3},
@@ -2122,6 +2139,9 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
**budget,
"gpu_count": budget.get("gpu_count", 0),
}
for key in ("supervisor_resources", "planning_workers"):
if refresh_kwargs.get(key) is not None:
expected[key] = refresh_kwargs[key]
if refresh_kwargs.get("retry_policy") is not None:
expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate(
refresh_kwargs["retry_policy"]
@@ -2350,6 +2370,51 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
},
"unsupported key 'unknown'",
),
(
{
"supervisor_resources": {
"cpu_millis": 0,
"memory_bytes": 1,
"ephemeral_storage_bytes": 1,
}
},
"supervisor_resources.cpu_millis",
),
(
{
"supervisor_resources": {
"cpu_millis": 1,
"memory_bytes": 1,
}
},
"supervisor_resources.ephemeral_storage_bytes",
),
(
{
"supervisor_resources": {
"cpu_millis": 1,
"memory_bytes": 1,
"ephemeral_storage_bytes": 1,
"unknown": 1,
}
},
"unsupported key 'unknown'",
),
(
{
"planning_workers": {
"resources": {
"cpu_millis": 1,
"memory_bytes": 1,
"ephemeral_storage_bytes": 1,
},
"max_workers": 0,
"rows_per_worker": 1,
"fragments_per_worker": 1,
}
},
"planning_workers.max_workers",
),
(
{"max_executor_processes_per_worker": -2},
"max_executor_processes_per_worker",
@@ -2991,6 +3056,69 @@ def test_remote_job_wait_raises_on_failure():
assert exc_info.value.sql_job_id is None
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [True, False])
@pytest.mark.parametrize("with_terminal_server", [True, False])
async def test_remote_job_wait_preserves_terminal_build(sync, with_terminal_server):
from lancedb.exceptions import JobFailedError
message = "ValueError: corrupt frame at frame_index=207"
server = {
"release": "1.13.0-beta.0",
"git_sha": "2a7874ecd589",
"build_date": "2026-11-12T22:45:43Z",
}
result = {"terminal_server": server} if with_terminal_server else None
def handler(request):
assert request.path == "/v1/jobs/describe"
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.send_header(
"x-lancedb-server-build",
json.dumps({"release": "2.0.0", "git_sha": "new-query-node"}),
)
request.end_headers()
request.wfile.write(
json.dumps(
{
"job_id": "job-provenance",
"job_state": "FAILED",
"failure": {
"phase": "function_refresh_attempt_failed",
"message": message,
"traceback": "Traceback: original user code",
"retryable": False,
},
"result": result,
}
).encode()
)
if sync:
with mock_lancedb_connection(handler) as db:
job = db.open_job("job-provenance")
with pytest.raises(JobFailedError) as caught:
job.wait()
else:
async with mock_lancedb_connection_async(handler) as db:
job = await db.open_job("job-provenance")
with pytest.raises(JobFailedError) as caught:
await job.wait()
expected = f"Job job-provenance failed: {message}"
if with_terminal_server:
expected += (
" [server: 1.13.0-beta.0 (git 2a7874ecd589, built 2026-11-12T22:45:43Z)]"
)
expected += " (in function_refresh_attempt_failed)"
assert str(caught.value) == expected
assert caught.value.job_id == "job-provenance"
assert job.failure.message == message
assert job.failure.traceback == "Traceback: original user code"
assert job.result == result
@pytest.mark.parametrize("server_version", ["0.2.0", "0.6.0"])
def test_remote_json_fts_config(server_version):
from lancedb.index import FTS
+25
View File
@@ -6013,6 +6013,31 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
"resource_budget",
),
(
{
"supervisor_resources": {
"cpu_millis": 1000,
"memory_bytes": 1024,
"ephemeral_storage_bytes": 2048,
}
},
"supervisor_resources",
),
(
{
"planning_workers": {
"resources": {
"cpu_millis": 1000,
"memory_bytes": 1024,
"ephemeral_storage_bytes": 2048,
},
"max_workers": 2,
"rows_per_worker": 100,
"fragments_per_worker": 1,
}
},
"planning_workers",
),
({"num_workers": 2}, "num_workers"),
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
],
+7 -1
View File
@@ -164,9 +164,12 @@ pub fn expr_col(name: &str) -> PyExpr {
/// Create a literal value expression.
///
/// Supported Python types: `bool`, `int`, `float`, `str`, `bytes`, `date`,
/// `datetime`, `Decimal`.
/// `datetime`, `Decimal`, and `None` (SQL NULL).
#[pyfunction]
pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult<PyExpr> {
if value.is_none() {
return Ok(PyExpr(df_lit(ScalarValue::Null)));
}
// bool must be checked before int because bool is a subclass of int in Python
if let Ok(b) = value.extract::<bool>() {
return Ok(PyExpr(df_lit(b)));
@@ -174,6 +177,9 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult<PyExpr> {
if let Ok(i) = value.extract::<i64>() {
return Ok(PyExpr(df_lit(i)));
}
if let Ok(i) = value.extract::<u64>() {
return Ok(PyExpr(df_lit(i)));
}
// Decimal must be checked before f64: Python's Decimal implements __float__,
// so value.extract::<f64>() would succeed and silently truncate the value to
// f64, losing precision. Build a Decimal128 scalar to preserve it instead.
+114 -4
View File
@@ -30,8 +30,9 @@ use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode,
NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig,
FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform,
Ref, RefreshColumnOptions, Table as LanceDbTable,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
@@ -52,6 +53,8 @@ struct RefreshColumnArgs {
max_concurrency: Option<u32>,
publication_interval_rows: Option<i64>,
resource_budget: Option<FunctionWorkerResourceBudget>,
supervisor_resources: Option<FunctionRefreshPodResources>,
planning_workers: Option<FunctionRefreshPlanningConfig>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -159,6 +162,101 @@ fn parse_resource_budget(
))
}
fn structured_integer(value: &Bound<'_, PyAny>, name: &str) -> PyResult<u64> {
if value.is_none() || value.is_instance_of::<PyBool>() {
return Err(PyValueError::new_err(format!("{name} must be an integer")));
}
let parsed = value
.extract::<u64>()
.map_err(|_| PyValueError::new_err(format!("{name} must be an integer")))?;
if parsed == 0 {
return Err(PyValueError::new_err(format!(
"{name} must be greater than zero"
)));
}
Ok(parsed)
}
fn parse_pod_resources(
resources: &Bound<'_, PyDict>,
prefix: &str,
) -> PyResult<FunctionRefreshPodResources> {
for key in resources.keys() {
let key = key
.extract::<String>()
.map_err(|_| PyValueError::new_err(format!("{prefix} keys must be strings")))?;
if !matches!(
key.as_str(),
"cpu_millis" | "memory_bytes" | "ephemeral_storage_bytes"
) {
return Err(PyValueError::new_err(format!(
"{prefix} contains unsupported key '{key}'"
)));
}
}
let get = |name: &str| -> PyResult<u64> {
let value = resources
.get_item(name)?
.ok_or_else(|| PyValueError::new_err(format!("{prefix}.{name} is required")))?;
structured_integer(&value, &format!("{prefix}.{name}"))
};
Ok(FunctionRefreshPodResources::new(
get("cpu_millis")?,
get("memory_bytes")?,
get("ephemeral_storage_bytes")?,
))
}
fn parse_supervisor_resources(
resources: Option<&Bound<'_, PyDict>>,
) -> PyResult<Option<FunctionRefreshPodResources>> {
resources
.map(|resources| parse_pod_resources(resources, "supervisor_resources"))
.transpose()
}
fn parse_planning_workers(
planning: Option<&Bound<'_, PyDict>>,
) -> PyResult<Option<FunctionRefreshPlanningConfig>> {
let Some(planning) = planning else {
return Ok(None);
};
for key in planning.keys() {
let key = key
.extract::<String>()
.map_err(|_| PyValueError::new_err("planning_workers keys must be strings"))?;
if !matches!(
key.as_str(),
"resources" | "max_workers" | "rows_per_worker" | "fragments_per_worker"
) {
return Err(PyValueError::new_err(format!(
"planning_workers contains unsupported key '{key}'"
)));
}
}
let resources = planning
.get_item("resources")?
.ok_or_else(|| PyValueError::new_err("planning_workers.resources is required"))?;
let resources = resources
.cast::<PyDict>()
.map_err(|_| PyValueError::new_err("planning_workers.resources must be a dict"))?;
let resources = parse_pod_resources(resources, "planning_workers.resources")?;
let get = |name: &str| -> PyResult<u64> {
let value = planning
.get_item(name)?
.ok_or_else(|| PyValueError::new_err(format!("planning_workers.{name} is required")))?;
structured_integer(&value, &format!("planning_workers.{name}"))
};
let max_workers = usize::try_from(get("max_workers")?)
.map_err(|_| PyValueError::new_err("planning_workers.max_workers is too large"))?;
Ok(Some(FunctionRefreshPlanningConfig::new(
resources,
max_workers,
get("rows_per_worker")?,
get("fragments_per_worker")?,
)))
}
fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOptions> {
let RefreshColumnArgs {
where_clause,
@@ -166,6 +264,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
max_concurrency,
publication_interval_rows,
resource_budget,
supervisor_resources,
planning_workers,
gpu_class,
gpu_count,
retry_policy,
@@ -211,6 +311,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
options.publication_interval_rows =
positive_count(publication_interval_rows, "publication_interval_rows")?;
options.resource_budget = resource_budget;
options.supervisor_resources = supervisor_resources;
options.planning_workers = planning_workers;
options.gpu_class = gpu_class;
options.gpu_count = gpu_count
.map(|count| {
@@ -2492,7 +2594,7 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column<'py>(
self_: PyRef<'py, Self>,
@@ -2502,6 +2604,8 @@ impl Table {
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
supervisor_resources: Option<Bound<'py, PyDict>>,
planning_workers: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2519,6 +2623,8 @@ impl Table {
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?,
planning_workers: parse_planning_workers(planning_workers.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
@@ -2540,7 +2646,7 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column_async<'py>(
self_: PyRef<'py, Self>,
@@ -2550,6 +2656,8 @@ impl Table {
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
supervisor_resources: Option<Bound<'py, PyDict>>,
planning_workers: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2567,6 +2675,8 @@ impl Table {
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?,
planning_workers: parse_planning_workers(planning_workers.as_ref())?,
gpu_class,
gpu_count,
retry_policy,