mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main and align cosine patch with Lance beta.29
This commit is contained in:
@@ -16,7 +16,7 @@ The Python package is a wrapper around the Rust library, `lancedb`. We use
|
||||
|
||||
To set up your development environment, you will need to install the following:
|
||||
|
||||
1. Python 3.10 or later
|
||||
1. Python 3.11 or later
|
||||
2. Cargo (Rust's package manager). Use [rustup](https://rustup.rs/) to install.
|
||||
3. [protoc](https://grpc.io/docs/protoc-installation/) (Protocol Buffers compiler)
|
||||
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.25"
|
||||
version = "0.42.0-beta.27"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
@@ -32,7 +32,7 @@ env_logger.workspace = true
|
||||
log.workspace = true
|
||||
# Maturin enables extension-module mode for Python builds. Keeping it out of
|
||||
# Cargo features lets Rust unit tests link against libpython.
|
||||
pyo3 = { version = "0.29", features = ["abi3-py310", "chrono", "uuid"] }
|
||||
pyo3 = { version = "0.29", features = ["abi3-py311", "chrono", "uuid"] }
|
||||
chrono.workspace = true
|
||||
pyo3-async-runtimes = { version = "0.29", features = [
|
||||
"attributes",
|
||||
|
||||
@@ -16,7 +16,7 @@ description = "Embedded database for vector, full-text and hybrid search on Lanc
|
||||
authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }]
|
||||
license = { file = "LICENSE" }
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
requires-python = ">=3.11"
|
||||
keywords = [
|
||||
"lance",
|
||||
"vector-search",
|
||||
@@ -33,7 +33,6 @@ classifiers = [
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
@@ -64,7 +63,7 @@ tests = [
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b28",
|
||||
"pylance==15.0.0b29",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
@@ -73,18 +72,17 @@ dev = [
|
||||
"ruff>=0.3.0",
|
||||
"pre-commit>=3.5.0",
|
||||
"pyright>=1.1.350",
|
||||
'typing-extensions>=4.0.0; python_version < "3.11"',
|
||||
"maturin>=1.10",
|
||||
]
|
||||
docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material", "mkdocstrings-python"]
|
||||
clip = ["torch", "pillow>=12.1.1", "open-clip-torch"]
|
||||
siglip = ["torch", "pillow>=12.1.1", "transformers>=4.41.0","sentencepiece"]
|
||||
clip = ["torch", "pillow>=13.0.0", "open-clip-torch"]
|
||||
siglip = ["torch", "pillow>=13.0.0", "transformers>=4.41.0","sentencepiece"]
|
||||
embeddings = [
|
||||
"requests>=2.31.0",
|
||||
"openai>=1.6.1",
|
||||
"sentence-transformers>=2.2.0",
|
||||
"torch>=2.0.0",
|
||||
"pillow>=12.1.1",
|
||||
"pillow>=13.0.0",
|
||||
"open-clip-torch>=2.20.0",
|
||||
"cohere>=4.0",
|
||||
"colpali-engine>=0.3.10",
|
||||
|
||||
@@ -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))
|
||||
@@ -463,6 +463,9 @@ class DBConnection(EnforceOverrides):
|
||||
azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_storage_account_access_key_secret: Optional[
|
||||
Union[str, SecretReference]
|
||||
] = None,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
exist_ok: bool = False,
|
||||
@@ -2754,6 +2757,9 @@ class LanceDBConnection(DBConnection):
|
||||
azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_storage_account_access_key_secret: Optional[
|
||||
Union[str, SecretReference]
|
||||
] = None,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
exist_ok: bool = False,
|
||||
@@ -2772,6 +2778,7 @@ class LanceDBConnection(DBConnection):
|
||||
azure_tenant_id_secret=azure_tenant_id_secret,
|
||||
azure_client_id_secret=azure_client_id_secret,
|
||||
azure_client_secret_secret=azure_client_secret_secret,
|
||||
azure_storage_account_access_key_secret=azure_storage_account_access_key_secret,
|
||||
gcp_credentials_json_secret=gcp_credentials_json_secret,
|
||||
huggingface_token_secret=huggingface_token_secret,
|
||||
exist_ok=exist_ok,
|
||||
@@ -4269,6 +4276,9 @@ class AsyncConnection(object):
|
||||
azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_storage_account_access_key_secret: Optional[
|
||||
Union[str, SecretReference]
|
||||
] = None,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
exist_ok: bool = False,
|
||||
@@ -4279,7 +4289,8 @@ class AsyncConnection(object):
|
||||
``namespace_path`` follows Secret naming rules. A SecretReference can name
|
||||
another database; a string names a root Secret in this database.
|
||||
For Azure, set ``storage_provider="AZURE"``, ``azure_storage_account``,
|
||||
and Secret references for tenant ID, client ID and client secret.
|
||||
and either ``azure_storage_account_access_key_secret`` or the three
|
||||
Secret references for tenant ID, client ID and client secret.
|
||||
For GCP, set ``storage_provider="GCP"`` and ``gcp_credentials_json_secret``
|
||||
to a Secret containing the application credentials JSON file content.
|
||||
For Hugging Face, set ``storage_provider="HUGGINGFACE"`` and
|
||||
@@ -4291,11 +4302,14 @@ class AsyncConnection(object):
|
||||
integration exists, preserving its provider, prefix and credential
|
||||
bindings. Existing names are errors by default.
|
||||
"""
|
||||
azure_options = (
|
||||
azure_service_principal = (
|
||||
azure_tenant_id_secret,
|
||||
azure_client_id_secret,
|
||||
azure_client_secret_secret,
|
||||
)
|
||||
azure_options = azure_service_principal + (
|
||||
azure_storage_account_access_key_secret,
|
||||
)
|
||||
if storage_provider != "HUGGINGFACE" and huggingface_token_secret is not None:
|
||||
raise ValueError(
|
||||
"Hugging Face options require storage_provider HUGGINGFACE"
|
||||
@@ -4331,12 +4345,17 @@ class AsyncConnection(object):
|
||||
):
|
||||
raise ValueError("GCP integrations cannot contain AWS or Azure options")
|
||||
elif storage_provider == "AZURE":
|
||||
if not azure_storage_account or any(
|
||||
value is None for value in azure_options
|
||||
):
|
||||
if not azure_storage_account:
|
||||
raise ValueError("Azure integrations require azure_storage_account")
|
||||
valid_credentials = (
|
||||
all(value is None for value in azure_service_principal)
|
||||
if azure_storage_account_access_key_secret is not None
|
||||
else all(value is not None for value in azure_service_principal)
|
||||
)
|
||||
if not valid_credentials:
|
||||
raise ValueError(
|
||||
"Azure requires a storage account and "
|
||||
"all three credential Secret references"
|
||||
"Specify either azure_storage_account_access_key_secret or "
|
||||
"all three Azure service principal Secret references"
|
||||
)
|
||||
if any(
|
||||
value is not None
|
||||
@@ -4393,6 +4412,9 @@ class AsyncConnection(object):
|
||||
"azure_tenant_id_secret": reference(azure_tenant_id_secret),
|
||||
"azure_client_id_secret": reference(azure_client_id_secret),
|
||||
"azure_client_secret_secret": reference(azure_client_secret_secret),
|
||||
"azure_storage_account_access_key_secret": reference(
|
||||
azure_storage_account_access_key_secret
|
||||
),
|
||||
"gcp_credentials_json_secret": reference(gcp_credentials_json_secret),
|
||||
"huggingface_token_secret": reference(huggingface_token_secret),
|
||||
"aws_access_key_id_secret": reference(aws_access_key_id_secret),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -62,7 +62,7 @@ from ._blob import (
|
||||
from .types import BlobMode, QueryProjection
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import sys
|
||||
from typing import Self
|
||||
|
||||
import PIL
|
||||
import polars as pl
|
||||
@@ -77,11 +77,6 @@ if TYPE_CHECKING:
|
||||
from .pydantic import LanceModel
|
||||
from .table import AsyncTable, Table
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import Self
|
||||
else:
|
||||
from typing_extensions import Self
|
||||
|
||||
T = TypeVar("T", bound="LanceModel")
|
||||
|
||||
|
||||
|
||||
@@ -1150,6 +1150,9 @@ class RemoteDBConnection(DBConnection):
|
||||
azure_tenant_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_id_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
|
||||
azure_storage_account_access_key_secret: Optional[
|
||||
Union[str, SecretReference]
|
||||
] = None,
|
||||
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
|
||||
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
|
||||
exist_ok: bool = False,
|
||||
@@ -1168,6 +1171,7 @@ class RemoteDBConnection(DBConnection):
|
||||
azure_tenant_id_secret=azure_tenant_id_secret,
|
||||
azure_client_id_secret=azure_client_id_secret,
|
||||
azure_client_secret_secret=azure_client_secret_secret,
|
||||
azure_storage_account_access_key_secret=azure_storage_account_access_key_secret,
|
||||
gcp_credentials_json_secret=gcp_credentials_json_secret,
|
||||
huggingface_token_secret=huggingface_token_secret,
|
||||
exist_ok=exist_ok,
|
||||
|
||||
@@ -50,6 +50,7 @@ class StorageIntegrationInfo:
|
||||
azure_client_secret_secret: Optional[SecretReference] = None
|
||||
gcp_credentials_json_secret: Optional[SecretReference] = None
|
||||
huggingface_token_secret: Optional[SecretReference] = None
|
||||
azure_storage_account_access_key_secret: Optional[SecretReference] = None
|
||||
|
||||
def __post_init__(self):
|
||||
for field in (
|
||||
@@ -58,6 +59,7 @@ class StorageIntegrationInfo:
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
"azure_storage_account_access_key_secret",
|
||||
"gcp_credentials_json_secret",
|
||||
"huggingface_token_secret",
|
||||
):
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1374,7 +1374,11 @@ async def test_profile_wait_preserves_timeout_and_never_waits_or_cancels_parent(
|
||||
await asyncio.to_thread(Job(job).wait_for_profile, "profile-1", **kwargs)
|
||||
else:
|
||||
await job.wait_for_profile("profile-1", **kwargs)
|
||||
assert caught.value is error
|
||||
assert caught.value.args == error.args
|
||||
# On Python 3.11 and 3.12, run_coroutine_threadsafe re-creates TimeoutError
|
||||
# when copying it across futures, so identity only holds on the async path.
|
||||
if not sync:
|
||||
assert caught.value is error
|
||||
inner.wait_for_profile.assert_awaited_once_with(
|
||||
"profile-1", timeout_seconds=0.05, poll_interval_seconds=5.0
|
||||
)
|
||||
|
||||
@@ -68,8 +68,17 @@ def test_windows_wheel_tag_and_native_import():
|
||||
if not wheels:
|
||||
pytest.skip("no wheel artifact is available in this development environment")
|
||||
|
||||
# The wheel is tagged with the abi3 floor, which follows requires-python.
|
||||
minimum_python = re.search(
|
||||
r'^requires-python\s*=\s*">=(\d+)\.(\d+)"$',
|
||||
(project_dir / "pyproject.toml").read_text(),
|
||||
re.MULTILINE,
|
||||
)
|
||||
assert minimum_python is not None
|
||||
major, minor = minimum_python.groups()
|
||||
|
||||
assert len(wheels) == 1
|
||||
assert wheels[0].name.endswith("-cp310-abi3-win_amd64.whl")
|
||||
assert wheels[0].name.endswith(f"-cp{major}{minor}-abi3-win_amd64.whl")
|
||||
|
||||
native_module = importlib.import_module("lancedb._lancedb")
|
||||
assert Path(native_module.__file__).suffix == ".pyd"
|
||||
|
||||
@@ -118,14 +118,23 @@ def remote_server(text_type=pa.string()):
|
||||
trust_policy=None,
|
||||
permissions_policy=None,
|
||||
)
|
||||
for field, name in (
|
||||
("azure_tenant_id_secret", "tenant"),
|
||||
("azure_client_id_secret", "client"),
|
||||
("azure_client_secret_secret", "credential"),
|
||||
):
|
||||
info[field] = dict(
|
||||
database="shared", namespace_path=["credentials"], name=name
|
||||
if b"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET" in command:
|
||||
info["azure_storage_account_access_key_secret"] = dict(
|
||||
database="shared",
|
||||
namespace_path=["credentials"],
|
||||
name="blob_key",
|
||||
)
|
||||
else:
|
||||
for field, name in (
|
||||
("azure_tenant_id_secret", "tenant"),
|
||||
("azure_client_id_secret", "client"),
|
||||
("azure_client_secret_secret", "credential"),
|
||||
):
|
||||
info[field] = dict(
|
||||
database="shared",
|
||||
namespace_path=["credentials"],
|
||||
name=name,
|
||||
)
|
||||
if b"STORAGE_AWS_ACCESS_KEY_ID_SECRET" in command:
|
||||
info["aws_role_arn"] = None
|
||||
info["trust_policy"] = None
|
||||
@@ -149,6 +158,7 @@ def remote_server(text_type=pa.string()):
|
||||
"azure_tenant_id_secret",
|
||||
"azure_client_id_secret",
|
||||
"azure_client_secret_secret",
|
||||
"azure_storage_account_access_key_secret",
|
||||
"gcp_credentials_json_secret",
|
||||
"huggingface_token_secret",
|
||||
]:
|
||||
@@ -339,6 +349,44 @@ def test_azure_lifecycle_uses_three_qualified_secret_references(text_type):
|
||||
assert b"STORAGE_AWS" not in sql
|
||||
|
||||
|
||||
def test_azure_lifecycle_uses_one_qualified_account_access_key_secret():
|
||||
with remote_server() as (host, calls):
|
||||
db = connect(host)
|
||||
key = SecretReference(
|
||||
"blob_key", database="shared", namespace_path=("credentials",)
|
||||
)
|
||||
config = {
|
||||
"storage_provider": "AZURE",
|
||||
"azure_storage_account": "customeraccount",
|
||||
"azure_storage_account_access_key_secret": key,
|
||||
}
|
||||
with pytest.raises(ValueError, match="service principal"):
|
||||
db.create_storage_integration(
|
||||
"blobs",
|
||||
"az://customer-data/raw/",
|
||||
azure_client_id_secret="client",
|
||||
**config,
|
||||
)
|
||||
assert calls == []
|
||||
|
||||
info = db.create_storage_integration(
|
||||
"blobs", "az://customer-data/raw/", **config
|
||||
)
|
||||
reference = info.azure_storage_account_access_key_secret
|
||||
assert reference is not None
|
||||
assert reference.name == key.name
|
||||
assert reference.database == key.database
|
||||
assert tuple(reference.namespace_path) == key.namespace_path
|
||||
assert info.azure_tenant_id_secret is None
|
||||
assert info.azure_client_id_secret is None
|
||||
assert info.azure_client_secret_secret is None
|
||||
assert db.describe_storage_integration("blobs") == info
|
||||
assert (
|
||||
b"STORAGE_AZURE_STORAGE_ACCOUNT_ACCESS_KEY_SECRET = "
|
||||
b'"shared"."credentials"."blob_key"' in calls[0]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_azure_requires_account_and_all_three_secret_references():
|
||||
with remote_server() as (host, calls):
|
||||
|
||||
Generated
+52
-1147
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user