mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main and align cosine fix with Lance beta.25
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.17"
|
||||
version = "0.42.0-beta.18"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
|
||||
@@ -64,7 +64,7 @@ tests = [
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b23",
|
||||
"pylance==15.0.0b25",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
|
||||
@@ -1859,24 +1859,42 @@ def _is_function_decorator(node: ast.expr) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _literal_source(value: Any, name: str) -> str:
|
||||
if value is None or type(value) in (bool, int, str, bytes):
|
||||
return repr(value)
|
||||
if type(value) is float and math.isfinite(value):
|
||||
return repr(value)
|
||||
if type(value) is tuple:
|
||||
children = ", ".join(_literal_source(child, name) for child in value)
|
||||
if len(value) == 1:
|
||||
children += ","
|
||||
return f"({children})"
|
||||
raise TypeError(
|
||||
# A captured value is inlined into the artifact source; larger data belongs in a
|
||||
# table or a package resource.
|
||||
_MAX_CAPTURED_SOURCE = 1024 * 1024
|
||||
# Far below CPython's parser nesting limit.
|
||||
_MAX_CAPTURED_DEPTH = 32
|
||||
_CAPTURE_REMEDY = "Define this value inside the function or class body instead."
|
||||
|
||||
|
||||
def _unsupported_capture(name: str, kind: str) -> TypeError:
|
||||
return TypeError(
|
||||
"Function source references an unsupported global value of type "
|
||||
f"{type(value).__name__} in {name!r}. Only None, bool, int, str, bytes, "
|
||||
"finite float, and tuples of these literals can be captured. "
|
||||
"Define this value inside the function or class body instead."
|
||||
f"{kind} in {name!r}. Captured globals can be None, bool, int, str, "
|
||||
"bytes, or finite float values; tuples, lists, dicts, sets, or frozensets "
|
||||
"of supported values; PyArrow data types, fields, or schemas; or NumPy "
|
||||
"arrays or scalars of bool, integer, float16, float32, or float64 dtypes. "
|
||||
+ _CAPTURE_REMEDY
|
||||
)
|
||||
|
||||
|
||||
def _python_extension_type(data_type: pa.DataType) -> Optional[pa.ExtensionType]:
|
||||
"""The first extension type within `data_type` whose class is defined in
|
||||
Python. IPC carries only its name, so it deserializes as the storage type
|
||||
wherever that class is not registered."""
|
||||
if isinstance(data_type, pa.ExtensionType):
|
||||
return data_type
|
||||
if isinstance(data_type, pa.BaseExtensionType):
|
||||
return _python_extension_type(data_type.storage_type)
|
||||
if isinstance(data_type, pa.DictionaryType):
|
||||
return _python_extension_type(data_type.value_type)
|
||||
for index in range(data_type.num_fields):
|
||||
found = _python_extension_type(data_type.field(index).type)
|
||||
if found is not None:
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
_DYNAMIC_NAMESPACE_ACCESS = frozenset(
|
||||
{"globals", "locals", "vars", "eval", "exec", "compile", "__import__"}
|
||||
)
|
||||
@@ -2175,7 +2193,7 @@ class _SourcePackager:
|
||||
|
||||
The module holds the definition plus exactly the module-level names it
|
||||
references: modules as imports, importable classes and functions as
|
||||
imports, literals inline, and functions and classes defined in
|
||||
imports, captured values inline, and functions and classes defined in
|
||||
``__main__`` by source, recursively, dependencies first.
|
||||
"""
|
||||
|
||||
@@ -2183,6 +2201,7 @@ class _SourcePackager:
|
||||
self._code_modules = code_modules
|
||||
self._requirements = requirements
|
||||
self._imports: dict[str, str] = {}
|
||||
self._support_imports: dict[str, str] = {}
|
||||
self._definitions: list[str] = []
|
||||
self._packaged: set[int] = set()
|
||||
self._names: dict[str, Any] = {}
|
||||
@@ -2191,8 +2210,13 @@ class _SourcePackager:
|
||||
def package(self, target: Any, signature: FunctionSignature) -> str:
|
||||
entry = self._definition(target, entry=True, signature=signature)
|
||||
parts = [_SOURCE_HEADER]
|
||||
if self._imports:
|
||||
parts.extend(["", *(self._imports[name] for name in sorted(self._imports))])
|
||||
# Captured values are rebuilt with the support modules, so those come first.
|
||||
imports = [
|
||||
*(self._support_imports[alias] for alias in sorted(self._support_imports)),
|
||||
*(self._imports[name] for name in sorted(self._imports)),
|
||||
]
|
||||
if imports:
|
||||
parts.extend(["", *imports])
|
||||
for definition in self._definitions:
|
||||
parts.extend(["", definition])
|
||||
parts.extend(["", entry, ""])
|
||||
@@ -2313,8 +2337,8 @@ class _SourcePackager:
|
||||
|
||||
def _global_source(self, name: str, value: Any) -> str:
|
||||
"""One module-level line that rebinds `name` to `value` in the artifact:
|
||||
an import for modules and importable classes/functions, a literal
|
||||
otherwise."""
|
||||
an import for modules and importable classes/functions, a captured
|
||||
copy otherwise."""
|
||||
if value is BlobReader:
|
||||
return f"from lance_blob import BlobReader as {name}"
|
||||
if isinstance(value, types.ModuleType):
|
||||
@@ -2347,7 +2371,149 @@ class _SourcePackager:
|
||||
if imported is value:
|
||||
self._require_importable(module_name)
|
||||
return f"from {module_name} import {qualname} as {name}"
|
||||
return f"{name} = {_literal_source(value, name)}"
|
||||
return f"{name} = {self._captured_source(name, value)}"
|
||||
|
||||
def _captured_source(self, name: str, value: Any) -> str:
|
||||
"""An expression that rebuilds a copy of the global `name`.
|
||||
|
||||
Literals and containers are written as Python literals, with set
|
||||
elements sorted by their source so the artifact does not depend on hash
|
||||
randomization. Arrow values are rebuilt from Arrow's IPC schema encoding
|
||||
and NumPy values from their dtype and elements.
|
||||
"""
|
||||
remaining = _MAX_CAPTURED_SOURCE
|
||||
enclosing: set[int] = set()
|
||||
|
||||
def too_large() -> ValueError:
|
||||
return ValueError(
|
||||
f"Function global {name!r} is too large to capture: its source "
|
||||
f"exceeds {_MAX_CAPTURED_SOURCE} characters. Load large data inside "
|
||||
"the function or class body instead, for example from a table or a "
|
||||
"package resource shipped with code=."
|
||||
)
|
||||
|
||||
def charge(source: str, nested: Sequence[str] = ()) -> str:
|
||||
nonlocal remaining
|
||||
remaining -= len(source) - sum(map(len, nested))
|
||||
if remaining < 0:
|
||||
raise too_large()
|
||||
return source
|
||||
|
||||
def emit(value: Any) -> str:
|
||||
if value is None or type(value) in (bool, int, str, bytes):
|
||||
return charge(repr(value))
|
||||
if type(value) is float and math.isfinite(value):
|
||||
return charge(repr(value))
|
||||
if isinstance(value, (pa.DataType, pa.Field, pa.Schema)):
|
||||
return charge(self._arrow_source(name, value))
|
||||
numpy = sys.modules.get("numpy")
|
||||
if numpy is not None and (
|
||||
type(value) is numpy.ndarray or isinstance(value, numpy.generic)
|
||||
):
|
||||
return emit_numpy(numpy, value)
|
||||
if type(value) in (tuple, list, dict, set, frozenset):
|
||||
return emit_container(value)
|
||||
raise _unsupported_capture(name, type(value).__name__)
|
||||
|
||||
def emit_numpy(numpy: types.ModuleType, value: Any) -> str:
|
||||
# These convert to exact Python values; longdouble stays a NumPy scalar.
|
||||
if value.dtype.kind not in "biuf" or value.dtype.type is numpy.longdouble:
|
||||
raise _unsupported_capture(
|
||||
name, f"{type(value).__name__} with dtype {value.dtype}"
|
||||
)
|
||||
# Every element takes at least one character; check before tolist().
|
||||
if value.size > remaining:
|
||||
raise too_large()
|
||||
alias = self._support_module("numpy")
|
||||
dtype = repr(value.dtype.str)
|
||||
if isinstance(value, numpy.generic):
|
||||
item = emit(value.item())
|
||||
return charge(f"{alias}.dtype({dtype}).type({item})", (item,))
|
||||
if value.size == 0:
|
||||
return charge(
|
||||
f"{alias}.array([], dtype={dtype}).reshape({value.shape!r})"
|
||||
)
|
||||
elements = emit(value.tolist())
|
||||
source = f"{alias}.array({elements}, dtype={dtype})"
|
||||
return charge(source, (elements,))
|
||||
|
||||
def emit_container(value: Any) -> str:
|
||||
if id(value) in enclosing:
|
||||
raise ValueError(
|
||||
f"Function global {name!r} contains itself and cannot be "
|
||||
"captured. " + _CAPTURE_REMEDY
|
||||
)
|
||||
if len(enclosing) == _MAX_CAPTURED_DEPTH:
|
||||
raise ValueError(
|
||||
f"Function global {name!r} nests containers more than "
|
||||
f"{_MAX_CAPTURED_DEPTH} levels deep and cannot be captured. "
|
||||
+ _CAPTURE_REMEDY
|
||||
)
|
||||
enclosing.add(id(value))
|
||||
if type(value) is dict:
|
||||
entries = [(emit(key), emit(child)) for key, child in value.items()]
|
||||
children = [part for entry in entries for part in entry]
|
||||
listed = ", ".join(f"{key}: {child}" for key, child in entries)
|
||||
source = f"{{{listed}}}"
|
||||
else:
|
||||
children = [emit(child) for child in value]
|
||||
if type(value) in (set, frozenset):
|
||||
listed = ", ".join(sorted(children))
|
||||
else:
|
||||
listed = ", ".join(children)
|
||||
if type(value) is tuple:
|
||||
source = f"({listed},)" if len(children) == 1 else f"({listed})"
|
||||
elif type(value) is list:
|
||||
source = f"[{listed}]"
|
||||
elif type(value) is set:
|
||||
source = (
|
||||
f"{{{listed}}}" if children else f"{self._builtin('set')}()"
|
||||
)
|
||||
else:
|
||||
items = f"{{{listed}}}" if children else ""
|
||||
source = f"{self._builtin('frozenset')}({items})"
|
||||
enclosing.remove(id(value))
|
||||
return charge(source, children)
|
||||
|
||||
return emit(value)
|
||||
|
||||
def _arrow_source(
|
||||
self, name: str, value: Union[pa.DataType, pa.Field, pa.Schema]
|
||||
) -> str:
|
||||
if isinstance(value, pa.Schema):
|
||||
schema, suffix = value, ""
|
||||
elif isinstance(value, pa.Field):
|
||||
schema, suffix = pa.schema([value]), ".field(0)"
|
||||
else:
|
||||
schema, suffix = pa.schema([pa.field("", value)]), ".field(0).type"
|
||||
for data_type in schema.types:
|
||||
extension = _python_extension_type(data_type)
|
||||
if extension is not None:
|
||||
raise TypeError(
|
||||
f"Function global {name!r} uses the Arrow extension type "
|
||||
f"{extension.extension_name!r}, which is defined in Python and "
|
||||
"cannot be captured. " + _CAPTURE_REMEDY
|
||||
)
|
||||
alias = self._support_module("pyarrow")
|
||||
# Schema IPC keeps nullability, metadata, and nested fields exactly.
|
||||
data = schema.serialize().to_pybytes()
|
||||
return f"{alias}.ipc.read_schema({alias}.py_buffer({data!r})){suffix}"
|
||||
|
||||
def _support_module(self, module: str) -> str:
|
||||
"""The artifact's private alias for a module that rebuilds captured
|
||||
values."""
|
||||
alias = f"_lancedb_{module}"
|
||||
if alias not in self._support_imports:
|
||||
self._require_importable(module)
|
||||
self._claim(alias, ("support", module))
|
||||
self._support_imports[alias] = f"import {module} as {alias}"
|
||||
return alias
|
||||
|
||||
def _builtin(self, name: str) -> str:
|
||||
"""A builtin called by captured source, which the artifact must not
|
||||
rebind."""
|
||||
self._claim(name, ("builtin", name))
|
||||
return name
|
||||
|
||||
def _require_importable(self, module_name: str) -> None:
|
||||
"""Warn about an import the Function's environment may not be able to
|
||||
@@ -3015,8 +3181,11 @@ def function(
|
||||
- modules, and classes and functions importable from an installed
|
||||
package, become imports; the package must be declared in ``pip`` or
|
||||
``conda``;
|
||||
- literals (``None``, ``bool``, ``int``, ``str``, ``bytes``, finite
|
||||
``float``, and tuples containing only these literals) are inlined;
|
||||
- values are copied into the source: ``None``, ``bool``, ``int``,
|
||||
``str``, ``bytes``, and finite ``float``; tuples, lists, dicts, sets,
|
||||
and frozensets of supported values; PyArrow data types, fields, and
|
||||
schemas; and NumPy arrays and scalars of ``bool``, integer,
|
||||
``float16``, ``float32``, and ``float64`` dtypes;
|
||||
- functions and classes defined in ``__main__``, such as notebook cells,
|
||||
are packaged by source, together with what they reference;
|
||||
- modules and packages listed in ``code`` are shipped as Python source and
|
||||
@@ -3034,13 +3203,27 @@ def function(
|
||||
image. Warnings follow normal Python warning filters and may be promoted
|
||||
to errors. Declare every third-party import in ``pip`` or ``conda`` even
|
||||
when it happens to be installed on the registration host.
|
||||
Other global values, including Arrow types and schemas, lists, dictionaries,
|
||||
sets, and NumPy arrays, cannot be captured as literals. Define them inside
|
||||
the function or class body instead.
|
||||
Closures, lambdas, nested definitions, mutable module-level objects, and a
|
||||
non-standard ``__builtins__`` are rejected where they can be seen and
|
||||
Closures, lambdas, nested definitions, other mutable module-level objects,
|
||||
and a non-standard ``__builtins__`` are rejected where they can be seen and
|
||||
otherwise unsupported.
|
||||
|
||||
**Captured values.** A captured value is copied when the decorator runs
|
||||
and rebuilt in every worker process. Later changes on the client do not
|
||||
reach the Function, changes a worker makes stay in that process, and
|
||||
globals that share an object on the client become separate copies.
|
||||
Dictionaries keep their insertion order and set elements are written in a
|
||||
canonical order, so the same values always package to the same source.
|
||||
Floats, including NumPy elements, must be finite. Arrow values are rebuilt
|
||||
from Arrow's IPC schema encoding, which preserves nullability, metadata,
|
||||
and nested fields; extension types defined in Python cannot be captured.
|
||||
NumPy values keep their dtype and shape and need ``numpy`` in the remote
|
||||
environment, so declare it in ``pip`` or ``conda``. Each captured value is
|
||||
limited to 1 MiB of source and 32 levels of nesting, and cannot contain
|
||||
itself. Load larger data inside the function or class body, for example
|
||||
from a table or a package resource shipped with ``code``. Define other
|
||||
values, such as instances of your own classes, inside the function or
|
||||
class body as well.
|
||||
|
||||
**Namespace restrictions.** The packaged source cannot import ``sys``,
|
||||
``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``,
|
||||
including submodules such as ``ctypes.util`` and ``importlib.metadata``.
|
||||
|
||||
@@ -9,6 +9,7 @@ import base64
|
||||
import importlib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
@@ -17,6 +18,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Optional, get_type_hints
|
||||
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
@@ -234,10 +236,15 @@ def test_function_can_return_a_list_from_a_generator_expression():
|
||||
@pytest.mark.parametrize(
|
||||
("global_value", "value_type"),
|
||||
[
|
||||
("pa.struct([('label', pa.string())])", "StructType"),
|
||||
("(1, (pa.int64(),))", "DataType"),
|
||||
("{'label': 1}", "dict"),
|
||||
("float('inf')", "float"),
|
||||
("{'label': float('nan')}", "float"),
|
||||
("[1, (2, object())]", "object"),
|
||||
("{'labels': range(2)}", "range"),
|
||||
("pa.array([1])", "Int64Array"),
|
||||
("np.array(['label'])", "ndarray with dtype <U5"),
|
||||
("np.array([1.0], dtype=np.longdouble)", "ndarray with dtype"),
|
||||
("np.datetime64('2026-01-01')", "datetime64 with dtype datetime64[D]"),
|
||||
("np.ma.masked_array([1.0])", "MaskedArray"),
|
||||
],
|
||||
)
|
||||
def test_unsupported_global_names_value_and_remedy(
|
||||
@@ -254,8 +261,8 @@ def test_unsupported_global_names_value_and_remedy(
|
||||
module = helper_package(
|
||||
"fx_unsupported_global",
|
||||
{
|
||||
"__init__.py": f"import pyarrow as pa\nCAPTURED_VALUE = {global_value}\n"
|
||||
+ definition
|
||||
"__init__.py": "import numpy as np\nimport pyarrow as pa\n"
|
||||
f"CAPTURED_VALUE = {global_value}\n" + definition
|
||||
},
|
||||
)
|
||||
with pytest.raises(TypeError) as error:
|
||||
@@ -284,6 +291,256 @@ def test_supported_nested_literal_global_still_packages(helper_package):
|
||||
assert namespace["CAPTURED_VALUE"] == module.CAPTURED_VALUE
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["function", "class"])
|
||||
def test_arrow_and_structured_globals_are_captured(helper_package, kind):
|
||||
body = (
|
||||
" if x is None:\n"
|
||||
" return (LABELS, EMPTY, ARROW, WEIGHTS, NUMPY)\n"
|
||||
" rows = [{'label': 'pick', 'score': LABELS['pick']}] * len(x)\n"
|
||||
" return pa.array(rows, type=OUT_TYPE)\n"
|
||||
)
|
||||
definition = (
|
||||
"class judge:\n def __call__(self, x: pa.Array) -> pa.Array:\n"
|
||||
+ textwrap.indent(body, " ")
|
||||
if kind == "class"
|
||||
else "def judge(x: pa.Array) -> pa.Array:\n" + body
|
||||
)
|
||||
module = helper_package(
|
||||
"fx_structured_global",
|
||||
{
|
||||
"__init__.py": textwrap.dedent("""
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
|
||||
OUT_TYPE = pa.struct(
|
||||
[pa.field("label", pa.string()), pa.field("score", pa.int32())]
|
||||
)
|
||||
LABELS = {
|
||||
"pick": 0,
|
||||
"place": 1,
|
||||
"nested": [None, (1.5, b"x"), {"deep": frozenset({"b", "a"})}],
|
||||
}
|
||||
EMPTY = ([], {}, set(), frozenset(), ())
|
||||
ARROW = {
|
||||
"field": pa.field(
|
||||
"score", pa.int32(), nullable=False, metadata={"unit": "pts"}
|
||||
),
|
||||
"schema": pa.schema(
|
||||
[pa.field("label", pa.dictionary(pa.int8(), pa.utf8(), True))],
|
||||
metadata={"version": "1"},
|
||||
),
|
||||
"tensor": pa.fixed_shape_tensor(pa.float32(), [2, 2]),
|
||||
}
|
||||
WEIGHTS = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32)
|
||||
NUMPY = (
|
||||
np.float32(0.5),
|
||||
np.True_,
|
||||
np.uint64(2**64 - 1),
|
||||
np.array(1.5),
|
||||
np.zeros((0, 3), dtype=np.int16),
|
||||
np.array([1.0, -0.0], dtype=">f8"),
|
||||
)
|
||||
""")
|
||||
+ definition
|
||||
},
|
||||
)
|
||||
out_type = module.OUT_TYPE
|
||||
packaged = function(
|
||||
input_schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]),
|
||||
output_schema=pa.field("out", out_type, nullable=False),
|
||||
)(module.judge)
|
||||
source = artifact(packaged).decode()
|
||||
assert "import numpy as _lancedb_numpy" in source
|
||||
assert "import pyarrow as _lancedb_pyarrow" in source
|
||||
|
||||
namespace = {}
|
||||
exec(compile(source, "user_function.py", "exec"), namespace)
|
||||
call = namespace["judge"]() if kind == "class" else namespace["judge"]
|
||||
result = call(pa.array([1, 2]))
|
||||
assert result.type == out_type
|
||||
assert result.to_pylist() == [{"label": "pick", "score": 0}] * 2
|
||||
assert namespace["OUT_TYPE"] == out_type
|
||||
|
||||
assert namespace["LABELS"] == module.LABELS
|
||||
assert list(namespace["LABELS"]) == list(module.LABELS)
|
||||
assert namespace["EMPTY"] == module.EMPTY
|
||||
assert [type(value) for value in namespace["EMPTY"]] == [
|
||||
type(value) for value in module.EMPTY
|
||||
]
|
||||
for key, value in module.ARROW.items():
|
||||
assert namespace["ARROW"][key].equals(value, check_metadata=True)
|
||||
assert type(namespace["ARROW"][key]) is type(value)
|
||||
|
||||
weights = namespace["WEIGHTS"]
|
||||
assert weights.dtype == module.WEIGHTS.dtype
|
||||
assert np.array_equal(weights, module.WEIGHTS)
|
||||
for captured, original in zip(namespace["NUMPY"], module.NUMPY, strict=True):
|
||||
assert type(captured) is type(original)
|
||||
assert captured.dtype == original.dtype
|
||||
assert np.shape(captured) == np.shape(original)
|
||||
assert np.array_equal(captured, original)
|
||||
assert np.signbit(namespace["NUMPY"][-1][1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["function", "class"])
|
||||
@pytest.mark.parametrize("shape", [(0,), (0, 3), (2, 0, 3), (500_000, 0)])
|
||||
def test_empty_numpy_captures_preserve_shape_without_expanding(
|
||||
helper_package, kind, shape
|
||||
):
|
||||
definition = (
|
||||
"class empty_size:\n def __call__(self, value: int) -> int:\n"
|
||||
" return value + EMPTY.size\n"
|
||||
if kind == "class"
|
||||
else "def empty_size(value: int) -> int:\n return value + EMPTY.size\n"
|
||||
)
|
||||
module = helper_package(
|
||||
"fx_empty_numpy_global",
|
||||
{
|
||||
"__init__.py": "import numpy as np\n"
|
||||
f"EMPTY = np.empty({shape!r}, dtype='>i2')\n" + definition
|
||||
},
|
||||
)
|
||||
source = artifact(function(module.empty_size))
|
||||
assert len(source) < 1024
|
||||
namespace = {}
|
||||
exec(compile(source, "user_function.py", "exec"), namespace)
|
||||
captured = namespace["EMPTY"]
|
||||
assert captured.shape == shape
|
||||
assert captured.dtype == module.EMPTY.dtype
|
||||
assert captured.size == 0
|
||||
call = namespace["empty_size"]() if kind == "class" else namespace["empty_size"]
|
||||
assert call(7) == 7
|
||||
|
||||
|
||||
def test_captured_containers_are_copied_when_decorated(helper_package):
|
||||
module = helper_package(
|
||||
"fx_captured_copy",
|
||||
{
|
||||
"__init__.py": """
|
||||
SHARED = [1, 2]
|
||||
CONFIG = {"shared": SHARED, "again": SHARED}
|
||||
|
||||
def uses_config(value: int) -> int:
|
||||
return value + len(CONFIG["shared"]) + len(SHARED)
|
||||
"""
|
||||
},
|
||||
)
|
||||
definition = function(module.uses_config)
|
||||
module.SHARED.append(3)
|
||||
|
||||
namespace = {}
|
||||
exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
|
||||
assert namespace["SHARED"] == [1, 2]
|
||||
assert namespace["CONFIG"] == {"shared": [1, 2], "again": [1, 2]}
|
||||
assert namespace["CONFIG"]["shared"] is not namespace["CONFIG"]["again"]
|
||||
assert namespace["CONFIG"]["shared"] is not namespace["SHARED"]
|
||||
assert namespace["uses_config"](1) == 5
|
||||
|
||||
|
||||
def test_captured_sets_package_deterministically(tmp_path):
|
||||
script = tmp_path / "sets.py"
|
||||
script.write_text(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
import json
|
||||
|
||||
from lancedb import function
|
||||
|
||||
WORDS = {f"word{index}" for index in range(20)}
|
||||
MIXED = frozenset({("pair", 1), b"bytes", None, 2.5, "text"})
|
||||
|
||||
@function
|
||||
def known(word: str) -> bool:
|
||||
return word in WORDS or word in MIXED
|
||||
|
||||
print(json.dumps([
|
||||
known.registration_request.artifact.digest,
|
||||
list(WORDS),
|
||||
]))
|
||||
"""
|
||||
)
|
||||
)
|
||||
runs = []
|
||||
for seed in ("0", "1", "2", "3"):
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(script)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env={**os.environ, "PYTHONHASHSEED": seed},
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
runs.append(json.loads(result.stdout))
|
||||
# Hash randomization reorders the client's set; the artifact must not change.
|
||||
assert len({tuple(order) for _, order in runs}) > 1
|
||||
assert len({digest for digest, _ in runs}) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("global_value", "message"),
|
||||
[
|
||||
("list(range(300_000))", "too large to capture"),
|
||||
("np.zeros(2_000_000)", "too large to capture"),
|
||||
("'x' * (1024 * 1024)", "too large to capture"),
|
||||
("functools.reduce(lambda inner, _: [inner], range(40), [])", "32 levels"),
|
||||
("_cycle()", "contains itself"),
|
||||
("pa.schema([pa.field('x', pa.list_(_Extension()))])", "defined in Python"),
|
||||
],
|
||||
)
|
||||
def test_captured_value_limits_name_the_global(helper_package, global_value, message):
|
||||
module = helper_package(
|
||||
"fx_captured_limits",
|
||||
{
|
||||
"__init__.py": textwrap.dedent("""
|
||||
import functools
|
||||
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
|
||||
class _Extension(pa.ExtensionType):
|
||||
def __init__(self):
|
||||
super().__init__(pa.int64(), "fx.extension")
|
||||
|
||||
def __arrow_ext_serialize__(self):
|
||||
return b""
|
||||
|
||||
@classmethod
|
||||
def __arrow_ext_deserialize__(cls, storage_type, serialized):
|
||||
return cls()
|
||||
|
||||
def _cycle():
|
||||
value = []
|
||||
value.append(value)
|
||||
return value
|
||||
""")
|
||||
+ f"CAPTURED_VALUE = {global_value}\n"
|
||||
"def uses_global(value: int) -> int:\n"
|
||||
" return value if CAPTURED_VALUE else 0\n"
|
||||
},
|
||||
)
|
||||
with pytest.raises((TypeError, ValueError)) as error:
|
||||
function(module.uses_global)
|
||||
assert "CAPTURED_VALUE" in str(error.value)
|
||||
assert message in str(error.value)
|
||||
assert "inside the function or class body" in str(error.value)
|
||||
|
||||
|
||||
def test_captured_sets_keep_their_builtins(helper_package):
|
||||
module = helper_package(
|
||||
"fx_captured_builtins",
|
||||
{
|
||||
"__init__.py": """
|
||||
STOP = frozenset({"a"})
|
||||
frozenset = ("shadowed",)
|
||||
|
||||
def uses_sets(word: str) -> bool:
|
||||
return word in STOP or word in frozenset
|
||||
"""
|
||||
},
|
||||
)
|
||||
with pytest.raises(ValueError, match="cannot package 'frozenset'"):
|
||||
function(module.uses_sets)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"])
|
||||
@pytest.mark.parametrize("kind", ["function", "class"])
|
||||
def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package):
|
||||
|
||||
Generated
+9
-9
@@ -2147,7 +2147,7 @@ requires-dist = [
|
||||
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
|
||||
{ name = "pydantic", specifier = ">=2.7.4,<3" },
|
||||
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b23" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b25" },
|
||||
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
|
||||
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
|
||||
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
|
||||
@@ -4301,7 +4301,7 @@ crypto = [
|
||||
|
||||
[[package]]
|
||||
name = "pylance"
|
||||
version = "15.0.0b23"
|
||||
version = "15.0.0b25"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
dependencies = [
|
||||
{ name = "lance-namespace" },
|
||||
@@ -4312,13 +4312,13 @@ dependencies = [
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_ldwuz/pylance-15.0.0b23-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b7980c606424e63e9be645536dbcaff75b479886a53abdae3aef64684c9a6fc4" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_5wKzE/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a6d887bc81d5f79b8a23d5cbc840cb56dbea4d8b0a9d2c2edf063dea48bcf741" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_FKuk6/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1424bd48cac2160b7745c9b87cd24d81c7cf2b0a89f342ea46ecd2a473ea74e6" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_SVglj/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:09de71b60ac6b8b91fdd73207f71c74bc521626de7e437102ebfe4f2c1f78fa0" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_SgTr6/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d9385471578bec51ae546f7bd7ea638e20bd12d687082d43ed465017dfd992e7" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_wyipY/pylance-15.0.0b23-cp310-abi3-win_amd64.whl", hash = "sha256:7b98b0d78564c5acea3693334c41dc3ced20484fb2c8e738113eeb078281a109" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1v2uEn/pylance-15.0.0b23-cp310-abi3-win_arm64.whl", hash = "sha256:0f4d2645143d44c11237e6ea00772c169a3c6ed23a7c36beaeaef9a18d1be14d" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2hpc2R/pylance-15.0.0b25-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:2a0bb8d6b0c55b7a821989759fc0f8f62cb4da621f89eae232cef49bb7ef341e" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_4LUKQ/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9b73e6e9373c4d5af3fea51e63c3e55873f470aa1a6d0412c22916f88ff5df88" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_11CcHk/pylance-15.0.0b25-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8090d403b2a38cd4ac8eb09de0327bc404cb3bc965d905f2b6a8479891273fae" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1S87Ih/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7f0a20e8ed41d3e49cd5e0bbba97d18ad684cf337e053641321404c9db34f1a1" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_13KmLJ/pylance-15.0.0b25-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:079385a6816a10d42f57bc467d9c822c7207cd31d9a6f768bbf522c0a3007229" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1bTDlQ/pylance-15.0.0b25-cp310-abi3-win_amd64.whl", hash = "sha256:d9b1d713b0d03043a3f5596e909405787f85219f54c427b14437367f0ea7acb9" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_j7adN/pylance-15.0.0b25-cp310-abi3-win_arm64.whl", hash = "sha256:4a1c18176ffd6a860c6e66b0deb39fcc9ac1434dba57ee66559b7638ad4a200a" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user