Merge branch 'merge-insert-source-stats' into merge-insert-source-stats-bindings

This commit is contained in:
Will Jones
2026-11-11 08:38:10 +00:00
90 changed files with 4502 additions and 529 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b15",
"pylance==15.0.0b16",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+30 -6
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Blob fetch API and v2 projection helpers."""
"""Blob fetch API and projection helpers."""
from __future__ import annotations
@@ -13,7 +13,11 @@ from typing import TYPE_CHECKING, Optional, Union
import pyarrow as pa
from .expr import Expr
from .schema import blob_column_paths, row_addressable_blob_v2_paths
from .schema import (
blob_column_paths,
row_addressable_blob_paths,
row_addressable_blob_v2_paths,
)
from .types import BlobMode, QueryProjection, QueryProjectionSpec
if TYPE_CHECKING:
@@ -165,6 +169,25 @@ def blob_v2_projection_sources(
return _project_blob_paths(row_addressable_blob_v2_paths(schema), projection)
def blob_projection_sources(
schema: pa.Schema,
projection: QueryProjection,
*,
include_legacy: bool = False,
) -> dict[str, str]:
"""Map projected blob outputs to row-addressable source columns.
Legacy v1 columns are included only when the caller can safely fetch them
through the same row-id path as v2.
"""
paths = (
row_addressable_blob_paths(schema)
if include_legacy
else row_addressable_blob_v2_paths(schema)
)
return _project_blob_paths(paths, projection)
def reject_unfetchable_blob_columns(
schema: pa.Schema, projection: QueryProjection, blob_sources: dict[str, str]
) -> None:
@@ -177,8 +200,9 @@ def reject_unfetchable_blob_columns(
if unfetchable:
raise ValueError(
f"blob_mode='bytes' cannot fetch blob columns {unfetchable}. Bytes are "
"fetched by row id, which covers blob v2 columns with one blob per "
"row but not legacy blob columns or blobs inside lists. Use "
"fetched by row id for legacy and v2 columns in local plain scans, "
"but not for blobs inside lists or query shapes whose result columns "
"cannot be matched back to the source. Use "
"blob_mode='descriptions' or remove these columns from the projection."
)
@@ -269,7 +293,7 @@ def finalize_blob_query_table(
return stash_auto_row_ids(tbl, blob_paths)
async def replace_v2_blob_columns_with_bytes(
async def replace_blob_columns_with_bytes(
tbl: pa.Table,
blob_sources: dict[str, str],
fetch_blobs: FetchBlobsAsync,
@@ -289,7 +313,7 @@ async def replace_v2_blob_columns_with_bytes(
return tbl
def replace_v2_blob_columns_with_bytes_sync(
def replace_blob_columns_with_bytes_sync(
tbl: pa.Table,
blob_sources: dict[str, str],
fetch_blobs: FetchBlobsSync,
+19 -1
View File
@@ -25,6 +25,7 @@ from .index import (
LabelList,
Fm,
NGram,
ZoneMap,
HnswPq,
HnswSq,
HnswFlat,
@@ -189,7 +190,10 @@ class Connection(object):
self, request_json: str, namespace_path: Optional[List[str]] = None
) -> Job: ...
async def get_function(
self, name: str, version: str, namespace_path: Optional[List[str]] = None
self,
name: str,
version: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
) -> str: ...
def list_functions(
self,
@@ -501,6 +505,8 @@ class JobDescription:
class SqlQuery:
@property
def id(self) -> UUID: ...
@property
def job_id(self) -> Optional[str]: ...
async def describe(self) -> QueryDescription: ...
async def reader(self) -> RecordBatchStream: ...
async def cancel(self) -> None: ...
@@ -509,6 +515,8 @@ class QueryDescription:
@property
def id(self) -> UUID: ...
@property
def job_id(self) -> Optional[str]: ...
@property
def status(self) -> str: ...
@property
def progress(self) -> Optional[float]: ...
@@ -549,6 +557,7 @@ class Table:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
],
replace: Optional[bool],
@@ -572,6 +581,7 @@ class Table:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
],
replace: Optional[bool],
@@ -605,6 +615,7 @@ class Table:
columns: list[tuple[str, str]],
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[int] = None,
auto_refresh_resource_budget: Optional[dict[str, int]] = None,
) -> AddColumnsResult: ...
async def add_function_columns(
self,
@@ -612,6 +623,7 @@ class Table:
output_name: Optional[str],
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[int] = None,
auto_refresh_resource_budget: Optional[dict[str, int]] = None,
) -> AddColumnsResult: ...
async def refresh_column(
self,
@@ -619,6 +631,9 @@ class Table:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -636,6 +651,9 @@ class Table:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
+40 -7
View File
@@ -140,6 +140,18 @@ def _view_description(
)
def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[str]:
if version is None:
return None
if isinstance(version, bool):
raise TypeError("version must be an int, str, or None")
if isinstance(version, int):
return str(version)
if isinstance(version, str):
return version
raise TypeError("version must be an int, str, or None")
class DBConnection(EnforceOverrides):
"""An active LanceDB connection interface.
@@ -1027,10 +1039,15 @@ class DBConnection(EnforceOverrides):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
"""Open one exact immutable Function version from the remote catalog."""
"""Open an immutable Function version from the remote catalog.
``version`` may be an integer or string. When omitted, the server
resolves the latest currently visible revision and returns that exact
immutable version.
"""
raise NotImplementedError(
_append_doc_url(
"Function catalog operations are not supported "
@@ -1515,7 +1532,10 @@ class DBConnection(EnforceOverrides):
This submits through :meth:`execute_query_async` and waits until the
initial result stream is readable. It does not wait for the full query
to finish.
to finish. A statement that ran as a server-side SQL job exposes the
durable Job Registry id in the reader schema metadata under
``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the
query handle itself is needed.
"""
return self.execute_query_async(
query,
@@ -1554,6 +1574,9 @@ class DBConnection(EnforceOverrides):
stops a directly streamed query; deferred execution requires explicit
cancellation. Open ``reader()`` directly: a streamed query needs its
reader to make progress and reports ``running`` until the stream ends.
Once a server-side SQL job exists, ``describe().job_id`` exposes its
durable Job Registry id while the query is still running. This is
separate from the connection-scoped query ``id``.
LanceDB Embedded connections do not support SQL.
"""
@@ -2313,9 +2336,10 @@ class LanceDBConnection(DBConnection):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
version = _normalize_function_version(version)
return LOOP.run(
self._conn.get_function(
name, version=version, namespace_path=namespace_path
@@ -3613,10 +3637,16 @@ class AsyncConnection(object):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
"""Open one exact immutable Function version from the remote catalog."""
"""Open an immutable Function version from the remote catalog.
``version`` may be an integer or string. When omitted, the server
resolves the latest currently visible revision and returns that exact
immutable version.
"""
version = _normalize_function_version(version)
return FunctionVersion.from_json(
await self._inner.get_function(name, version, namespace_path)
)
@@ -4137,7 +4167,10 @@ class AsyncConnection(object):
This submits through :meth:`execute_query_async` and waits until the
initial result stream is readable. It does not wait for the full query
to finish.
to finish. A statement that ran as a server-side SQL job exposes the
durable Job Registry id in the reader schema metadata under
``x-lancedb-sql-job-id``. Use :meth:`execute_query_async` when the
query handle itself is needed.
"""
submitted = await self.execute_query_async(
query,
+47 -9
View File
@@ -97,6 +97,16 @@ def _validate_batch_size(value: Any) -> Optional[int]:
return value
def _validate_max_concurrency(value: Any) -> Optional[int]:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError("max_concurrency must be an integer")
if not 1 <= value <= 2**32 - 1:
raise ValueError("max_concurrency must be between 1 and 4294967295")
return value
def _validate_row_timeout(value: Any) -> Optional[float]:
if value is None:
return None
@@ -529,9 +539,10 @@ class FunctionVersion(_RemoteValue):
``gpu_class`` is the operator-defined GPU pool fixed into this Function
version, or ``None`` when registration used the deployment default.
``batch_size``, ``row_timeout_seconds``, and ``result_stability`` retain
the execution controls reported by the catalog. They are ``None`` for
versions registered before the corresponding declaration.
``batch_size``, ``max_concurrency``, ``row_timeout_seconds``, and
``result_stability`` retain the execution controls reported by the
catalog. They are ``None`` for versions registered before the
corresponding declaration.
"""
name: str
@@ -548,6 +559,7 @@ class FunctionVersion(_RemoteValue):
disabled: bool
gpu_class: Optional[str] = None
batch_size: Optional[int] = None
max_concurrency: Optional[int] = None
row_timeout_seconds: Optional[float] = None
result_stability: Optional[str] = None
@@ -556,6 +568,11 @@ class FunctionVersion(_RemoteValue):
def _validate_batch_size(cls, value):
return _validate_batch_size(value)
@field_validator("max_concurrency", mode="before")
@classmethod
def _validate_max_concurrency(cls, value):
return _validate_max_concurrency(value)
@field_validator("row_timeout_seconds", mode="before")
@classmethod
def _validate_row_timeout(cls, value):
@@ -691,6 +708,7 @@ class FunctionRegistrationRequest(_RemoteValue):
signature: FunctionSignature
runtime: PythonRuntimeSpec
batch_size: Optional[int] = None
max_concurrency: Optional[int] = None
row_timeout_seconds: Optional[float] = None
retry_policy: Optional[FunctionRetryPolicy] = None
secret_bindings: tuple[SecretBinding, ...] = ()
@@ -701,6 +719,11 @@ class FunctionRegistrationRequest(_RemoteValue):
def _validate_batch_size(cls, value):
return _validate_batch_size(value)
@field_validator("max_concurrency", mode="before")
@classmethod
def _validate_max_concurrency(cls, value):
return _validate_max_concurrency(value)
@field_validator("row_timeout_seconds", mode="before")
@classmethod
def _validate_row_timeout(cls, value):
@@ -1428,19 +1451,21 @@ def _is_function_decorator(node: ast.expr) -> bool:
)
def _literal_source(value: Any) -> str:
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) for child in value)
children = ", ".join(_literal_source(child, name) for child in value)
if len(value) == 1:
children += ","
return f"({children})"
raise TypeError(
"Function source references an unsupported global value of type "
f"{type(value).__name__}"
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."
)
@@ -1875,7 +1900,7 @@ 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)}"
return f"{name} = {_literal_source(value, name)}"
def _require_importable(self, module_name: str) -> None:
"""Warn about an import the Function's environment may not be able to
@@ -2161,6 +2186,7 @@ class FunctionDefinition:
env: Mapping[str, str],
python_version: Optional[str],
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
row_timeout_seconds: Optional[float] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
gpu: bool = False,
@@ -2308,6 +2334,7 @@ class FunctionDefinition:
signature=signature,
runtime=runtime,
batch_size=batch_size,
max_concurrency=max_concurrency,
row_timeout_seconds=row_timeout_seconds,
retry_policy=retry_policy,
models=models,
@@ -2406,6 +2433,7 @@ def function(
env: Optional[Mapping[str, str]] = None,
python_version: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
row_timeout_seconds: Optional[float] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
gpu: bool = False,
@@ -2429,6 +2457,7 @@ def function(
env: Optional[Mapping[str, str]] = None,
python_version: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
row_timeout_seconds: Optional[float] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
gpu: bool = False,
@@ -2486,8 +2515,8 @@ 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``, booleans, numbers, strings, bytes, tuples of them)
are inlined;
- literals (``None``, ``bool``, ``int``, ``str``, ``bytes``, finite
``float``, and tuples containing only these literals) are inlined;
- 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
@@ -2505,6 +2534,9 @@ 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, code that reaches the module namespace another way
(``globals()``/``eval``, ``sys.modules``, ``builtins``), and a
@@ -2559,6 +2591,11 @@ def function(
Maximum number of input rows supplied in one execution batch. Must be
between 1 and 4294967295. Remote execution may use smaller batches.
When omitted, the service chooses the batch size adaptively.
max_concurrency : int, optional
Maximum user-code calls in flight for one Function within one logical
execution. Must be between 1 and 4294967295. A refresh can override
this default for that execution only. Omitting it preserves the
existing behavior. This is not an account-wide quota.
row_timeout_seconds : float, optional
Positive, finite deadline in seconds for each Python call: one row for
scalar Functions and one batch for vectorized Functions. This does not
@@ -2695,6 +2732,7 @@ def function(
env={} if env is None else env,
python_version=python_version,
batch_size=batch_size,
max_concurrency=max_concurrency,
row_timeout_seconds=row_timeout_seconds,
retry_policy=retry_policy,
gpu=gpu,
+17
View File
@@ -130,6 +130,23 @@ class NGram:
pass
@dataclass
class ZoneMap:
"""Describe a ZoneMap index configuration.
A `ZoneMap` index stores compact min and max summaries for contiguous
ranges (zones) of rows. During a scan it skips any zone whose summary
cannot satisfy the predicate, so it accelerates range and equality
filters such as `col > 10`, `col BETWEEN a AND b`, and `col = x`,
without changing the results.
It suits large numeric or temporal columns whose values are correlated
with row order (for example `timestamp`, `price`, `id`).
"""
pass
@dataclass
class FTS:
"""Describe a FTS index configuration.
+21 -15
View File
@@ -4,7 +4,7 @@
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
import asyncio
import json
import reprlib
import time
from datetime import timedelta
from typing import Any, Callable, Generic, Optional, TypeVar, cast
@@ -461,43 +461,49 @@ class AsyncJob(Generic[T]):
_REPR_INDENT = " " * 4
_REPR_MAX_FIELD_LENGTH = 240
_PAYLOAD_REPR = reprlib.Repr()
_PAYLOAD_REPR.maxlevel = 2
_PAYLOAD_REPR.maxdict = 4
_PAYLOAD_REPR.maxlist = 4
_PAYLOAD_REPR.maxtuple = 4
_PAYLOAD_REPR.maxstring = 120
_PAYLOAD_REPR.maxother = 120
def _repr_payload(value: Any) -> str:
"""Render a job payload as indented JSON, aligned under its field."""
try:
rendered = json.dumps(value, indent=4)
except TypeError:
return repr(value)
return rendered.replace("\n", "\n" + _REPR_INDENT)
"""Bound nested payload previews without changing the stored values."""
rendered = _PAYLOAD_REPR.repr(value).replace("\n", "\\n")
if len(rendered) > _REPR_MAX_FIELD_LENGTH:
return rendered[: _REPR_MAX_FIELD_LENGTH - 3] + "..."
return rendered
def _job_repr(kind: str, job: Any) -> str:
"""Render every field the handle currently knows, omitting the rest.
"""Show cached job identity and bounded previews without backend calls.
One field per line, with the JSON payloads indented, because a refresh
job's spec and result are the point of printing it.
The complete payloads remain available through ``spec`` and ``result``.
"""
state = job.state
if state is None:
# Nothing has been fetched yet, so there is nothing to lay out.
known = f"id={job.id!r}, " if job.id is not None else ""
known = f"id={_repr_payload(job.id)}, " if job.id is not None else ""
return f"{kind}({known}not refreshed)"
fields = []
if job.id is not None:
fields.append(f"id={job.id!r}")
fields.append(f"state={state!r}")
fields.append(f"id={_repr_payload(job.id)}")
fields.append(f"state={_repr_payload(state)}")
for name in ("job_type", "creation_ms"):
value = getattr(job, name)
if value is not None:
fields.append(f"{name}={value!r}")
fields.append(f"{name}={_repr_payload(value)}")
for name in ("spec", "result"):
value = getattr(job, name)
if value is not None:
fields.append(f"{name}={_repr_payload(value)}")
if job.failure is not None:
fields.append(f"failure={job.failure!r}")
fields.append(f"failure={_repr_payload(job.failure)}")
body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields)
return f"{kind}({body}\n)"
+187 -77
View File
@@ -48,12 +48,13 @@ from ._blob import (
FetchBlobsAsync,
FetchBlobsSync,
blob_auto_row_id_for_scan,
blob_projection_sources,
blob_v2_projection_sources,
finalize_blob_query_table,
reject_unfetchable_blob_columns,
reject_unmatched_blob_outputs,
replace_v2_blob_columns_with_bytes,
replace_v2_blob_columns_with_bytes_sync,
replace_blob_columns_with_bytes,
replace_blob_columns_with_bytes_sync,
strip_auto_row_ids,
validate_blob_mode,
)
@@ -206,7 +207,10 @@ def _blob_bytes_without_snapshot_error() -> NotImplementedError:
"blob_mode='bytes' cannot safely materialize blob columns without a "
"stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown "
"run the query on a server, so the blob fetch could read another table "
"version. Use blob_mode='descriptions'."
"version. Use blob_mode='descriptions' to inspect descriptors. To read "
"payloads, select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
"row_ids). Keep the source unchanged between selection and fetching."
)
@@ -242,6 +246,17 @@ def _query_is_plain_scan(query: Query) -> bool:
)
def _query_is_plain_blob_scan(query: Query) -> bool:
"""Whether native batch conversion can preserve this query's row result."""
return (
query.vector is None
and query.full_text_query is None
and query.take_offsets is None
and query.take_row_ids is None
and not query.postfilter
)
def _filter_to_sql(filter: Optional[Union[str, Expr]]) -> Optional[str]:
if filter is None:
return None
@@ -418,7 +433,7 @@ def _finish_plain_scan_pandas(
) -> pd.DataFrame:
if blob_sources:
tbl = _scanner_to_table(scanner)
tbl = replace_v2_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
tbl = replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
if strip_auto_row_id and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
if flatten is not None:
@@ -453,7 +468,10 @@ def _finish_remote_pandas(
raise NotImplementedError(
f"remote to_pandas(blob_mode={blob_mode!r}) cannot safely materialize "
"blob columns without a stable table snapshot; "
"use blob_mode='descriptions'"
"use blob_mode='descriptions' to inspect descriptors. To read payloads, "
"select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
"row_ids). Keep the source unchanged between selection and fetching."
)
@@ -469,7 +487,7 @@ async def _finish_plain_scan_pandas_async(
) -> pd.DataFrame:
if blob_sources:
tbl = _scanner_to_table(scanner)
tbl = await replace_v2_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
tbl = await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
if strip_auto_row_id and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
if flatten is not None:
@@ -1275,10 +1293,10 @@ class LanceQueryBuilder(ABC):
blob_mode: str, default "lazy"
Controls how blob columns are returned. Local blob v2 queries support
``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
mode and for legacy blob columns. Other local blob v2
queries return descriptors in ``"lazy"`` and ``"descriptions"``
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
plain scans also support ``"bytes"`` for row-addressable legacy blob
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
@@ -1346,8 +1364,8 @@ class LanceQueryBuilder(ABC):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
"""
raise NotImplementedError
@@ -1364,7 +1382,7 @@ class LanceQueryBuilder(ABC):
Execute the query and return the results as a pyarrow
[RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html)
For v2 blob projections, the default ``blob_mode="lazy"`` keeps the
For blob v2 projections, the default ``blob_mode="lazy"`` keeps the
auto ``_rowid`` column visible so batch consumers can call
``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide
automatic row ids.
@@ -1384,10 +1402,11 @@ class LanceQueryBuilder(ABC):
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
payloads one batch at a time, without requiring pylance. Bytes mode
has the same restrictions as :meth:`to_arrow`.
``"lazy"`` keeps blob v2 descriptors and auto row ids for manual
fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches
supported row-addressable blob payloads one batch at a time, without
requiring pylance. Bytes mode has the same restrictions as
:meth:`to_arrow`.
Examples
--------
@@ -1593,20 +1612,41 @@ class LanceQueryBuilder(ABC):
def _scan_needs_row_id(self) -> bool:
return self._user_requested_row_id() or self._blob_auto_row_id_enabled()
def _query_for_scan(self) -> Query:
def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query:
query = self.to_query_object()
if self._scan_needs_row_id():
if self._scan_needs_row_id() or blob_sources:
query.with_row_id = True
return query
def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes":
return False
try:
query = self.to_query_object()
except NotImplementedError:
return False
return (
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
self._table._table,
getattr(self._table, "_pushdown_operations", ()),
)
)
def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
"""Map projected blob v2 outputs to their source columns.
"""Map projected blob outputs to their source columns.
Bytes mode is checked here, before the query runs.
"""
validate_blob_mode(blob_mode)
schema = self._table.schema
blob_sources = blob_v2_projection_sources(schema, self._columns)
blob_sources = blob_projection_sources(
schema,
self._columns,
include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, self._columns, blob_sources)
@@ -1627,7 +1667,7 @@ class LanceQueryBuilder(ABC):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return replace_v2_blob_columns_with_bytes_sync(
return replace_blob_columns_with_bytes_sync(
tbl, blob_sources, self._table.fetch_blobs
)
@@ -1639,18 +1679,23 @@ class LanceQueryBuilder(ABC):
blob_sources: dict[str, str],
) -> pa.Table:
blob_auto_row_id = self._blob_auto_row_id_enabled()
finalized = finalize_blob_query_table(
tbl,
user_requested_row_id=self._user_requested_row_id(),
blob_auto_row_id=blob_auto_row_id,
blob_paths=blob_sources.keys() if blob_auto_row_id else (),
)
if blob_mode == "bytes" and blob_sources:
# Bytes conversion reads _rowid directly, including when the
# projection mixes legacy and v2 columns.
finalized = tbl
else:
finalized = finalize_blob_query_table(
tbl,
user_requested_row_id=self._user_requested_row_id(),
blob_auto_row_id=blob_auto_row_id,
blob_paths=blob_sources.keys() if blob_auto_row_id else (),
)
finalized = self._apply_arrow_blob_mode(finalized, blob_mode, blob_sources)
# with_row_id(False) does not reach the scan, which adds _rowid anyway.
# Lazy keeps it because fetch_blobs(hits) reads it there.
if (
blob_mode != "lazy"
and self._with_row_id is False
and not self._user_requested_row_id()
and "_rowid" in finalized.column_names
):
finalized = finalized.drop_columns(["_rowid"])
@@ -1890,18 +1935,29 @@ class LanceQueryBuilder(ABC):
query = self.to_query_object()
if not _query_is_plain_scan(query):
return None
blob_sources = (
blob_projection_sources(
self._table.schema,
query.columns,
include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode == "bytes"
else {}
)
# Remote and in-memory tables have no Lance dataset to scan.
if not self._table._table._inner._is_native() or (
get_uri_scheme(self._table._dataset_path) == "memory"
):
return None
# Blob v2 payloads and descriptions use LanceDB's native fetch path.
# Only lazy handles, legacy blobs, and scanner-only options need pylance.
if (
blob_mode != "lazy"
and not _query_needs_lance_scanner(self)
and blob_v2_projection_sources(self._table.schema, query.columns)
# Bytes conversions use LanceDB's fetch path for both blob versions.
# Descriptions for v2 do too; lazy handles still need the scanner.
if not _query_needs_lance_scanner(self) and (
(blob_mode == "bytes" and blob_sources)
or (
blob_mode == "descriptions"
and blob_v2_projection_sources(self._table.schema, query.columns)
)
):
return None
try:
@@ -1909,12 +1965,7 @@ class LanceQueryBuilder(ABC):
except ImportError as err:
raise _unsupported_blob_pandas_error(str(err)) from err
blob_auto_row_id = self._blob_auto_row_id_enabled()
blob_sources = (
blob_v2_projection_sources(self._table.schema, query.columns)
if blob_mode == "bytes"
else {}
)
if blob_sources:
if blob_mode == "bytes":
reject_unfetchable_blob_columns(
self._table.schema, query.columns, blob_sources
)
@@ -2248,8 +2299,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
"""
blob_sources = self._validated_blob_sources(blob_mode)
return self._finalize_blob_query_table(
@@ -2327,7 +2378,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
vector = self._query if isinstance(self._query, list) else self._query.tolist()
if isinstance(vector[0], np.ndarray):
vector = [v.tolist() for v in vector]
query = self._query_for_scan()
query = self._query_for_scan(blob_sources)
result_set = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
)
@@ -2545,7 +2596,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
blob_sources = self._validated_blob_sources(blob_mode)
self._table._ensure_no_legacy_fts_index()
query = self._query_for_scan()
query = self._query_for_scan(blob_sources)
results = self._table._execute_query(query, timeout=timeout).read_all()
if self._reranker is not None:
results = self._reranker.rerank_fts(self._query, results)
@@ -2591,6 +2642,8 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
blob_mode: BlobMode = "lazy",
) -> pa.Table:
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all()
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
@@ -2624,7 +2677,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
blob_sources = self._validated_blob_sources(blob_mode)
query = self._query_for_scan()
query = self._query_for_scan(blob_sources)
reader = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
)
@@ -3495,6 +3548,22 @@ class AsyncQueryBase(object):
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
self._inner.with_row_id()
async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes" or self._table is None:
return False
try:
query = self.to_query_object()
except NotImplementedError:
return False
return (
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
self._table, self._table._pushdown_operations
)
)
def select(self, columns: Union[List[str], dict[str, str]]) -> Self:
"""
Return only the specified columns.
@@ -3602,10 +3671,11 @@ class AsyncQueryBase(object):
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
payloads one batch at a time, without requiring pylance. Bytes mode
has the same restrictions as :meth:`to_arrow`.
``"lazy"`` keeps blob v2 descriptors and auto row ids for manual
fetches. ``"descriptions"`` omits auto row ids. ``"bytes"`` fetches
supported row-addressable blob payloads one batch at a time, without
requiring pylance. Bytes mode has the same restrictions as
:meth:`to_arrow`.
Examples
--------
@@ -3614,13 +3684,16 @@ class AsyncQueryBase(object):
"""
blob_sources = await self._validated_blob_sources(blob_mode)
reader = await self._execute_batches(
max_batch_length=max_batch_length, timeout=timeout
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
)
if blob_mode == "lazy":
return reader
async def convert(tbl: pa.Table) -> pa.Table:
tbl = self._finalize_blob_query_table(tbl)
if not (blob_mode == "bytes" and blob_sources):
tbl = self._finalize_blob_query_table(tbl)
tbl = await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
if not self._user_requested_row_id() and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
@@ -3641,7 +3714,24 @@ class AsyncQueryBase(object):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
if (
blob_sources
and not self._user_requested_row_id()
and await self._can_fetch_plain_legacy_blobs("bytes")
):
# Build a separate query so the hidden row id needed for byte
# conversion cannot leak into later executions of this builder.
query = self.to_query_object()
query.with_row_id = True
if self._table is None:
raise RuntimeError("blob query is not bound to a table")
row_id_query = self._table._sync_query_to_async(query)
return await row_id_query._execute_batches(
max_batch_length=max_batch_length,
timeout=timeout,
)
await self._maybe_add_blob_row_id()
return AsyncRecordBatchReader(
await self._inner.execute(
@@ -3658,7 +3748,7 @@ class AsyncQueryBase(object):
return await self._inner.output_schema()
async def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
"""Map projected blob v2 outputs to their source columns.
"""Map projected blob outputs to their source columns.
Bytes mode is checked here, before the query runs.
"""
@@ -3668,7 +3758,11 @@ class AsyncQueryBase(object):
return {}
schema = await self._table.schema()
projection = _query_request_projection(self._inner.to_query_request())
blob_sources = blob_v2_projection_sources(schema, projection)
blob_sources = blob_projection_sources(
schema,
projection,
include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, projection, blob_sources)
@@ -3689,7 +3783,7 @@ class AsyncQueryBase(object):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return await replace_v2_blob_columns_with_bytes(
return await replace_blob_columns_with_bytes(
tbl, blob_sources, self._table.fetch_blobs
)
@@ -3715,11 +3809,14 @@ class AsyncQueryBase(object):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``.
"""
blob_sources = await self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode)
return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
batch_iter = await self.to_batches(timeout=timeout)
tbl = self._finalize_blob_query_table(
pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema)
@@ -3792,10 +3889,10 @@ class AsyncQueryBase(object):
blob_mode: str, default "lazy"
Controls how blob columns are returned. Local blob v2 queries support
``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
mode and for legacy blob columns. Other local blob v2
queries return descriptors in ``"lazy"`` and ``"descriptions"``
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
plain scans also support ``"bytes"`` for row-addressable legacy blob
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
@@ -3873,21 +3970,27 @@ class AsyncQueryBase(object):
with_row_id=self._with_row_id,
)
blob_sources = (
blob_v2_projection_sources(schema, query.columns)
blob_projection_sources(
schema,
query.columns,
include_legacy=await self._can_fetch_plain_legacy_blobs(blob_mode),
)
if blob_mode == "bytes"
else {}
)
if blob_sources:
if blob_mode == "bytes":
reject_unfetchable_blob_columns(schema, query.columns, blob_sources)
# Remote and in-memory tables have no Lance dataset to scan.
if not self._table._inner._is_native() or (
get_uri_scheme(await self._table.uri()) == "memory"
):
return None
if (
blob_mode != "lazy"
and not _query_needs_lance_scanner(self)
and blob_v2_projection_sources(schema, query.columns)
if not _query_needs_lance_scanner(self) and (
(blob_mode == "bytes" and blob_sources)
or (
blob_mode == "descriptions"
and blob_v2_projection_sources(schema, query.columns)
)
):
return None
try:
@@ -4398,8 +4501,11 @@ class AsyncFTSQuery(AsyncStandardQuery):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(timeout=timeout)
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
results = self._reranker.rerank_fts(self.get_query(), results)
@@ -4722,8 +4828,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(timeout=timeout)
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
results = self._reranker.rerank_vector(self._query_string, results)
@@ -4851,11 +4960,14 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
# WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s.
return await _wal_hybrid.with_pk_fallback_async(
lambda: self._run_hybrid(
max_batch_length=max_batch_length, timeout=timeout
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
),
self._table,
fused=lambda: self._pk_fusion is not None,
@@ -4867,19 +4979,18 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
fts_query, vec_query, limit, offset = await self._create_child_queries()
req = fts_query._inner.to_query_request()
blob_auto_row_id = False
blob_auto_row_id = bool(blob_sources)
blob_paths: tuple[str, ...] = ()
if self._table is not None:
schema = await self._table.schema()
projection = _query_request_projection(req)
blob_auto_row_id = blob_auto_row_id_for_scan(
schema,
projection,
with_row_id=self._with_row_id,
blob_auto_row_id = blob_auto_row_id or blob_auto_row_id_for_scan(
schema, projection, with_row_id=self._with_row_id
)
if blob_auto_row_id:
blob_paths = tuple(
@@ -5176,8 +5287,7 @@ class BaseQueryBuilder(object):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` is not supported for remote or pushdown blob queries.
"""
return LOOP.run(self._inner.to_arrow(timeout, blob_mode=blob_mode))
+3 -2
View File
@@ -37,7 +37,7 @@ import pyarrow as pa
from ..common import DATA
from lancedb.listing import Listing, NamespaceListing, TableListing
from ..db import DBConnection, LOOP
from ..db import DBConnection, LOOP, _normalize_function_version
from ..functions import FunctionVersion, FunctionDefinition
from ..graph import EdgeTable, NodeTable, PropertyGraph
from ..job import AsyncJob, Job
@@ -985,9 +985,10 @@ class RemoteDBConnection(DBConnection):
self,
name: str,
*,
version: str,
version: Optional[Union[int, str]] = None,
namespace_path: Optional[List[str]] = None,
) -> FunctionVersion:
version = _normalize_function_version(version)
return LOOP.run(
self._conn.get_function(
name, version=version, namespace_path=namespace_path
+14
View File
@@ -1127,6 +1127,7 @@ class RemoteTable(Table):
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
) -> AddColumnsResult:
return LOOP.run(
self._table.add_columns(
@@ -1134,6 +1135,7 @@ class RemoteTable(Table):
computed=computed,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
auto_refresh_resource_budget=auto_refresh_resource_budget,
)
)
@@ -1143,6 +1145,9 @@ class RemoteTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1159,6 +1164,9 @@ class RemoteTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1178,6 +1186,9 @@ class RemoteTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1195,6 +1206,9 @@ class RemoteTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
+9
View File
@@ -122,6 +122,15 @@ def blob_v2_column_paths(schema: pa.Schema) -> list[str]:
return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)]
def row_addressable_blob_paths(schema: pa.Schema) -> list[str]:
"""Blob v1 and v2 paths with one blob addressable by table row id."""
return [
path
for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_like_field)
if not has_list_ancestor
]
def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]:
"""Blob v2 paths with one blob addressable by table row id.
+30 -2
View File
@@ -104,6 +104,15 @@ class AsyncQuery:
"""The stable identifier scoped to the connection that submitted it."""
return self._inner.id
@property
def job_id(self) -> Optional[str]:
"""The durable Job Registry id once the server reports this query as a job.
A running query reports it after :meth:`describe` observes the latest
server status. This is separate from the connection-scoped ``id``.
"""
return self._inner.job_id
async def describe(self) -> QueryDescription:
"""Get a point-in-time description of the query."""
return await self._inner.describe()
@@ -118,7 +127,12 @@ class AsyncQuery:
return AsyncRecordBatchReader(await self._inner.reader())
async def cancel(self) -> None:
"""Request cancellation of the query."""
"""Request cancellation of this query's Flight execution.
A durable server-side job may reject this operation because its Flight
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
with ``job_id`` to cancel that job.
"""
await self._inner.cancel()
@@ -133,6 +147,15 @@ class Query:
"""The stable identifier scoped to the connection that submitted it."""
return self._inner.id
@property
def job_id(self) -> Optional[str]:
"""The durable Job Registry id once the server reports this query as a job.
A running query reports it after :meth:`describe` observes the latest
server status. This is separate from the connection-scoped ``id``.
"""
return self._inner.job_id
def describe(self) -> QueryDescription:
"""Get a point-in-time description of the query."""
return LOOP.run(self._inner.describe())
@@ -159,7 +182,12 @@ class Query:
return pa.RecordBatchReader.from_batches(reader.schema, batches())
def cancel(self) -> None:
"""Request cancellation of the query."""
"""Request cancellation of this query's Flight execution.
A durable server-side job may reject this operation because its Flight
waiter cannot cancel the registry job. Use ``connection.cancel_job()``
with ``job_id`` to cancel that job.
"""
LOOP.run(self._inner.cancel())
+176 -28
View File
@@ -75,6 +75,7 @@ from .index import (
LabelList,
Fm,
NGram,
ZoneMap,
HnswPq,
HnswSq,
HnswFlat,
@@ -300,6 +301,7 @@ IndexConfigType = Union[
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
]
@@ -1587,8 +1589,8 @@ class Table(ABC):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
Returns
-------
@@ -1907,7 +1909,7 @@ class Table(ABC):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
@@ -2624,6 +2626,12 @@ class Table(ABC):
bytes. The client splits requests automatically and reads an individual
larger blob through the Range route. This method still materializes all
bytes in memory; for large values use :meth:`fetch_blob_files`.
The returned Arrow ``large_binary`` array contains payload bytes, not
SQL/query descriptor dictionaries. Use ``.to_pylist()`` to obtain
Python ``bytes`` or ``None`` values for copying into a blob column.
Select row IDs with ``search().with_row_id(True)`` first. Selection and
fetching are separate requests: keep the source unchanged between them.
"""
@abstractmethod
@@ -3077,6 +3085,7 @@ class Table(ABC):
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
):
"""
Add new columns with defined values.
@@ -3145,6 +3154,12 @@ class Table(ABC):
When omitted, the server determines when to refresh. Applies to every
computed output in this call.
Scheduling options require computed or Function columns.
auto_refresh_resource_budget: dict[str, int], optional
Aggregate CPU, memory, and GPU budget for automatic refreshes of a
registered Function declaration. ``cpu_millis`` and
``memory_bytes`` are required; ``gpu_count`` defaults to zero.
This option cannot be used with SQL-expression columns. LanceDB
Enterprise only.
Returns
-------
@@ -3178,6 +3193,9 @@ class Table(ABC):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3216,15 +3234,35 @@ class Table(ABC):
Maximum rows per Function call on the remote server. Must be
greater than zero. None uses the server default. Has no effect on
local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -3244,7 +3282,8 @@ class Table(ABC):
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -3263,6 +3302,9 @@ class Table(ABC):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3300,15 +3342,35 @@ class Table(ABC):
greater than zero. None uses the server default. Lower this for
slow Functions to stay within the executor's per-call deadline.
Has no effect on local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -3328,7 +3390,8 @@ class Table(ABC):
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -4118,7 +4181,7 @@ class LanceTable(Table):
):
return self.to_arrow().to_pandas(**kwargs)
if blob_mode == "bytes" and blob_v2_column_paths(self.schema):
if blob_mode == "bytes" and schema_has_blob_field(self.schema):
return self.search().to_pandas(blob_mode=blob_mode, **kwargs)
return self.to_lance().to_pandas(blob_mode=blob_mode, **kwargs)
@@ -4131,8 +4194,8 @@ class LanceTable(Table):
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
Returns
-------
@@ -4271,7 +4334,7 @@ class LanceTable(Table):
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, NGram, FTS.
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
@@ -5426,6 +5489,7 @@ class LanceTable(Table):
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
) -> AddColumnsResult:
return LOOP.run(
self._table.add_columns(
@@ -5433,6 +5497,7 @@ class LanceTable(Table):
computed=computed,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
auto_refresh_resource_budget=auto_refresh_resource_budget,
)
)
@@ -5442,6 +5507,9 @@ class LanceTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5461,6 +5529,9 @@ class LanceTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5480,6 +5551,9 @@ class LanceTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5501,6 +5575,9 @@ class LanceTable(Table):
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -6590,7 +6667,7 @@ class AsyncTable:
if blob_mode == "lazy" and get_uri_scheme(await self.uri()) == "memory":
return (await self.to_arrow()).to_pandas(**kwargs)
if blob_mode == "bytes" and blob_v2_column_paths(schema):
if blob_mode == "bytes" and schema_has_blob_field(schema):
return await self.query().to_pandas(blob_mode=blob_mode, **kwargs)
return (await self.to_lance()).to_pandas(blob_mode=blob_mode, **kwargs)
@@ -6602,8 +6679,8 @@ class AsyncTable:
blob_mode: str, default "lazy"
``"lazy"`` returns blob v2 descriptors that carry the row id
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
Returns
-------
@@ -6644,6 +6721,7 @@ class AsyncTable:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
]
] = None,
@@ -6720,12 +6798,13 @@ class AsyncTable:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
),
):
raise TypeError(
"config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq,"
" BTree, Bitmap, LabelList, Fm, NGram, or FTS, but got "
" BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, or FTS, but got "
+ str(type(config))
)
try:
@@ -6764,6 +6843,7 @@ class AsyncTable:
LabelList,
Fm,
NGram,
ZoneMap,
FTS,
]
] = None,
@@ -7407,7 +7487,10 @@ class AsyncTable:
if query.offset is not None:
async_query = async_query.offset(query.offset)
if query.columns:
async_query = async_query.select(query.columns)
columns = query.columns
if isinstance(columns, list) and columns and isinstance(columns[0], tuple):
columns = dict(columns)
async_query = async_query.select(columns)
if query.filter is not None:
async_query = async_query.where(query.filter)
if query.fast_search:
@@ -7703,6 +7786,7 @@ class AsyncTable:
computed: dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
auto_refresh_resource_budget: Optional[Dict[str, int]] = None,
) -> AddColumnsResult:
"""
Add new columns with defined values.
@@ -7769,6 +7853,12 @@ class AsyncTable:
not force recomputation. Applies to every declared computed output.
These options cannot be used with one-time transforms or ordinary
all-null columns.
auto_refresh_resource_budget: dict[str, int], optional
Aggregate CPU, memory, and GPU budget for automatic refreshes of
registered Function outputs. ``cpu_millis`` and ``memory_bytes``
are required; ``gpu_count`` defaults to zero. SQL-expression
columns do not use Function workers and reject this option.
LanceDB Enterprise only.
Examples
--------
@@ -7797,6 +7887,7 @@ class AsyncTable:
options_supplied = (
auto_refresh_enabled is not None
or auto_refresh_interval_seconds is not None
or auto_refresh_resource_budget is not None
)
function_application = None
function_output_name = None
@@ -7825,6 +7916,7 @@ class AsyncTable:
function_output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
)
if isinstance(transforms, pa.Field):
@@ -7845,6 +7937,7 @@ class AsyncTable:
list(computed.items()),
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
)
if options_supplied:
raise ValueError(
@@ -7866,6 +7959,9 @@ class AsyncTable:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -7904,15 +8000,35 @@ class AsyncTable:
Maximum rows per Function call on the remote server. Must be
greater than zero. None uses the server default. Has no effect on
local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -7932,7 +8048,8 @@ class AsyncTable:
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -7946,6 +8063,9 @@ class AsyncTable:
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8055,6 +8175,9 @@ class AsyncTable:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8092,15 +8215,35 @@ class AsyncTable:
greater than zero. None uses the server default. Lower this for
slow Functions to stay within the executor's per-call deadline.
Has no effect on local expression-backed columns.
max_concurrency: int, optional
Override the registered Function's maximum concurrent user-code
calls for this logical execution. Must be between 1 and
4294967295. None uses the registration default. This is not an
account-wide quota. LanceDB Enterprise only; local refreshes
reject this option.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
resource_budget: dict[str, int], optional
Aggregate resources for one registered Function refresh. The
``cpu_millis`` and ``memory_bytes`` keys are required;
``gpu_count`` is optional and defaults to zero, which requests a
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
None keeps the Function's registered class or the deployment
default. LanceDB Enterprise only.
gpu_count: int, optional
Positive aggregate GPU budget for Function workers. None leaves
the server's configured budget unchanged. LanceDB Enterprise
only.
Positive aggregate GPU budget for Function workers without changing
the deployment's CPU and memory defaults. None leaves the server's
configured budget unchanged. For a complete CPU and memory budget,
use ``resource_budget`` instead. LanceDB Enterprise only.
retry_policy: FunctionRetryPolicy, optional
Override retries of failed user-code calls. Only use when repeating
partial work is safe. Set max_attempts=1 to disable retries.
@@ -8120,7 +8263,8 @@ class AsyncTable:
Deadline for Function initialization. LanceDB Enterprise only.
num_workers: int, optional
Worker count for an expression column; registered Function
columns reject it. LanceDB Enterprise only.
columns reject it and use ``resource_budget`` instead. LanceDB
Enterprise only.
max_executor_processes_per_worker: int, optional
Cap on executor processes per Function worker. LanceDB
Enterprise only.
@@ -8151,6 +8295,9 @@ class AsyncTable:
column,
where=where,
batch_size=batch_size,
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8708,6 +8855,7 @@ class IndexStatistics:
"BITMAP",
"LABEL_LIST",
"NGRAM",
"ZONEMAP",
]
distance_type: Optional[Literal["l2", "cosine", "dot"]] = None
num_indices: Optional[int] = None
+63 -4
View File
@@ -1070,8 +1070,10 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path):
)
table.add([{"id": 1, "image": b"one"}])
with pytest.raises(NotImplementedError, match="stable table snapshot"):
with pytest.raises(NotImplementedError, match="stable table snapshot") as exc:
table.to_arrow(blob_mode="bytes")
assert "fetch_blobs(column, row_ids)" in str(exc.value)
assert "with_row_id(True)" in str(exc.value)
with pytest.raises(NotImplementedError, match="stable table snapshot"):
table.search().to_list(blob_mode="bytes")
with pytest.raises(NotImplementedError, match="stable table snapshot"):
@@ -1103,6 +1105,36 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path)
await table.query().to_batches(blob_mode="bytes")
def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
db = lancedb.connect(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
rows = [
{"id": 1, "image": b"one"},
{"id": 2, "image": b""},
{"id": 3, "image": None},
{"id": 4, "image": b"excluded"},
]
source = db.create_table("source", data=rows, schema=schema)
hits = (
source.search()
.where("id < 4")
.select(["id"])
.with_row_id(True)
.limit(100)
.to_arrow()
)
payloads = source.fetch_blobs("image", hits["_rowid"]).to_pylist()
subset = db.create_table("subset", schema=schema)
subset.add(
[
{"id": image_id, "image": payload}
for image_id, payload in zip(hits["id"].to_pylist(), payloads, strict=True)
]
)
copied = subset.search().to_list(blob_mode="bytes")
assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
def test_fetch_blobs_round_trip():
table = _blob_table(
"round_trip",
@@ -1619,16 +1651,41 @@ def test_bytes_mode_rejects_blobs_inside_lists():
def test_row_addressable_paths_exclude_list_children():
from lancedb.schema import row_addressable_blob_v2_paths
from lancedb.schema import (
row_addressable_blob_paths,
row_addressable_blob_v2_paths,
)
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("info", pa.struct([lancedb.blob("blob")])),
pa.field(
"info",
pa.struct(
[
lancedb.blob("blob"),
pa.field(
"legacy",
pa.large_binary(),
metadata={"lance-encoding:blob": "true"},
),
]
),
),
pa.field(
"legacy",
pa.large_binary(),
metadata={"lance-encoding:blob": "true"},
),
pa.field("images", pa.list_(lancedb.blob("image"))),
]
)
assert blob_v2_column_paths(schema) == ["info.blob", "images.image"]
assert row_addressable_blob_paths(schema) == [
"info.blob",
"info.legacy",
"legacy",
]
assert row_addressable_blob_v2_paths(schema) == ["info.blob"]
@@ -2293,6 +2350,8 @@ async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch):
if blob_mode != "lazy":
assert "_rowid" not in reader.schema.names
assert "_lance_row_id" not in str(reader.schema)
else:
assert "_rowid" in reader.schema.names
class _KeepAllScoresReranker(Reranker):
@@ -2336,7 +2395,7 @@ def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
.rerank(_KeepAllScoresReranker())
)
with pytest.raises(ValueError, match=r"\['blob'\].*legacy blob columns"):
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
query.to_arrow(blob_mode="bytes")
@@ -8,12 +8,7 @@ import textwrap
import pytest
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
def test_blob_query_without_pylance(tmp_path, api, result):
if result == "pandas":
pytest.importorskip("pandas")
script = """\
_WITHOUT_LANCE = """\
import importlib.abc
import sys
@@ -23,7 +18,15 @@ class MissingLance(importlib.abc.MetaPathFinder):
raise ModuleNotFoundError(fullname, name="lance")
sys.meta_path.insert(0, MissingLance())
""" + textwrap.dedent(
"""
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
def test_blob_query_without_pylance(tmp_path, api, result):
if result == "pandas":
pytest.importorskip("pandas")
script = _WITHOUT_LANCE + textwrap.dedent(
"""\
import asyncio
import lancedb
@@ -94,3 +97,187 @@ sys.meta_path.insert(0, MissingLance())
text=True,
)
assert completed.returncode == 0, completed.stderr
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "arrow"])
def test_plain_legacy_blob_query_without_pylance(tmp_path, api, result):
if result == "pandas":
pytest.importorskip("pandas")
script = _WITHOUT_LANCE + textwrap.dedent(
"""\
import asyncio
import lancedb
import pyarrow as pa
from lancedb.query import ColumnOrdering
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("filename", pa.string()),
pa.field(
"video_blob",
pa.large_binary(),
metadata={"lance-encoding:blob": "true"},
),
]
)
rows = [
{"id": 1, "filename": "file-1.mp4", "video_blob": b"outside"},
{"id": 2, "filename": "file-2.mp4", "video_blob": b""},
{"id": 3, "filename": "file-3.mp4", "video_blob": None},
{"id": 4, "filename": "file-4.mp4", "video_blob": b"four"},
]
expected = [
{"filename": "file-2.mp4", "payload": b""},
{"filename": "file-3.mp4", "payload": None},
{"filename": "file-4.mp4", "payload": b"four"},
]
def configure(query):
return (
query.select({"filename": "filename", "payload": "video_blob"})
.where("id >= 2")
.order_by(
[ColumnOrdering(column_name="id", ascending=True)]
)
.limit(3)
)
async def main():
storage_options = {"new_table_data_storage_version": "2.1"}
if sys.argv[2] == "async":
db = await lancedb.connect_async(
sys.argv[1], storage_options=storage_options
)
table = await db.create_table("legacy", schema=schema)
await table.add(rows)
table = await db.open_table("legacy")
def query():
return configure(table.query())
def original_query():
return table.query().select(
{"filename": "filename", "payload": "video_blob"}
).limit(1)
def empty_query():
return query().where("id < 0")
def batches():
return query().to_batches(
max_batch_length=1, blob_mode="bytes"
)
else:
db = lancedb.connect(
sys.argv[1], storage_options=storage_options
)
table = db.create_table("legacy", schema=schema)
table.add(rows)
table = db.open_table("legacy")
def query():
return configure(table.search())
def original_query():
return table.search().select(
{"filename": "filename", "payload": "video_blob"}
).limit(1)
def empty_query():
return query().where("id < 0")
def batches():
return query().to_batches(
batch_size=1, blob_mode="bytes"
)
if sys.argv[2] == "async":
reused = table.query().select(
{"filename": "filename", "payload": "video_blob"}
).limit(3)
byte_reader = await reused.to_batches(blob_mode="bytes")
await byte_reader.read_all()
lazy_reader = await reused.to_batches(blob_mode="lazy")
assert "_rowid" not in lazy_reader.schema.names
await lazy_reader.read_all()
reused.select(["filename"])
nonblob_reader = await reused.to_batches(blob_mode="lazy")
assert nonblob_reader.schema.names == ["filename"]
await nonblob_reader.read_all()
if sys.argv[3] == "pandas":
frame = query().to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
frame = await frame
assert frame.to_dict("records") == expected
original = original_query().to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
original = await original
assert original.to_dict("records") == [
{"filename": "file-1.mp4", "payload": b"outside"}
]
direct = table.to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
direct = await direct
assert direct.to_dict("records") == rows
empty = empty_query().to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
empty = await empty
assert empty.to_dict("records") == []
elif sys.argv[3] == "batches":
reader = batches()
if sys.argv[2] == "async":
reader = await reader
rows_out = [batch async for batch in reader]
else:
rows_out = list(reader)
assert reader.schema.field("payload").type == pa.large_binary()
assert "_rowid" not in reader.schema.names
assert all(batch.num_rows == 1 for batch in rows_out)
assert all(batch.schema == reader.schema for batch in rows_out)
actual = [row for batch in rows_out for row in batch.to_pylist()]
assert actual == expected
original_reader = original_query().to_batches(blob_mode="bytes")
if sys.argv[2] == "async":
original_reader = await original_reader
original_rows = [batch async for batch in original_reader]
else:
original_rows = list(original_reader)
assert [
row for batch in original_rows for row in batch.to_pylist()
] == [{"filename": "file-1.mp4", "payload": b"outside"}]
empty_reader = empty_query().to_batches(blob_mode="bytes")
if sys.argv[2] == "async":
empty_reader = await empty_reader
empty_batches = [batch async for batch in empty_reader]
else:
empty_batches = list(empty_reader)
assert empty_batches == []
assert empty_reader.schema.field("payload").type == pa.large_binary()
else:
table_out = query().to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
table_out = await table_out
assert table_out.schema.field("payload").type == pa.large_binary()
assert "_rowid" not in table_out.column_names
assert table_out.to_pylist() == expected
original = original_query().to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
original = await original
assert original.to_pylist() == [
{"filename": "file-1.mp4", "payload": b"outside"}
]
direct = table.to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
direct = await direct
assert direct.to_pylist() == rows
empty_table = empty_query().to_arrow(blob_mode="bytes")
if sys.argv[2] == "async":
empty_table = await empty_table
assert empty_table.num_rows == 0
assert empty_table.schema.field("payload").type == pa.large_binary()
assert "lance" not in sys.modules
asyncio.run(main())
"""
)
completed = subprocess.run(
[sys.executable, "-c", script, str(tmp_path), api, result],
capture_output=True,
text=True,
)
assert completed.returncode == 0, completed.stderr
@@ -184,6 +184,7 @@ def test_function_version_preserves_execution_controls():
value = job_result("remote_function_job.json")
value.update(
batch_size=12,
max_concurrency=4,
row_timeout_seconds=8.0,
result_stability="input_and_context",
)
@@ -192,9 +193,14 @@ def test_function_version_preserves_execution_controls():
assert encoded == value
assert type(encoded["batch_size"]) is int
assert type(encoded["max_concurrency"]) is int
assert type(encoded["row_timeout_seconds"]) is float
assert type(encoded["result_stability"]) is str
for invalid in [True, 1.5, 0, -1, 2**32]:
with pytest.raises(ValueError, match="max_concurrency"):
FunctionVersion(**{**value, "max_concurrency": invalid})
def test_function_version_binds_named_columns_as_one_immutable_application():
version = FunctionVersion.from_json(
@@ -459,6 +465,7 @@ class _FunctionDeclarationInner:
output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
):
self.calls.append(
(
@@ -466,6 +473,7 @@ class _FunctionDeclarationInner:
output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
auto_refresh_resource_budget,
)
)
return "declared"
@@ -491,7 +499,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
)
assert result == "declared"
assert inner.calls[-1][1] == "features"
assert inner.calls[-1][2:] == (None, None)
assert inner.calls[-1][2:] == (None, None, None)
bare = application._copy(update={"columns": {}}).rename(
columns={"normalized_text": "search_text"}
@@ -502,7 +510,7 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
assert result == "declared"
assert inner.calls[-1][1] is None
assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"}
assert inner.calls[-1][2:] == (False, 300)
assert inner.calls[-1][2:] == (False, 300, None)
@pytest.mark.asyncio
@@ -134,6 +134,7 @@ def test_function_execution_controls_match_shared_registration_golden():
env={"MODE": "test"},
python_version="3.12",
batch_size=2,
max_concurrency=4,
row_timeout_seconds=0.75,
)(normalize_score.__wrapped__)
assert (
@@ -193,6 +194,11 @@ def test_function_retry_policy_rejects_invalid_options(options):
({"batch_size": 0}, "batch_size"),
({"batch_size": 2**32}, "batch_size"),
({"batch_size": True}, "batch_size"),
({"max_concurrency": 0}, "max_concurrency"),
({"max_concurrency": -1}, "max_concurrency"),
({"max_concurrency": 2**32}, "max_concurrency"),
({"max_concurrency": True}, "max_concurrency"),
({"max_concurrency": 1.5}, "max_concurrency"),
({"row_timeout_seconds": 0}, "row_timeout_seconds"),
({"row_timeout_seconds": -0.25}, "row_timeout_seconds"),
({"row_timeout_seconds": float("inf")}, "row_timeout_seconds"),
@@ -1894,6 +1900,8 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path):
db.create_function_async(normalize_score)
with pytest.raises(NotImplementedError, match=message):
db.get_function("normalize_score", version=FUNCTION_VERSION)
with pytest.raises(NotImplementedError, match=message):
db.get_function("normalize_score")
with pytest.raises(NotImplementedError, match=message):
list(db.list_functions())
with pytest.raises(NotImplementedError, match=message):
@@ -1903,8 +1911,10 @@ def test_local_function_catalog_operations_are_not_supported(tmp_path):
class _RawFunctionCatalog:
def __init__(self, definition, *, encode=False):
self.definition = json.dumps(definition) if encode else definition
self.requested_versions = []
async def get_function(self, _name, version, namespace_path):
async def get_function(self, _name, version=None, namespace_path=None):
self.requested_versions.append(version)
return self.definition
def list_functions(self, *, namespace_path=None, page_token=None, page_limit=None):
@@ -1944,13 +1954,22 @@ async def test_async_catalog_path_preserves_execution_controls():
row_timeout_seconds=8.0,
result_stability="input_and_context",
)
connection = AsyncConnection(_RawFunctionCatalog(definition, encode=True))
catalog = _RawFunctionCatalog(definition, encode=True)
connection = AsyncConnection(catalog)
latest = await connection.get_function("embed")
integer = await connection.get_function("embed", version=1)
exact = await connection.get_function("embed", version="1")
await connection.get_function("embed", version="001")
listed = [item async for item in connection.list_functions(page_limit=32)]
assert len(listed) == 1
for version in [exact, *listed]:
for version in [latest, integer, exact, *listed]:
assert _assert_execution_control_encoding(version) == definition
assert catalog.requested_versions == [None, "1", "1", "001"]
with pytest.raises(TypeError, match="int, str, or None"):
await connection.get_function("embed", version=True)
with pytest.raises(TypeError, match="int, str, or None"):
await connection.get_function("embed", version=1.5)
def test_sync_catalog_path_preserves_execution_controls():
@@ -1963,13 +1982,22 @@ def test_sync_catalog_path_preserves_execution_controls():
result_stability="input_and_context",
)
connection = object.__new__(RemoteDBConnection)
connection._conn = _RawFunctionCatalog(FunctionVersion(**definition))
catalog = _RawFunctionCatalog(FunctionVersion(**definition))
connection._conn = catalog
latest = connection.get_function("embed")
integer = connection.get_function("embed", version=1)
exact = connection.get_function("embed", version="1")
connection.get_function("embed", version="001")
listed = list(connection.list_functions(page_limit=32))
assert len(listed) == 1
for version in [exact, *listed]:
for version in [latest, integer, exact, *listed]:
assert _assert_execution_control_encoding(version) == definition
assert catalog.requested_versions == [None, "1", "1", "001"]
with pytest.raises(TypeError, match="int, str, or None"):
connection.get_function("embed", version=True)
with pytest.raises(TypeError, match="int, str, or None"):
connection.get_function("embed", version=1.5)
def test_sync_drop_function_emits_server_warnings_without_changing_bool_api():
@@ -127,6 +127,60 @@ def test_function_without_initialization_keeps_its_wire_form():
assert request["artifact"]["kind"] == "python_callable"
@pytest.mark.parametrize("kind", ["function", "class"])
@pytest.mark.parametrize(
("global_value", "value_type"),
[
("pa.struct([('label', pa.string())])", "StructType"),
("(1, (pa.int64(),))", "DataType"),
("{'label': 1}", "dict"),
("float('inf')", "float"),
],
)
def test_unsupported_global_names_value_and_remedy(
helper_package, kind, global_value, value_type
):
definition = (
"class uses_global:\n"
" def __call__(self, value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
if kind == "class"
else "def uses_global(value: int) -> int:\n"
" return value if CAPTURED_VALUE else 0\n"
)
module = helper_package(
"fx_unsupported_global",
{
"__init__.py": f"import pyarrow as pa\nCAPTURED_VALUE = {global_value}\n"
+ definition
},
)
with pytest.raises(TypeError) as error:
function(module.uses_global)
message = str(error.value)
assert "CAPTURED_VALUE" in message
assert value_type in message
assert "finite float" in message
assert "inside the function or class body" in message
def test_supported_nested_literal_global_still_packages(helper_package):
module = helper_package(
"fx_literal_global",
{
"__init__.py": "CAPTURED_VALUE = (None, True, 1, 'label', "
"b'bytes', (1.5,))\n"
"def uses_global(value: int) -> int:\n"
" return value + CAPTURED_VALUE[2]\n"
},
)
definition = function(module.uses_global)
namespace = {}
exec(compile(artifact(definition), "user_function.py", "exec"), namespace)
assert namespace["uses_global"](3) == 4
assert namespace["CAPTURED_VALUE"] == module.CAPTURED_VALUE
@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"])
@pytest.mark.parametrize("kind", ["function", "class"])
def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package):
+24
View File
@@ -22,6 +22,7 @@ from lancedb.index import (
LabelList,
Fm,
NGram,
ZoneMap,
HnswPq,
HnswSq,
HnswFlat,
@@ -279,6 +280,28 @@ async def test_create_ngram_index(db_async):
assert "ScalarIndexQuery" in plan
@pytest.mark.asyncio
async def test_create_zonemap_index(db_async):
# ZoneMap indexes accelerate range and equality filters on ordered columns.
data = pa.table(
{
"id": list(range(100)),
"value": list(range(100)),
}
)
table = await db_async.create_table("zonemap_table", data)
await table.create_index("value", config=ZoneMap())
indices = await table.list_indices()
assert len(indices) == 1
assert indices[0].index_type == "ZoneMap"
assert indices[0].columns == ["value"]
# The index narrows a range scan without changing its results.
result = await table.query().where("value >= 90").to_arrow()
assert sorted(result["id"].to_pylist()) == list(range(90, 100))
@pytest.mark.asyncio
async def test_create_bitmap_index(some_table: AsyncTable):
await some_table.create_index("id", config=Bitmap())
@@ -591,6 +614,7 @@ def test_index_statistics_index_type_lists_all_supported_values():
"BITMAP",
"LABEL_LIST",
"NGRAM",
"ZONEMAP",
}
assert (
+45
View File
@@ -4,6 +4,7 @@
import asyncio
import time
from datetime import timedelta
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -13,6 +14,50 @@ from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@pytest.mark.parametrize("sync", [False, True])
def test_job_repr_bounds_large_payloads_without_fetching(sync):
spec = {"initialization": list(range(100000)), "source": "x" * 100000}
result = {"rows_computed": 7, "details": [{"data": b"x" * 10000}] * 1000}
inner = SimpleNamespace(
id="job-repr",
_state="failed",
job_type="function_refresh",
_description=SimpleNamespace(
creation_ms=2000,
spec=spec,
result=result,
failure="worker failed " + "x" * 10000,
),
)
job = AsyncJob(inner)
if sync:
job = Job(job)
rendered = repr(job)
assert len(rendered) < 1600
assert len(rendered.splitlines()) <= 10
assert "id='job-repr'" in rendered
assert "state='failed'" in rendered
assert "job_type='function_refresh'" in rendered
assert "rows_computed" in rendered
assert "worker failed" in rendered
assert "..." in rendered
assert len(repr(job.status)) < 1700
assert job.spec is spec
assert job.result is result
assert len(job.spec["initialization"]) == 100000
@pytest.mark.parametrize("sync", [False, True])
def test_job_repr_handles_unobserved_and_local_jobs(sync):
unobserved = AsyncJob(SimpleNamespace(id="job-pending", _state=None))
local = AsyncJob(None)
if sync:
unobserved, local = Job(unobserved), Job(local)
assert "id='job-pending', not refreshed" in repr(unobserved)
assert "state='finished'" in repr(local)
assert "failure=" not in repr(local)
@pytest.fixture(params=["async", "sync"])
def wait_job(request):
async def wait(inner, timeout=None, result_decoder=None):
+12 -8
View File
@@ -348,7 +348,7 @@ def test_plain_scan_query_to_pandas_blob_bytes_projection(tmp_db, blob_schema):
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
def test_plain_scan_query_to_pandas_blob_mode_uses_native_path(
tmp_db, monkeypatch, blob_mode
):
pytest.importorskip("lance")
@@ -362,7 +362,8 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
def fail_to_arrow(*args, **kwargs):
raise AssertionError("to_arrow should not be called before native pandas")
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
if blob_mode == "descriptions":
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
df = query.to_pandas(blob_mode=blob_mode)
@@ -488,7 +489,7 @@ async def test_async_plain_scan_query_to_pandas_blob_bytes_projection(
@pytest.mark.asyncio
@pytest.mark.parametrize("blob_mode", ["bytes", "descriptions"])
async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow(
async def test_async_plain_scan_query_to_pandas_blob_mode_uses_native_path(
tmp_db_async, monkeypatch, blob_mode
):
pytest.importorskip("lance")
@@ -502,7 +503,8 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow
async def fail_to_arrow(*args, **kwargs):
raise AssertionError("to_arrow should not be called before native pandas")
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
if blob_mode == "descriptions":
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
df = await query.to_pandas(blob_mode=blob_mode)
@@ -541,12 +543,14 @@ def test_vector_query_to_pandas_legacy_blob_descriptions_and_bytes(tmp_db):
df = query.to_pandas(blob_mode="descriptions")
assert df["blob"].tolist() == [{"position": 0, "size": 3}]
with pytest.raises(ValueError, match="legacy blob columns"):
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
query.to_pandas(blob_mode="bytes")
with pytest.raises(ValueError, match="legacy blob columns"):
with pytest.raises(ValueError, match=r"\['blob'\].*local plain scans"):
query.to_arrow(blob_mode="bytes")
with pytest.raises(ValueError, match="legacy blob columns"):
table.to_arrow(blob_mode="bytes")
table_arrow = table.to_arrow(blob_mode="bytes")
assert table_arrow.schema.field("blob").type == pa.large_binary()
assert "_rowid" not in table_arrow.column_names
assert table_arrow["blob"].to_pylist() == [b"one", b"two", b"three", b"four"]
assert table.to_pandas(blob_mode="bytes")["blob"].tolist() == [
b"one",
b"two",
+192 -10
View File
@@ -10,6 +10,7 @@ import io
import inspect
import json
import multiprocessing as mp
from pathlib import Path
import pickle
import re
import socket
@@ -36,6 +37,7 @@ from lancedb.graph import (
PropertyGraph,
PropertyGraphDescription,
)
from lancedb.functions import FunctionApplication, function
from lancedb.query import (
AsyncQuery,
ColumnOrdering,
@@ -1863,6 +1865,16 @@ def test_remote_create_index_async_returns_job():
{"batch_size": None},
{"batch_size": 1},
{"batch_size": 8},
{"max_concurrency": 3},
{"publication_interval_rows": 60},
{"resource_budget": {"cpu_millis": 2000, "memory_bytes": 4 * 1024**3}},
{
"resource_budget": {
"cpu_millis": 8000,
"memory_bytes": 16 * 1024**3,
"gpu_count": 2,
}
},
{"gpu_class": "a10g", "gpu_count": 2},
{
"retry_policy": {"transient": True, "max_attempts": 3},
@@ -1903,6 +1915,12 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
expected["gpu_class"] = refresh_kwargs["gpu_class"]
if refresh_kwargs.get("gpu_count") is not None:
expected["gpu_count"] = refresh_kwargs["gpu_count"]
if refresh_kwargs.get("resource_budget") is not None:
budget = refresh_kwargs["resource_budget"]
expected["resource_budget"] = {
**budget,
"gpu_count": budget.get("gpu_count", 0),
}
if refresh_kwargs.get("retry_policy") is not None:
expected["retry_policy"] = lancedb.FunctionRetryPolicy.model_validate(
refresh_kwargs["retry_policy"]
@@ -1911,6 +1929,8 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
expected["error_policy"] = refresh_kwargs["error_policy"]
for key in (
"where",
"max_concurrency",
"publication_interval_rows",
"max_failed_fraction",
"max_failed_rows",
"row_timeout_seconds",
@@ -2088,7 +2108,47 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
({"max_failed_rows": -1}, "max_failed_rows"),
({"row_timeout_seconds": 0}, "row_timeout_seconds"),
({"init_timeout_seconds": -5}, "init_timeout_seconds"),
({"publication_interval_rows": 0}, "publication_interval_rows"),
({"publication_interval_rows": -1}, "publication_interval_rows"),
({"max_concurrency": True}, "max_concurrency"),
({"max_concurrency": 1.5}, "max_concurrency"),
({"max_concurrency": 0}, "max_concurrency"),
({"max_concurrency": -1}, "max_concurrency"),
({"max_concurrency": 2**32}, "max_concurrency"),
({"num_workers": 0}, "num_workers"),
(
{"resource_budget": {"cpu_millis": 1000}},
"resource_budget.memory_bytes",
),
(
{
"resource_budget": {
"cpu_millis": 0,
"memory_bytes": 1,
}
},
"resource_budget.cpu_millis",
),
(
{
"resource_budget": {
"cpu_millis": 1000,
"memory_bytes": 1,
},
"gpu_count": 1,
},
"gpu_count cannot be combined with resource_budget",
),
(
{
"resource_budget": {
"cpu_millis": 1000,
"memory_bytes": 1,
"unknown": 1,
}
},
"unsupported key 'unknown'",
),
(
{"max_executor_processes_per_worker": -2},
"max_executor_processes_per_worker",
@@ -4954,8 +5014,12 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
assert "_rowid" not in df.columns
assert df["image"][0]["size"] == 5
else:
with pytest.raises(NotImplementedError, match="stable table snapshot"):
with pytest.raises(
NotImplementedError, match="stable table snapshot"
) as exc:
query.to_pandas(blob_mode=blob_mode)
assert "fetch_blobs(column, row_ids)" in str(exc.value)
assert "with_row_id(True)" in str(exc.value)
@pytest.mark.asyncio
@@ -5535,9 +5599,6 @@ def test_remote_job_handle_reports_its_own_detail():
assert json.loads(job._spec_json) == {"column": "vec"}
assert json.loads(job._result_json) == {"rows_assigned": 1000000}
# print() shows everything the handle knows and nothing it does not.
# print() lays every known field out on its own line, with the JSON
# payloads indented rather than crammed onto one line.
assert repr(job) == "\n".join(
[
"Job(",
@@ -5545,12 +5606,8 @@ def test_remote_job_handle_reports_its_own_detail():
" state='finished',",
" job_type='refresh_column',",
" creation_ms=2000,",
" spec={",
' "column": "vec"',
" },",
" result={",
' "rows_assigned": 1000000',
" },",
" spec={'column': 'vec'},",
" result={'rows_assigned': 1000000},",
")",
]
)
@@ -5783,6 +5840,92 @@ def test_remote_add_columns_reader_not_supported():
assert all("/add_columns/" not in path for path in requests)
@pytest.mark.asyncio
async def test_remote_add_function_columns_forwards_auto_refresh_resource_budget():
bodies = []
application = FunctionApplication.from_json(
json.dumps(
{
"function": {
"name": "embed",
"version": "1",
"object_id": "fixture",
"location": "memory:///fixture",
"manifest_digest": (
"sha256:7e22f815b6648e14f093a3979a8e5a2082"
"fa773ebe1ec84b135cae7e84d6f8e6"
),
},
"inputs": [
{
"parameter": "text",
"kind": "column",
"value": {"path": "text"},
}
],
"output": {
"kind": "scalar",
"arrow_type": "float32",
"nullable": False,
},
}
)
)
def handler(request):
if request.path == "/v1/table/test/describe/":
response = {
"version": 1,
"schema": {
"fields": [
{
"name": "text",
"type": {"type": "string"},
"nullable": True,
}
]
},
}
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(response).encode())
elif request.path == "/v1/table/test/add_columns/":
content_len = int(request.headers.get("Content-Length", 0))
bodies.append(json.loads(request.rfile.read(content_len)))
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(b'{"version": 2}')
else:
request.send_response(404)
request.end_headers()
budget = {"cpu_millis": 2_000, "memory_bytes": 4 * 1024**3}
with mock_lancedb_connection(handler) as db:
table = db.open_table("test")
table.add_columns(
{"embedding": application},
auto_refresh_resource_budget=budget,
)
async with mock_lancedb_connection_async(handler) as db:
table = await db.open_table("test")
await table.add_columns(
{"embedding": application},
auto_refresh_resource_budget=budget,
)
assert len(bodies) == 2
for body in bodies:
assert body["auto_refresh_enabled"] is True
assert body["auto_refresh_resource_budget"] == {
**budget,
"gpu_count": 0,
}
assert body["new_columns"] == [{"name": "embedding", "all_null": True}]
@pytest.mark.asyncio
async def test_async_property_graph_handles():
calls = []
@@ -5958,6 +6101,45 @@ def _mock_remote_table_with_sql(flight_server):
yield lancedb.connect(**kwargs).create_table("test", [{"id": 1}])
def test_remote_function_registration_transports_max_concurrency():
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust"
/ "lancedb"
/ "tests"
/ "fixtures"
/ "first_class_functions"
/ "v1"
/ "remote_function_version.canonical.json"
)
definition = json.loads(fixture.read_text())
definition["max_concurrency"] = 4
@function(name="normalize_score", max_concurrency=4)
def registered(value: float) -> float:
return value
class RegistrationServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.tickets = []
def do_get(self, context, ticket):
self.tickets.append(ticket.ticket)
return flight.RecordBatchStream(
pa.table({"definition": [json.dumps(definition)]})
)
server = RegistrationServer()
with _mock_remote_sql_connection(server) as kwargs:
version = lancedb.connect(**kwargs).create_function(registered)
assert len(server.tickets) == 1
assert b'"max_concurrency":4' in server.tickets[0]
assert version.max_concurrency == 4
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
+10
View File
@@ -20,6 +20,7 @@ NIL_QUERY_ID = UUID(int=0)
class FakeNativeQuery:
id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef")
job_id = None
async def reader(self):
return pa.table({"value": [1, 2]})
@@ -68,6 +69,15 @@ def test_query_id_is_uuid():
assert Query(query).id == query.id
def test_query_job_id_is_optional_and_separate_from_query_id():
native = FakeNativeQuery()
native.job_id = "j1-durable"
query = AsyncQuery(native)
assert query.id != query.job_id
assert query.job_id == "j1-durable"
assert Query(query).job_id == "j1-durable"
def test_connection_serializes_sql_host_override():
endpoint = "grpc+tls://sql.example.com:10026"
restored = lancedb.deserialize_conn(
+21
View File
@@ -6064,6 +6064,12 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
({"max_failed_rows": 10}, "max_failed_rows"),
({"row_timeout_seconds": 30}, "row_timeout_seconds"),
({"init_timeout_seconds": 60}, "init_timeout_seconds"),
({"max_concurrency": 4}, "max_concurrency"),
({"publication_interval_rows": 60}, "publication_interval_rows"),
(
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
"resource_budget",
),
({"num_workers": 2}, "num_workers"),
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
],
@@ -6319,6 +6325,21 @@ def test_auto_refresh_options_require_computed_columns(tmp_path):
table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True)
def test_auto_refresh_resource_budget_requires_a_function(tmp_path):
table = lancedb.connect(tmp_path).create_table("invalid_budget", [{"x": 1}])
before = table.version
with pytest.raises(ValueError, match="registered Function"):
table.add_columns(
computed={"doubled": "x * 2"},
auto_refresh_resource_budget={
"cpu_millis": 1_000,
"memory_bytes": 1_024,
},
)
assert table.version == before
assert table.schema.names == ["x"]
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
+8 -8
View File
@@ -877,22 +877,22 @@ impl Connection {
})
}
#[pyo3(signature = (name, version, namespace_path=None))]
#[pyo3(signature = (name, version=None, namespace_path=None))]
pub fn get_function(
self_: PyRef<'_, Self>,
name: String,
version: String,
version: Option<String>,
namespace_path: Option<Vec<String>>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.get_function(name, version, &namespace_path)
.await
.infer_error()?
.to_canonical_json()
.infer_error()
let function = match version {
Some(version) => inner.get_function(name, version, &namespace_path).await,
None => inner.get_function_latest(name, &namespace_path).await,
}
.infer_error()?;
function.to_canonical_json().infer_error()
})
}
+3 -1
View File
@@ -10,6 +10,7 @@ use lancedb::index::{
Index as LanceDbIndex,
scalar::{
BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder,
ZoneMapIndexBuilder,
},
};
use pyo3::IntoPyObject;
@@ -117,6 +118,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
"LabelList" => Ok(LanceDbIndex::LabelList(Default::default())),
"Fm" => Ok(LanceDbIndex::Fm(FmIndexBuilder::default())),
"NGram" => Ok(LanceDbIndex::NGram(NGramIndexBuilder::default())),
"ZoneMap" => Ok(LanceDbIndex::ZoneMap(ZoneMapIndexBuilder::default())),
"FTS" => {
let params = source.extract::<FtsParams>()?;
let code_options = CodeAnalyzerOptions {
@@ -291,7 +293,7 @@ pub fn extract_index_params(source: &Option<Bound<'_, PyAny>>) -> PyResult<Lance
Ok(LanceDbIndex::IvfHnswFlat(hnsw_flat_builder))
}
not_supported => Err(PyValueError::new_err(format!(
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
"Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat",
not_supported
))),
}
+9 -2
View File
@@ -31,6 +31,11 @@ impl Query {
self.inner.id()
}
#[getter]
pub fn job_id(&self) -> Option<String> {
self.inner.job_id()
}
pub fn describe(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
@@ -63,6 +68,7 @@ impl Query {
#[derive(Clone)]
pub struct QueryDescription {
id: Uuid,
job_id: Option<String>,
status: String,
progress: Option<f64>,
expires_at: Option<DateTime<Utc>>,
@@ -72,8 +78,8 @@ pub struct QueryDescription {
impl QueryDescription {
fn __repr__(&self) -> String {
format!(
"QueryDescription(id={:?}, status={:?}, progress={:?}, expires_at={:?})",
self.id, self.status, self.progress, self.expires_at
"QueryDescription(id={:?}, job_id={:?}, status={:?}, progress={:?}, expires_at={:?})",
self.id, self.job_id, self.status, self.progress, self.expires_at
)
}
}
@@ -82,6 +88,7 @@ impl From<lancedb::sql::QueryDescription> for QueryDescription {
fn from(description: lancedb::sql::QueryDescription) -> Self {
Self {
id: description.id,
job_id: description.job_id,
status: description.status.to_string(),
progress: description.progress,
expires_at: description.expires_at,
+135 -19
View File
@@ -29,15 +29,17 @@ use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, IndexRemapMode, NewColumnTransform, Ref,
RefreshColumnOptions, Table as LanceDbTable,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode,
NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
exceptions::{PyRuntimeError, PyValueError},
pyclass, pyfunction, pymethods,
types::{IntoPyDict, PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods},
types::{
IntoPyDict, PyAnyMethods, PyBool, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods,
},
};
mod scannable;
@@ -46,6 +48,9 @@ mod scannable;
struct RefreshColumnArgs {
where_clause: Option<String>,
batch_size: Option<i64>,
max_concurrency: Option<u32>,
publication_interval_rows: Option<i64>,
resource_budget: Option<FunctionWorkerResourceBudget>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -69,10 +74,97 @@ fn positive_count<T: TryFrom<i64>>(value: Option<i64>, name: &str) -> PyResult<O
.transpose()
}
fn positive_u32_integer(value: Option<&Bound<'_, PyAny>>, name: &str) -> PyResult<Option<u32>> {
let Some(value) = value else {
return Ok(None);
};
if value.is_none() || value.is_instance_of::<PyBool>() {
return Err(PyValueError::new_err(format!(
"{name} must be an integer between 1 and 4294967295"
)));
}
let parsed = value.extract::<i64>().map_err(|_| {
PyValueError::new_err(format!(
"{name} must be an integer between 1 and 4294967295"
))
})?;
u32::try_from(parsed)
.ok()
.filter(|parsed| *parsed > 0)
.map(Some)
.ok_or_else(|| {
PyValueError::new_err(format!(
"{name} must be an integer between 1 and 4294967295"
))
})
}
fn resource_budget_integer(
value: &Bound<'_, PyAny>,
name: &str,
allow_zero: bool,
) -> PyResult<u64> {
if value.is_none() || value.is_instance_of::<PyBool>() {
return Err(PyValueError::new_err(format!(
"resource_budget.{name} must be an integer"
)));
}
let parsed = value
.extract::<u64>()
.map_err(|_| PyValueError::new_err(format!("resource_budget.{name} must be an integer")))?;
if !allow_zero && parsed == 0 {
return Err(PyValueError::new_err(format!(
"resource_budget.{name} must be greater than zero"
)));
}
Ok(parsed)
}
fn parse_resource_budget(
budget: Option<&Bound<'_, PyDict>>,
) -> PyResult<Option<FunctionWorkerResourceBudget>> {
let Some(budget) = budget else {
return Ok(None);
};
for key in budget.keys() {
let key = key
.extract::<String>()
.map_err(|_| PyValueError::new_err("resource_budget keys must be strings"))?;
if !matches!(key.as_str(), "cpu_millis" | "memory_bytes" | "gpu_count") {
return Err(PyValueError::new_err(format!(
"resource_budget contains unsupported key '{key}'"
)));
}
}
let cpu_millis = budget
.get_item("cpu_millis")?
.ok_or_else(|| PyValueError::new_err("resource_budget.cpu_millis is required"))?;
let cpu_millis = resource_budget_integer(&cpu_millis, "cpu_millis", false)?;
let memory_bytes = budget
.get_item("memory_bytes")?
.ok_or_else(|| PyValueError::new_err("resource_budget.memory_bytes is required"))?;
let memory_bytes = resource_budget_integer(&memory_bytes, "memory_bytes", false)?;
let gpu_count = match budget.get_item("gpu_count")? {
None => 0,
Some(value) if value.is_none() => 0,
Some(value) => {
u32::try_from(resource_budget_integer(&value, "gpu_count", true)?).map_err(|_| {
PyValueError::new_err("resource_budget.gpu_count must be no greater than u32::MAX")
})?
}
};
Ok(Some(
FunctionWorkerResourceBudget::new(cpu_millis, memory_bytes).with_gpu_count(gpu_count),
))
}
fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOptions> {
let RefreshColumnArgs {
where_clause,
batch_size,
max_concurrency,
publication_interval_rows,
resource_budget,
gpu_class,
gpu_count,
retry_policy,
@@ -114,6 +206,10 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
.map(usize::try_from)
.transpose()
.map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?;
options.max_concurrency = max_concurrency;
options.publication_interval_rows =
positive_count(publication_interval_rows, "publication_interval_rows")?;
options.resource_budget = resource_budget;
options.gpu_class = gpu_class;
options.gpu_count = gpu_count
.map(|count| {
@@ -2151,17 +2247,21 @@ impl Table {
})
}
#[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
pub fn add_computed_columns(
self_: PyRef<'_, Self>,
#[pyo3(signature = (columns, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))]
pub fn add_computed_columns<'py>(
self_: PyRef<'py, Self>,
columns: Vec<(String, String)>,
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<u64>,
) -> PyResult<Bound<'_, PyAny>> {
auto_refresh_resource_budget: Option<Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let inner = self_.inner_ref()?.clone();
let options = ComputedColumnOptions {
auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true),
auto_refresh_interval_seconds,
auto_refresh_resource_budget: parse_resource_budget(
auto_refresh_resource_budget.as_ref(),
)?,
};
options.validate().infer_error()?;
future_into_py(self_.py(), async move {
@@ -2178,20 +2278,24 @@ impl Table {
})
}
#[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
pub fn add_function_columns(
self_: PyRef<'_, Self>,
#[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, auto_refresh_resource_budget=None))]
pub fn add_function_columns<'py>(
self_: PyRef<'py, Self>,
application_json: String,
output_name: Option<String>,
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<u64>,
) -> PyResult<Bound<'_, PyAny>> {
auto_refresh_resource_budget: Option<Bound<'py, PyDict>>,
) -> PyResult<Bound<'py, PyAny>> {
let application =
lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?;
let inner = self_.inner_ref()?.clone();
let options = ComputedColumnOptions {
auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true),
auto_refresh_interval_seconds,
auto_refresh_resource_budget: parse_resource_budget(
auto_refresh_resource_budget.as_ref(),
)?,
};
options.validate().infer_error()?;
future_into_py(self_.py(), async move {
@@ -2208,13 +2312,16 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column(
self_: PyRef<'_, Self>,
pub fn refresh_column<'py>(
self_: PyRef<'py, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2225,10 +2332,13 @@ impl Table {
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
) -> PyResult<Bound<'_, PyAny>> {
) -> PyResult<Bound<'py, PyAny>> {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
@@ -2250,13 +2360,16 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column_async(
self_: PyRef<'_, Self>,
pub fn refresh_column_async<'py>(
self_: PyRef<'py, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2267,10 +2380,13 @@ impl Table {
init_timeout_seconds: Option<f64>,
num_workers: Option<i64>,
max_executor_processes_per_worker: Option<i64>,
) -> PyResult<Bound<'_, PyAny>> {
) -> PyResult<Bound<'py, PyAny>> {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
+7 -7
View File
@@ -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.0b15" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" },
{ 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.0b15"
version = "15.0.0b16"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
@@ -4312,11 +4312,11 @@ 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_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" },
{ url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" },
{ url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" },
{ url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" },
{ url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" },
{ url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" },
]
[[package]]