feat(python)!: declare streaming Blob outputs for Functions (#5171)

BREAKING CHANGE: Rust callers constructing
`lancedb::function::FunctionOutput` with a struct literal now supply
`blob_writer_paths`. Use `Vec::new()` for an output without
writer-capable fields.

LanceDB Functions that generate large Blob v2 values can declare their
output with `BlobWriter` and write chunks during a computed column
refresh in a compatible LanceDB Enterprise environment. Row-wise and
vectorized callables use the same logical Blob schema. Named and nested
outputs can mark specific leaves with `BlobWriter.field` while retaining
ordinary binary siblings and nullable fields.

The SDK preserves writer requirements through native registration and
computed column binding. A distinct output kind lets earlier Enterprise
versions reject registrations that require a writer. Existing bytes-only
registrations retain their wire format and adapter.

On SDK commit
[`a19e7b87`](https://github.com/lancedb/lancedb/commit/a19e7b873c36aec865f092a368760be8846233ed),
a rebuilt extension preserved nested writer paths through Flight SQL
registration and version readback. Enterprise 1.14.1 rejected the writer
registration before building the Function image. With the compatible
runtime candidate, a real Flight SQL refresh published a 2 GiB + 137
byte value in each Blob layout against Moto. Independent reads verified
length and SHA-256 before and after cleanup of an older version. The run
also confirmed multipart abort and cumulative descriptor accounting.
[Runtime
evidence](https://linear.app/lancedb/issue/ENT-4209#comment-26e69e0e-faad-4aac-b148-3f4591181182)
· [Descriptor
accounting](https://linear.app/lancedb/issue/ENT-4209#comment-4d05e27a-8ff2-4003-804a-8af2f29ce2f4)

This SDK change is part of the coordinated Enterprise delivery.
[ENT-4209](https://linear.app/lancedb/issue/ENT-4209)
This commit is contained in:
Xuanwo
2026-11-24 13:53:06 +08:00
committed by GitHub
parent f183fe14c3
commit a6cca1efb0
9 changed files with 763 additions and 111 deletions
+2
View File
@@ -676,6 +676,8 @@ with BlobReader(read_range, len(payload)) as reader:
::: lancedb.BlobReader
::: lancedb.functions.BlobWriter
::: lancedb.functions.FunctionArtifact
::: lancedb.functions.FunctionParameter
+32 -18
View File
@@ -294,11 +294,10 @@ evaluation, and how that differs from rotating or revoking it later.
## Read and produce blobs {#blobs}
A Function can bind a [Blob v2 column](/management/table#managed-blobs) and
return another blob, including a blob nested inside a struct field, not only
at the top level. In row mode, a top-level blob parameter arrives as Python
`bytes`, or `None` for a nullable input, after the worker has read the
payload. Return bytes and let the destination table store the Managed
payload and descriptor.
return a Blob v2 value at the top level or inside a struct. In row mode, a
top-level blob parameter arrives as Python `bytes`, or `None` for a nullable
input, after the worker reads the payload. Use `BlobReader` to read it
incrementally.
This section extracts a frame from a stored video and captions it,
continuing as one example across chaining, persisting and incremental reads
@@ -322,10 +321,32 @@ frames = db.create_table("frames", [
### Produce a blob {#produce-blobs}
Declare blob inputs and outputs explicitly. `extract_frame` reads one frame
out of a video at a timestamp and returns it as a JPEG, without loading the
whole clip first -- see [Read a blob incrementally](#incremental) below for
how the `video: BlobReader` parameter does that:
{/*
Draft for the streaming Blob output release.
Use `BlobWriter` during computed column refresh to produce a Blob v2 value in
chunks. Register the Function with a Python SDK that exposes `BlobWriter`
after upgrading the LanceDB Enterprise server and Function worker images to
versions that support streaming Blob output. Keep returning `bytes` with an
explicit Blob v2 output schema on deployments without writer support.
Import `BlobWriter` from `lancedb.functions`. In a scalar Function,
`-> BlobWriter` infers a non-nullable Blob v2 output. For a vectorized
Function, provide `input_schema` and annotate the return as
`list[BlobWriter]` or `tuple[BlobWriter, ...]` to infer one Blob v2 result per
row. Return the writers in input row order. Use `BlobWriter.field(...)` in
an explicit output schema to mark writer-capable Blob v2 fields in named or
nested results.
Open a writer with `BlobWriter.open()`, pass each chunk to `write()`, and
return the sealed writer after leaving its context manager. For plain SQL
`SELECT`, use a byte-returning Function within the query's Arrow output
limits.
*/}
`extract_frame` reads one frame from a video and returns JPEG bytes. Its
explicit output schema declares a Blob v2 result. The `BlobReader` input
lets it read the video incrementally. [Read a blob incrementally](#incremental)
<CodeGroup>
```python Python icon="python"
@@ -365,15 +386,8 @@ fixed-size lists do not support this layout. List-nested values are queryable
as descriptors, but `fetch_blobs` and `blob_mode="bytes"` cannot fetch their
payloads.
<Warning>
`output_schema=lancedb.blob(...)` is what makes a persisted result Blob v2
rather than plain Arrow `binary`. Returning `bytes` from a function whose
output type is inferred from a bare annotation, with no explicit
`lancedb.blob(...)` output schema, persists as ordinary `binary`: the column
still holds the right bytes, but it skips the Managed storage path, descriptor
reads, and `fetch_blobs`. Declare it explicitly on every function whose output
should be a blob, not just the first one in a chain.
</Warning>
A bare `bytes` return annotation infers ordinary Arrow `binary`. To store
returned bytes as Blob v2, declare `output_schema=lancedb.blob(...)`.
### Chain a Function on its output {#chain}
+20 -6
View File
@@ -612,12 +612,26 @@ undecorated class, so local tests can create an instance and call it directly.
A Function can bind a [Blob v2 column](/management/table#managed-blobs) as
input and return another. In row mode, a top-level blob parameter arrives as
Python `bytes`, or `None` for a nullable input, after the worker has read
the payload; annotate it `BlobReader` instead for seekable, incremental
reads that avoid materializing the whole payload first. Return bytes and let
the destination table store the Managed payload and descriptor --
`output_schema=lancedb.blob(...)` is what makes the result Blob v2 rather
than plain Arrow `binary`; a bare annotation persists as ordinary binary
instead, skipping the Managed storage path and `fetch_blobs`.
the payload. Annotate it `BlobReader` for seekable, incremental reads.
For a Function that returns `bytes`, declare
`output_schema=lancedb.blob(...)` to store a Blob v2 result. A bare `bytes`
return annotation infers ordinary Arrow `binary`.
{/*
Draft for the streaming Blob output release.
A scalar `BlobWriter` return annotation infers a non-nullable Blob v2
output. A vectorized Function with an explicit `input_schema` can infer one
Blob v2 per row with `list[BlobWriter]` or `tuple[BlobWriter, ...]`. Use
`BlobWriter.field(...)` to declare writer-capable fields in named or nested
outputs.
Use `BlobWriter` for computed column refresh. Register writer-based Functions
after the LanceDB Enterprise server and Function worker images support
streaming Blob output, using a Python SDK that provides `BlobWriter`. Use
byte-returning Functions on earlier deployments and for plain SQL `SELECT`,
where results follow the query's Arrow output limits.
*/}
See [Read and produce blobs](/curation/create-function#blobs) for a full
example: extracting a frame from a stored video, chaining a second Function
+91
View File
@@ -0,0 +1,91 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Streaming Blob output for Enterprise Functions."""
from __future__ import annotations
import pyarrow as pa
from .schema import blob
_BLOB_WRITER_METADATA_KEY = b"lance.function.blob_writer"
_REFRESH_REQUIRED = (
"BlobWriter is available only during a LanceDB Enterprise computed column refresh"
)
def _mark_blob_writer(field: pa.Field) -> pa.Field:
metadata: dict[bytes | str, bytes | str] = {
key: value for key, value in (field.metadata or {}).items()
}
metadata[_BLOB_WRITER_METADATA_KEY] = b"true"
return field.with_metadata(metadata)
class BlobWriter:
"""Write one Blob v2 value in chunks during a computed column refresh.
Annotate a scalar Function's return value with ``BlobWriter`` to declare a
Blob v2 result. For named or nested results, use :meth:`field` for each
writer-capable field in the output schema. A vectorized Function returns
a row-aligned list or tuple of results.
Open one writer per Blob value. Writes are sequential and block for
capacity. Closing the writer seals the result, including an empty Blob.
A context manager seals on normal exit and aborts on exceptional exit.
A discarded writer still uses one entry in the batch's cumulative
descriptor allowance. Explicit writers and implicit uploads of returned
``bytes`` share this allowance.
Return the sealed writer once at its declared Blob v2 output field during
the same invocation. Unclosed or reused writers are invalid results.
The worker provides the implementation when it runs the packaged Function.
Examples
--------
```python
from lancedb.functions import BlobWriter, function
@function
def render(text: str) -> BlobWriter:
with BlobWriter.open() as output:
for line in text.splitlines():
output.write(line.encode("utf-8"))
output.write(b"\\n")
return output
```
"""
def __init__(self) -> None:
raise RuntimeError(_REFRESH_REQUIRED)
@classmethod
def open(cls) -> BlobWriter:
"""Open a sequential writer for one Blob in the active invocation."""
raise RuntimeError(_REFRESH_REQUIRED)
def write(self, data) -> int:
"""Write a bytes-like object and return the accepted byte count."""
raise RuntimeError(_REFRESH_REQUIRED)
def close(self) -> None:
"""Seal the Blob so the writer can be returned as a result."""
raise RuntimeError(_REFRESH_REQUIRED)
def __enter__(self) -> BlobWriter:
raise RuntimeError(_REFRESH_REQUIRED)
def __exit__(self, exc_type, exc, traceback) -> None:
raise RuntimeError(_REFRESH_REQUIRED)
@staticmethod
def field(name: str, nullable: bool = True) -> pa.Field:
"""Declare a writer-capable Blob v2 field in a Function output schema.
A marked field also accepts ordinary ``bytes`` and, if nullable,
``None``. Use this helper for Function output schemas and use
[``lancedb.blob``][lancedb.blob] for table schemas.
"""
return _mark_blob_writer(blob(name, nullable=nullable))
+255 -63
View File
@@ -63,6 +63,7 @@ from pydantic import (
from .schema import blob as _blob_field
from .schema import is_blob_v2_field as _is_blob_v2_field
from ._blob_reader import BlobReader
from ._blob_writer import BlobWriter, _BLOB_WRITER_METADATA_KEY, _mark_blob_writer
from ._lancedb import _validate_conda_requirement
from .secrets import EnvVarSecret
from .resources import _validate_gpu_class_name
@@ -330,17 +331,27 @@ class FunctionResultField(_OpenRemoteValue):
nullable: bool
class _BlobWriterFieldStep(_RemoteValue):
field: str
_BlobWriterPath = tuple[Union[_BlobWriterFieldStep, Literal["item"]], ...]
class FunctionOutput(_OpenRemoteValue):
"""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.
nullability; its fields carry their own flags. Writer-capable outputs
carry the paths of the declared Blob v2 leaves and use the corresponding
``scalar_blob_writer`` or ``named_struct_blob_writer`` kind.
"""
kind: str
arrow_type: Optional[str] = None
nullable: Optional[bool] = None
fields: tuple[FunctionResultField, ...] = ()
blob_writer_paths: tuple[_BlobWriterPath, ...] = ()
class SecretReference(_RemoteValue):
@@ -1069,7 +1080,7 @@ class FunctionApplication(_OpenRemoteValue):
def rename(self, *, columns: Mapping[str, str]) -> FunctionApplication:
"""Return a copy with result-field to table-column aliases."""
if self.output.kind != "named_struct":
if self.output.kind not in ("named_struct", "named_struct_blob_writer"):
raise ValueError("rename(columns=...) requires a named-struct application")
result_fields = {field.name for field in self.output.fields}
unknown = set(columns) - result_fields
@@ -1496,32 +1507,38 @@ def _grammar_list_item(data_type: pa.DataType) -> Optional[str]:
return _grammar_arrow_type(child.type)
def _validate_exact_arrow_field(field: pa.Field) -> None:
def _validate_exact_arrow_field(
field: pa.Field, *, allow_blob_writer: bool = False
) -> None:
if not field.name:
raise TypeError(
"unsupported Arrow type for Function signature: field names "
"must not be empty"
)
if _is_blob_v2_field(field):
metadata = field.metadata or {}
is_blob = _is_blob_v2_field(field)
if allow_blob_writer and _BLOB_WRITER_METADATA_KEY in metadata:
if not is_blob or metadata[_BLOB_WRITER_METADATA_KEY] != b"true":
raise TypeError("BlobWriter output requires a Blob v2 field marked true")
metadata = {
key: value
for key, value in metadata.items()
if key != _BLOB_WRITER_METADATA_KEY
}
if is_blob:
if not _has_supported_blob_v2_layout(field):
raise TypeError(
"unsupported Arrow type for Function signature: lance.blob.v2 "
f"requires a supported Blob storage layout, got {field}"
)
metadata = {
(key.decode() if isinstance(key, bytes) else key): (
value.decode() if isinstance(value, bytes) else value
)
for key, value in (field.metadata or {}).items()
}
if metadata and metadata != {
_ARROW_EXTENSION_NAME_KEY: _BLOB_V2_EXTENSION_NAME
_ARROW_EXTENSION_NAME_KEY.encode(): _BLOB_V2_EXTENSION_NAME.encode()
}:
raise TypeError(
"unsupported Arrow type for Function signature: lance.blob.v2 "
"field metadata must contain only its canonical extension marker"
)
elif field.metadata:
elif metadata:
raise TypeError(
"unsupported Arrow type for Function signature: field metadata "
f"is not supported, got {field}"
@@ -1580,7 +1597,7 @@ def _has_supported_blob_v2_layout(field: pa.Field) -> bool:
def _canonical_arrow_field(field: pa.Field, *, collection_blobs: bool = False) -> str:
"""``collection_blobs`` admits Blob v2 under a list, which only outputs support."""
_validate_exact_arrow_field(field)
_validate_exact_arrow_field(field, allow_blob_writer=collection_blobs)
if _is_blob_v2_field(field):
return _FUNCTION_BLOB_V2_TYPE
return _canonical_arrow_type(field.type, collection_blobs=collection_blobs)
@@ -1640,10 +1657,11 @@ def _exact_arrow_field(
inside_collection: bool = False,
collection_blobs: bool = False,
) -> dict[str, Any]:
_validate_exact_arrow_field(field)
if _is_blob_v2_field(field):
if inside_collection and not collection_blobs:
raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
is_blob = _is_blob_v2_field(field)
if is_blob and inside_collection and not collection_blobs:
raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
_validate_exact_arrow_field(field, allow_blob_writer=collection_blobs)
if is_blob:
return {
"name": field.name,
"nullable": field.nullable,
@@ -1914,6 +1932,106 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete
return parameters
def _uses_blob_writer(annotation: Any) -> bool:
return annotation is BlobWriter or any(
_uses_blob_writer(argument) for argument in get_args(annotation)
)
def _annotated_blob_writer_field(
annotation: Any, name: str, field: Optional[pa.Field] = None
) -> pa.Field:
"""Infer a writer-bearing field or mark the matching leaf in an explicit field."""
nullable = False
arrow_type = None
while True:
origin = get_origin(annotation)
if origin is Annotated:
annotation, *metadata = get_args(annotation)
types_ = [value for value in metadata if isinstance(value, pa.DataType)]
if len(types_) != 1:
raise TypeError(
"Annotated Function types require exactly one PyArrow DataType"
)
if arrow_type is None:
arrow_type = types_[0]
elif origin in (Union, types.UnionType):
arguments = get_args(annotation)
branches = tuple(arg for arg in arguments if arg is not type(None))
nullable |= len(branches) != len(arguments)
if len(branches) == 1:
(annotation,) = branches
elif frozenset(branches) == {BlobWriter, bytes}:
annotation = BlobWriter
else:
raise TypeError(f"unsupported union annotation: {annotation!r}")
else:
break
if field is None and arrow_type is not None:
field = pa.field(name, arrow_type, nullable=nullable)
if annotation is BlobWriter:
if field is None:
return BlobWriter.field(name, nullable=nullable)
if not _is_blob_v2_field(field):
raise TypeError("BlobWriter output requires a Blob v2 field")
_validate_exact_arrow_field(field, allow_blob_writer=True)
return _mark_blob_writer(field)
if get_origin(annotation) is list:
(element,) = get_args(annotation)
if field is None:
child = _annotated_blob_writer_field(element, "item")
return pa.field(name, pa.list_(child), nullable=nullable)
if not (pa.types.is_list(field.type) or pa.types.is_large_list(field.type)):
raise TypeError("a list of BlobWriter values requires a list output field")
child = field.type.value_field
child = _annotated_blob_writer_field(element, child.name, child)
list_type = pa.large_list if pa.types.is_large_list(field.type) else pa.list_
return field.with_type(list_type(child))
raise TypeError(
"BlobWriter return annotations require a BlobWriter or list of BlobWriter "
"values. Use BlobWriter.field in the output schema for named results."
)
def _writer_annotation_output(annotation, output_schema, *, vectorized: bool):
if vectorized:
arguments = get_args(annotation)
origin = get_origin(annotation)
if origin is list and len(arguments) == 1:
(annotation,) = arguments
elif origin is tuple and len(arguments) == 2 and arguments[1] is Ellipsis:
annotation = arguments[0]
else:
raise TypeError(
"vectorized BlobWriter Functions must annotate a row-aligned list "
"or tuple of results"
)
if output_schema is None:
return _annotated_blob_writer_field(annotation, "result")
if isinstance(output_schema, pa.DataType):
output_schema = pa.field("result", output_schema, nullable=False)
if not isinstance(output_schema, pa.Field):
raise TypeError("use BlobWriter.field in the output schema for named results")
return _annotated_blob_writer_field(annotation, output_schema.name, output_schema)
def _blob_writer_paths(field: pa.Field) -> tuple[_BlobWriterPath, ...]:
if _is_blob_v2_field(field):
return ((),) if _BLOB_WRITER_METADATA_KEY in (field.metadata or {}) else ()
if pa.types.is_struct(field.type):
return tuple(
(_BlobWriterFieldStep(field=child.name), *path)
for child in field.type
for path in _blob_writer_paths(child)
)
if pa.types.is_list(field.type) or pa.types.is_large_list(field.type):
return tuple(
("item", *path) for path in _blob_writer_paths(field.type.value_field)
)
return ()
def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutput:
if isinstance(output, pa.Schema):
if output.metadata:
@@ -1924,7 +2042,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp
and not _is_blob_v2_field(output)
and pa.types.is_struct(output.type)
):
_validate_exact_arrow_field(output)
_validate_exact_arrow_field(output, allow_blob_writer=True)
if output.nullable:
raise ValueError("Function output must be non-nullable")
fields = tuple(output.type)
@@ -1940,32 +2058,39 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp
raise TypeError(
"output_schema must be a PyArrow DataType, Field, or Schema"
)
_validate_exact_arrow_field(field)
arrow_type = _canonical_arrow_field(field, collection_blobs=True)
if field.nullable and _is_blob_v2_field(field):
raise ValueError("Blob v2 Function output must be non-nullable")
paths = _blob_writer_paths(field)
return FunctionOutput(
kind="scalar",
arrow_type=_canonical_arrow_field(field, collection_blobs=True),
kind="scalar_blob_writer" if paths else "scalar",
arrow_type=arrow_type,
nullable=field.nullable,
blob_writer_paths=paths,
)
if not fields:
raise ValueError("named-struct Function output must contain at least one field")
for field in fields:
_validate_exact_arrow_field(field)
names = [field.name for field in fields]
if len(set(names)) != len(names):
raise ValueError("Function output field names must be unique")
results = tuple(
FunctionResultField(
name=field.name,
arrow_type=_canonical_arrow_field(field, collection_blobs=True),
nullable=field.nullable,
)
for field in fields
)
paths = tuple(
(_BlobWriterFieldStep(field=field.name), *path)
for field in fields
for path in _blob_writer_paths(field)
)
return FunctionOutput(
kind="named_struct",
fields=tuple(
FunctionResultField(
name=field.name,
arrow_type=_canonical_arrow_field(field, collection_blobs=True),
nullable=field.nullable,
)
for field in fields
),
kind="named_struct_blob_writer" if paths else "named_struct",
fields=results,
blob_writer_paths=paths,
)
@@ -1987,6 +2112,8 @@ def _infer_signature(
def input_parameter(field):
annotation = annotations.get(field.name)
if _uses_blob_writer(annotation):
raise TypeError("BlobWriter is only supported in Function outputs")
if get_origin(annotation) in (Union, types.UnionType):
choices = [
value for value in get_args(annotation) if value is not type(None)
@@ -2042,10 +2169,17 @@ def _infer_signature(
missing.append("return")
if missing:
raise TypeError(f"missing Function annotations: {missing!r}")
return_annotation = annotations.get("return")
if _uses_blob_writer(return_annotation):
output_schema = _writer_annotation_output(
return_annotation,
output_schema,
vectorized=_is_vectorized_callable(function, method=method),
)
if output_schema is not None:
output = _function_output(output_schema)
else:
output_type, output_nullable = _annotation_type(annotations["return"])
output_type, output_nullable = _annotation_type(return_annotation)
output = _function_output(
pa.field("result", output_type, nullable=output_nullable)
)
@@ -2578,6 +2712,25 @@ def _module_locations_for_name(module_name: str) -> tuple[str, ...]:
return ()
def _blob_writer_annotation_source(annotation: Any, writer_name: str) -> str:
if annotation is BlobWriter:
return writer_name
if annotation is type(None):
return "None"
if annotation is bytes:
return "bytes"
if annotation is Ellipsis:
return "..."
origin = get_origin(annotation)
arguments = get_args(annotation)
if origin is Annotated:
return _blob_writer_annotation_source(arguments[0], writer_name)
elements = [_blob_writer_annotation_source(arg, writer_name) for arg in arguments]
if origin in (Union, types.UnionType):
return " | ".join(elements)
return f"{origin.__name__}[{', '.join(elements)}]"
class _SourcePackager:
"""Builds the entry module of a Function artifact.
@@ -2621,10 +2774,10 @@ class _SourcePackager:
"@function cannot package functions that capture closure values"
)
namespace = _definition_namespace(target)
reader_name = (
self._blob_annotations(definition, signature, namespace)
blob_bindings = (
self._blob_annotations(target, definition, signature, namespace)
if signature is not None
else None
else {}
)
source = ast.unparse(definition)
references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n")
@@ -2649,8 +2802,8 @@ class _SourcePackager:
self._warn_unshipped_direct_imports(definition)
self._packaged.add(id(target))
self._claim(target.__name__, ("definition", id(target)))
if reader_name is not None:
self._bind(reader_name, BlobReader, definition=definition)
for name, blob_type in blob_bindings.items():
self._bind(name, blob_type, definition=definition)
unresolved = []
for name in sorted(references):
if name == target.__name__:
@@ -2673,19 +2826,19 @@ class _SourcePackager:
def _blob_annotations(
self,
target: Any,
definition: Union[ast.FunctionDef, ast.ClassDef],
signature: FunctionSignature,
namespace: Mapping[str, Any],
) -> Optional[str]:
"""Bind reader inputs to the worker type, including postponed aliases."""
) -> dict[str, type]:
"""Bind Blob annotations to worker types, including postponed aliases."""
readers = {
parameter.name: parameter
for parameter in signature.inputs
if parameter.blob_access == "reader"
}
if not readers:
return None
call = definition
if not readers and not signature.output.blob_writer_paths:
return {}
if isinstance(definition, ast.ClassDef):
call = next(
(
@@ -2695,19 +2848,47 @@ class _SourcePackager:
),
None,
)
if call is None:
return None
# Avoid shadowing globals used by the body or other packaged definitions.
name = "_lance_blob_reader"
while name in namespace or name in self._names or name == definition.name:
name += "_"
for argument in (*call.args.args, *call.args.kwonlyargs):
if argument.arg in readers:
annotation = name
if readers[argument.arg].nullable:
annotation += " | None"
argument.annotation = ast.parse(annotation, mode="eval").body
return name
if call is None:
return {}
else:
call = definition
def alias(name: str) -> str:
# Avoid shadowing globals used by the body or other definitions.
while name in namespace or name in self._names or name == definition.name:
name += "_"
return name
bindings = {}
if readers:
name = alias("_lance_blob_reader")
for argument in (*call.args.args, *call.args.kwonlyargs):
if argument.arg in readers:
annotation = name
if readers[argument.arg].nullable:
annotation += " | None"
argument.annotation = ast.parse(annotation, mode="eval").body
bindings[name] = BlobReader
if signature.output.blob_writer_paths:
method = inspect.isclass(target)
callable_ = _class_call(target) if method else target
annotations = get_type_hints(callable_, include_extras=True)
if _is_vectorized_callable(callable_, method=method):
name = alias("_lance_arrow")
for argument in (*call.args.args, *call.args.kwonlyargs):
arrow_type = annotations.get(argument.arg)
if arrow_type is pa.Array or arrow_type is pa.RecordBatch:
argument.annotation = ast.parse(
f"{name}.{arrow_type.__name__}", mode="eval"
).body
bindings[name] = pa
return_type = annotations.get("return")
if _uses_blob_writer(return_type):
name = alias("_lance_blob_writer")
annotation = _blob_writer_annotation_source(return_type, name)
call.returns = ast.parse(annotation, mode="eval").body
bindings[name] = BlobWriter
return bindings
def _claim(self, name: str, meaning: Any) -> None:
claimed = self._names.setdefault(name, meaning)
@@ -2751,8 +2932,8 @@ class _SourcePackager:
approved = _approved_global_namespace_binding(definition, name, value)
if approved is not None:
return approved
if value is BlobReader:
return f"from lance_blob import BlobReader as {name}"
if value is BlobReader or value is BlobWriter:
return f"from lance_blob import {value.__name__} as {name}"
if isinstance(value, types.ModuleType):
if value.__name__.split(".")[0] in _NAMESPACE_MODULES:
raise _namespace_import_error([value.__name__])
@@ -3699,9 +3880,10 @@ def function(
----------
function : function or class, optional
The synchronous callable, or the class whose instances are called. For
a function, annotate every parameter as ``pyarrow.Array`` to opt into
vectorized execution; a matching return annotation documents that the
callable returns an Arrow array.
a function, annotate every parameter as ``pyarrow.Array`` or a single
parameter as ``pyarrow.RecordBatch`` to opt into vectorized execution.
A vectorized Function using ``BlobWriter`` returns a row-aligned list
or tuple of results.
name : str, optional
The remote Function name. Defaults to the callable name.
Must start with an ASCII letter or underscore and contain only ASCII
@@ -3717,8 +3899,9 @@ def function(
a map key must be non-nullable utf8 and its value field keeps the
declared nullability. Temporal fields use canonical Arrow JSON; the
microsecond/no-timezone case keeps the legacy timestamp/duration shape.
Required for batch annotations. When omitted, the output is inferred
from the return annotation.
Required for batch annotations unless the return annotation declares
a row-aligned sequence of ``BlobWriter`` results. 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
@@ -3892,6 +4075,14 @@ def function(
declared nullability. Use :func:`lancedb.blob` in the explicit schemas;
plain ``pyarrow.large_binary()`` does not carry Blob v2 semantics.
For a streaming Blob v2 result, annotate a scalar return with
[``BlobWriter``][lancedb.functions.BlobWriter], or annotate a vectorized
return with ``list[BlobWriter]`` or ``tuple[BlobWriter, ...]``. To declare a
writer in a named or nested output, use ``BlobWriter.field(...)`` in the
explicit output schema. Writer-capable Functions run during computed
column refresh. Plain SQL ``SELECT`` continues to support byte-returning
Functions under its Arrow output limits.
A Blob v2 field may sit at the top level or inside a struct in inputs and
outputs. Only outputs may nest it in a list or large list (for example
``pa.list_(lancedb.blob("item"))``, returned as a list of ``bytes``);
@@ -3935,6 +4126,7 @@ def function(
__all__ = [
"AssignmentMapping",
"ApplicationInput",
"BlobWriter",
"FunctionApplication",
"FunctionArtifact",
"FunctionArtifactContent",
+71 -1
View File
@@ -8,7 +8,7 @@ import pyarrow as pa
import pytest
import lancedb
from lancedb.functions import function
from lancedb.functions import BlobWriter, function
@pytest.mark.asyncio
@@ -61,3 +61,73 @@ async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, ex
assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
assert b'"exist_ok"' not in request
assert json.loads(version.to_canonical_json()) == stored
@pytest.mark.asyncio
async def test_blob_writer_paths_round_trip_through_function_registration():
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
stored = json.loads(fixture.read_text())
expected_paths = [[{"field": "item"}], [{"field": "variants"}, "item"]]
output_schema = pa.schema(
[
BlobWriter.field("item"),
pa.field("variants", pa.list_(BlobWriter.field("asset"))),
pa.field("checksum", pa.binary(), nullable=False),
]
)
@function(name=stored["name"], output_schema=output_schema)
def render(text: str):
with BlobWriter.open() as output:
output.write(text.encode())
return {"item": output, "variants": [b"", None], "checksum": b""}
expected_output = json.loads(
render.registration_request.signature.output.to_canonical_json()
)
assert expected_output["kind"] == "named_struct_blob_writer"
assert expected_output["blob_writer_paths"] == expected_paths
stored["signature"] = {
"inputs": [{"name": "text", "arrow_type": "utf8", "nullable": False}],
"output": expected_output,
}
class FunctionServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(
pa.table({"definition": [json.dumps(stored)]})
)
with FunctionServer() as server:
db = await lancedb.connect_async(
"db://analytics",
api_key="test-key",
host_override="http://localhost:10024",
sql_host_override=f"grpc://127.0.0.1:{server.port}",
)
job = await db.create_function_async(render)
version = await job.wait()
(request,) = server.requests
assert b"CREATE FUNCTION" in request
_, marker, body = request.partition(b" FROM '{")
assert marker
submitted, _ = json.JSONDecoder().raw_decode("{" + body.decode(errors="replace"))
assert submitted["signature"]["output"] == expected_output
assert (
json.loads(version.to_canonical_json())["signature"]["output"]
== expected_output
)
application = version(text=lancedb.col("text")).rename(columns={"item": "payload"})
assert json.loads(application.to_canonical_json())["output"] == expected_output
assert application.columns == {"item": "payload"}
+205 -2
View File
@@ -23,8 +23,14 @@ import pyarrow as pa
import pyarrow.compute as pc
import pytest
from lancedb import col
from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf
from lancedb import blob, col
from lancedb.functions import (
BlobWriter,
FunctionDefinition,
FunctionVersion,
function,
udf,
)
FIXTURES = (
Path(__file__).parents[3]
@@ -625,6 +631,203 @@ def test_class_definition_binds_initialization_only_on_a_version():
scale(factor=col("factor"), label="x")
def test_blob_writer_scalar_annotation_and_bytes_keep_distinct_wire_shapes():
@function
def render(text: str) -> BlobWriter:
with BlobWriter.open() as output:
output.write(text.encode())
return output
@function(output_schema=blob("image", nullable=False))
def render_bytes(text: str) -> bytes:
return text.encode()
scalar = {"kind": "scalar", "arrow_type": "blob_v2", "nullable": False}
writer = {**scalar, "kind": "scalar_blob_writer", "blob_writer_paths": [[]]}
for definition, expected in ((render, writer), (render_bytes, scalar)):
request = json.loads(definition.registration_request.to_canonical_json())
assert request["signature"]["output"] == expected
assert request["artifact"]["adapter"] == {
"kind": "scalar_to_arrow_batch",
"version": 1,
}
assert render_bytes("text") == b"text"
with pytest.raises(RuntimeError, match="computed column refresh"):
render("text")
@pytest.mark.parametrize("input_type", ["Array", "RecordBatch"])
@pytest.mark.parametrize("return_type", ["list[Writer]", "tuple[Writer, ...]"])
def test_blob_writer_vectorized_annotations_resolve_in_the_artifact(
helper_package, monkeypatch, input_type, return_type
):
as_tuple = return_type.startswith("tuple")
result = "tuple(results)" if as_tuple else "results"
column = "values" if input_type == "Array" else "values.column(0)"
module = helper_package(
"fx_blob_writers",
{
"__init__.py": f"""
from __future__ import annotations
import pyarrow as pa
from pyarrow import {input_type} as Batch
from lancedb.functions import BlobWriter as Writer, function
Output = {return_type}
@function(input_schema=pa.schema([pa.field("values", pa.string())]))
def render(values: Batch) -> Output:
results = []
for text in {column}:
with Writer.open() as output:
output.write(text.as_py().encode())
results.append(output)
return {result}
""",
},
)
assert json.loads(
module.render.registration_request.signature.output.to_canonical_json()
) == {
"kind": "scalar_blob_writer",
"arrow_type": "blob_v2",
"nullable": False,
"blob_writer_paths": [[]],
}
class WorkerWriter:
def __init__(self):
self.payload = bytearray()
self.closed = False
@classmethod
def open(cls):
return cls()
def write(self, data):
self.payload.extend(data)
return len(data)
def __enter__(self):
return self
def __exit__(self, *_):
self.closed = True
worker = types.ModuleType("lance_blob")
worker.BlobWriter = WorkerWriter
monkeypatch.setitem(sys.modules, "lance_blob", worker)
namespace = {}
exec(compile(artifact(module.render), "user_function.py", "exec"), namespace)
render = namespace["render"]
input_annotation = getattr(pa, input_type)
output_annotation = (
tuple[WorkerWriter, ...]
if return_type.startswith("tuple")
else list[WorkerWriter]
)
assert get_type_hints(render) == {
"values": input_annotation,
"return": output_annotation,
}
column = pa.array(["alpha", "", "omega"])
batch = column if input_type == "Array" else pa.record_batch([column], names=["x"])
output = render(batch)
assert [(type(value), value.closed, bytes(value.payload)) for value in output] == [
(WorkerWriter, True, b"alpha"),
(WorkerWriter, True, b""),
(WorkerWriter, True, b"omega"),
]
@pytest.mark.parametrize("list_type", [pa.list_, pa.large_list])
def test_blob_writer_nested_paths_keep_logical_arrow_schema(list_type):
def output_schema(blob_field):
return list_type(
pa.field(
"asset",
pa.struct(
[
blob_field("item"),
blob("bytes_sibling"),
pa.field("checksum", pa.binary(), nullable=False),
blob_field("rendered.blob", nullable=False),
]
),
)
)
def render_batch(values: pa.Array):
return [
[
{
"item": None,
"bytes_sibling": b"",
"checksum": b"ok",
"rendered.blob": b"",
}
]
] * len(values)
input_schema = pa.schema([pa.field("values", pa.string())])
streaming = function(
render_batch,
input_schema=input_schema,
output_schema=output_schema(BlobWriter.field),
)
materialized = function(
render_batch, input_schema=input_schema, output_schema=output_schema(blob)
)
plain = json.loads(
materialized.registration_request.signature.output.to_canonical_json()
)
writer = json.loads(
streaming.registration_request.signature.output.to_canonical_json()
)
assert writer == {
**plain,
"kind": "scalar_blob_writer",
"blob_writer_paths": [
["item", {"field": "item"}],
["item", {"field": "rendered.blob"}],
],
}
item = json.loads(writer["arrow_type"])["fields"][0]
assert item["name"] == "asset"
assert item["nullable"] is True
assert item["type"]["fields"][0]["metadata"] == {
"ARROW:extension:name": "lance.blob.v2"
}
def test_blob_writer_requires_supported_output_leaves():
def annotated(value: str) -> BlobWriter:
return BlobWriter.open()
def optional(value: str) -> BlobWriter | None:
return None
def explicit(value: str):
return value
with pytest.raises(TypeError, match="requires a Blob v2 field"):
function(annotated, output_schema=pa.binary())
with pytest.raises(ValueError, match="must be non-nullable"):
function(optional)
invalid_field = pa.field(
"value", pa.binary(), metadata={"lance.function.blob_writer": "true"}
)
with pytest.raises(TypeError, match="requires a Blob v2 field"):
function(explicit, output_schema=pa.struct([invalid_field]))
for schema in (
pa.list_(BlobWriter.field("item"), 2),
pa.map_(pa.string(), BlobWriter.field("value")),
):
with pytest.raises(TypeError, match="nested under collection types"):
function(explicit, output_schema=schema)
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("postponed", [False, True])
@pytest.mark.parametrize(
+39 -9
View File
@@ -162,15 +162,23 @@ fn application_has_unknown_nested_fields(value: &Value) -> bool {
return true;
}
application.get("output").is_some_and(|output| {
has_unknown_keys(output, &["kind", "arrow_type", "nullable", "fields"])
|| output
.get("fields")
.and_then(Value::as_array)
.is_some_and(|fields| {
fields
.iter()
.any(|field| has_unknown_keys(field, &["name", "arrow_type", "nullable"]))
})
has_unknown_keys(
output,
&[
"kind",
"arrow_type",
"nullable",
"fields",
"blob_writer_paths",
],
) || output
.get("fields")
.and_then(Value::as_array)
.is_some_and(|fields| {
fields
.iter()
.any(|field| has_unknown_keys(field, &["name", "arrow_type", "nullable"]))
})
})
}
@@ -224,6 +232,23 @@ pub struct FunctionResultField {
pub nullable: bool,
}
/// One step from the Function result root to a writer-capable Blob v2 leaf.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
pub enum BlobWriterPathStep {
/// A struct child addressed by its literal Arrow field name.
Field { field: String },
/// A list value field, independent of its name.
ListItem(BlobWriterListItem),
}
/// The list step in a Blob writer path, encoded as `"item"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlobWriterListItem {
Item,
}
/// Scalar or named-struct Function output.
///
/// `kind` remains a string so unknown future result shapes can be decoded.
@@ -236,6 +261,11 @@ pub struct FunctionOutput {
pub nullable: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<FunctionResultField>,
/// Writer-capable Blob v2 leaves in `scalar_blob_writer` and
/// `named_struct_blob_writer` results. An empty path denotes a scalar
/// Blob result; an empty list denotes a result with no writer leaves.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub blob_writer_paths: Vec<Vec<BlobWriterPathStep>>,
}
/// Ordered language-neutral Function signature.
+48 -12
View File
@@ -1709,7 +1709,7 @@ pub(crate) fn plan_function_application(
let mut outputs = Vec::new();
let mut output_fields = Vec::new();
match output.kind.as_str() {
"scalar" => {
"scalar" | "scalar_blob_writer" => {
if !application.columns().is_empty() {
return Err(invalid_function(
"scalar Function applications cannot rename result fields",
@@ -1738,7 +1738,7 @@ pub(crate) fn plan_function_application(
});
output_fields.push(function_output_field(name, true, arrow_type)?);
}
"named_struct" => {
"named_struct" | "named_struct_blob_writer" => {
if output.fields.is_empty() {
return Err(invalid_function(
"named-struct Function output requires at least one field",
@@ -5197,17 +5197,53 @@ mod tests {
#[test]
fn test_blob_function_plans_semantic_input_and_scalar_output() {
let schema = ArrowSchema::new(vec![crate::blob("image", false)]);
let application =
blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#);
let plan = plan_function_application(&schema, &application, Some("thumbnail")).unwrap();
for output in [
r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#,
r#"{"kind":"scalar_blob_writer","arrow_type":"blob_v2","nullable":false,"blob_writer_paths":[[]]}"#,
] {
let application = blob_application(output);
let plan = plan_function_application(&schema, &application, Some("thumbnail")).unwrap();
assert_eq!(plan.input_bindings[0].arrow_type, FUNCTION_BLOB_V2_TYPE);
let input_schema =
lance_namespace::schema::convert_json_arrow_schema(&plan.input_schema).unwrap();
assert!(input_schema.field(0).is_blob_v2());
let output_schema =
lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap();
assert!(output_schema.field(0).is_blob_v2());
assert_eq!(plan.input_bindings[0].arrow_type, FUNCTION_BLOB_V2_TYPE);
let input_schema =
lance_namespace::schema::convert_json_arrow_schema(&plan.input_schema).unwrap();
assert!(input_schema.field(0).is_blob_v2());
let output_schema =
lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap();
assert!(output_schema.field(0).is_blob_v2());
}
}
#[test]
fn test_named_blob_writer_plan_preserves_logical_output_columns() {
let schema = ArrowSchema::new(vec![crate::blob("image", false)]);
let application = blob_application(
r#"{
"kind":"named_struct_blob_writer",
"fields":[
{"name":"item","arrow_type":"blob_v2","nullable":true},
{"name":"checksum","arrow_type":"binary","nullable":false}
],
"blob_writer_paths":[[{"field":"item"}]]
}"#,
);
let expanded = plan_function_application(&schema, &application, None).unwrap();
let expanded_schema =
lance_namespace::schema::convert_json_arrow_schema(&expanded.output_schema).unwrap();
assert_eq!(expanded_schema.field(0).name(), "item");
assert!(expanded_schema.field(0).is_blob_v2());
assert_eq!(expanded_schema.field(1).data_type(), &DataType::Binary);
let whole = plan_function_application(&schema, &application, Some("rendered")).unwrap();
let whole_schema =
lance_namespace::schema::convert_json_arrow_schema(&whole.output_schema).unwrap();
let DataType::Struct(fields) = whole_schema.field(0).data_type() else {
panic!("named writer output must bind as a struct");
};
assert!(fields[0].is_blob_v2());
assert!(fields[0].is_nullable());
assert_eq!(fields[1].data_type(), &DataType::Binary);
assert!(!fields[1].is_nullable());
}
#[test]