Merge main into gatekeeper/fix-5025-1

This commit is contained in:
Gatefixer
2026-11-20 14:04:06 +00:00
58 changed files with 4305 additions and 763 deletions
+6 -6
View File
@@ -12,17 +12,17 @@ dependencies = [
"tqdm>=4.27.0",
"lance-namespace>=0.13.0"
]
description = "lancedb"
description = "Embedded database for vector, full-text and hybrid search on Lance tables"
authors = [{ name = "LanceDB Devs", email = "dev@lancedb.com" }]
license = { file = "LICENSE" }
readme = "README.md"
requires-python = ">=3.10"
keywords = [
"data-format",
"data-science",
"machine-learning",
"arrow",
"data-analytics",
"lance",
"vector-search",
"full-text-search",
"dataset",
"versioning",
]
classifiers = [
"Development Status :: 3 - Alpha",
+1
View File
@@ -79,6 +79,7 @@ from .materialized_view import (
from .view import ViewDescription as ViewDescription
from .graph import PropertyGraph, PropertyGraphDescription
from .table import AsyncTable, CompactionOptions, Table
from .query import ColumnOrdering as ColumnOrdering
from .types import BaseTokenizerType
from ._lancedb import Session
from .namespace import (
+18 -1
View File
@@ -962,6 +962,9 @@ class Query:
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -974,6 +977,9 @@ class TakeQuery:
def use_rte(self, enable: bool): ...
async def output_schema(self) -> pa.Schema: ...
async def execute(self) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -1000,6 +1006,9 @@ class FTSQuery:
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -1009,6 +1018,9 @@ class FTSQuery:
class VectorQuery:
async def output_schema(self) -> pa.Schema: ...
async def execute(self) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
def where(self, filter: str): ...
def where_expr(self, expr: PyExpr): ...
def select(self, columns: List[Tuple[str, str]]): ...
@@ -1280,7 +1292,12 @@ class AsyncPermutationBuilder:
seed: Optional[int] = None,
) -> "AsyncPermutationBuilder": ...
def split_hash(
self, columns: List[str], split_weights: List[int], *, discard_weight: int = 0
self,
columns: List[str],
split_weights: List[int],
*,
discard_weight: Optional[int] = None,
split_names: Optional[List[str]] = None,
) -> "AsyncPermutationBuilder": ...
def split_sequential(
self,
+47 -15
View File
@@ -13,22 +13,51 @@ class BackgroundEventLoop:
A background event loop that can run futures.
Used to bridge sync and async code, without messing with users event loops.
The loop and its thread are created by the first call to :meth:`run`, not
by constructing this object, so importing lancedb does not leave an idle
background thread behind.
"""
def __init__(self):
self._start()
self.loop: asyncio.AbstractEventLoop | None = None
self.thread: threading.Thread | None = None
self._start_lock = threading.Lock()
def _start(self):
self.loop = asyncio.new_event_loop()
self.thread = threading.Thread(
target=self.loop.run_forever,
name="LanceDBBackgroundEventLoop",
daemon=True,
)
self.thread.start()
def _start(self) -> asyncio.AbstractEventLoop:
loop = self.loop
if loop is not None:
return loop
with self._start_lock:
loop = self.loop
if loop is not None:
return loop
loop = asyncio.new_event_loop()
thread = threading.Thread(
target=loop.run_forever,
name="LanceDBBackgroundEventLoop",
daemon=True,
)
thread.start()
# Publish the loop first and the thread last. Callers that reach
# _start while this is in progress wait on _start_lock, so they
# cannot observe a half-initialized loop/thread pair.
self.loop = loop
self.thread = thread
return loop
def _reset_after_fork(self):
# Threads do not survive fork(). Reset to the unstarted state without
# calling into the inherited loop or thread: the thread is gone, and
# it may have held _start_lock when the fork happened. A fresh lock
# lets the child start a new loop on its first run().
self.loop = None
self.thread = None
self._start_lock = threading.Lock()
def run(self, future):
concurrent_future = asyncio.run_coroutine_threadsafe(future, self.loop)
loop = self._start()
concurrent_future = asyncio.run_coroutine_threadsafe(future, loop)
try:
return concurrent_future.result()
except BaseException:
@@ -60,12 +89,15 @@ _FORK_WARNED = False
def _reset_after_fork():
# Threads do not survive fork(), so the asyncio loop in LOOP.thread is
# dead in the child. Re-initialize the singleton in place so existing
# Threads do not survive fork(), so the loop in LOOP.thread is dead in
# the child. Reset the singleton in place so existing
# `from .background_loop import LOOP` references in other modules see
# the new state. The Rust-side tokio runtime is reset analogously by a
# pthread_atfork hook installed in the _lancedb extension.
LOOP._start()
# the unstarted state and create a fresh loop on their first run(). Do
# not restart it here: the child may never use LanceDB, and the at-fork
# handler must not touch the vanished thread or acquire inherited locks.
# The Rust-side tokio runtime is reset analogously by a pthread_atfork
# hook installed in the _lancedb extension.
LOOP._reset_after_fork()
# The embedding executor's worker threads are dead in the child as well.
# Replace it with a fresh pool (threads are spawned lazily, so this is
# cheap); we don't shut down the old one, since joining its dead workers
+30 -1
View File
@@ -1936,11 +1936,40 @@ class LanceDBConnection(DBConnection):
"manifest_enabled": self._manifest_enabled,
"namespace_client_properties": self._namespace_client_properties,
"read_consistency_interval_seconds": (
rci.total_seconds() if rci else None
rci.total_seconds() if rci is not None else None
),
}
)
def _pickle_state(self) -> str:
"""Serialize this connection for pickle-based workers."""
if self._session is not None:
raise TypeError(
"Cannot pickle a LanceDBConnection created with a Session; "
"Session objects are not serializable. Create the Session in "
"each worker process instead."
)
if self.uri.startswith("memory://"):
raise TypeError(
"Cannot pickle an in-memory LanceDBConnection because its tables "
"exist only in this process. Pickle a LanceTable instead to "
"export its data, or connect to a persistent URI."
)
return self.serialize()
def __getstate__(self) -> dict[str, str]:
return {"serialized": self._pickle_state()}
def __setstate__(self, state: dict[str, str]) -> None:
from . import deserialize_conn
connection = deserialize_conn(state["serialized"], for_worker=True)
if not isinstance(connection, LanceDBConnection):
raise TypeError(
"Serialized connection did not reconstruct a LanceDBConnection"
)
self.__dict__.update(connection.__dict__)
async def _async_get_table_names(self, start_after: Optional[str], limit: int):
conn = AsyncConnection(await lancedb_connect(self.uri))
return await conn.table_names(start_after=start_after, limit=limit)
+26 -2
View File
@@ -3182,6 +3182,12 @@ class FunctionDefinition:
remote application or build the declared remote runtime, and it does not
need the private implementation attribute.
Arguments to this call are Python and Arrow values. An
[Expr][lancedb.expr.Expr] argument, such as ``col("value")``, is a column
binding that only a registered
[FunctionVersion][lancedb.functions.FunctionVersion] can carry, so this
call rejects it with ``TypeError`` instead of running the callable.
Remote execution adapts the callable to the internal Arrow batch ABI
described by the registration artifact. By default it invokes the callable
once per row. A callable whose parameters are all annotated as
@@ -3451,6 +3457,16 @@ class FunctionDefinition:
return self._request._copy(update={"secret_bindings": resolved})
def __call__(self, *args, **kwargs):
from lancedb.expr import Expr
if any(isinstance(value, Expr) for value in (*args, *kwargs.values())):
raise TypeError(
"a FunctionDefinition runs locally on Python and Arrow values; "
"an Expr input binds only on a registered FunctionVersion. "
"Register the definition with create_function or "
"create_function_async, then bind col(...) on the returned "
"version."
)
return self._function(*args, **kwargs)
@@ -3541,7 +3557,12 @@ def function(
it takes one ``pyarrow.RecordBatch``. These batch annotations require both
``input_schema`` and ``output_schema`` explicitly: the annotations do not
specify Arrow element types or fields. This also applies to a class's
``__call__`` method. A decorated class is the same callable with state:
``__call__`` method. Each ``input_schema`` field names one parameter, so
several input columns take one ``pyarrow.Array`` parameter each, while a
single ``pyarrow.RecordBatch`` parameter binds one input column and
receives it as a batch. The
[Function authoring guide](https://lancedb.com/docs/curation/create-function#batch)
has the worked examples. A decorated class is the same callable with state:
each remote instance calls ``__init__`` once, calls
``__call__`` for every row or batch of every input it processes, and calls
``close()``, if defined, once when it retires. Load models, open clients,
@@ -3803,7 +3824,10 @@ def function(
remote environment, resolve Secrets, or run the remote Arrow adapter or
sandbox. A registered ``FunctionVersion`` call is different: it binds
``col(...)`` inputs and returns a remote
[FunctionApplication][lancedb.functions.FunctionApplication].
[FunctionApplication][lancedb.functions.FunctionApplication]. Passing an
[Expr][lancedb.expr.Expr] to a definition raises ``TypeError`` before the
callable runs, because a column reference binds only on a registered
version.
```python
scaled = scale(factor=2.0)
+16 -5
View File
@@ -509,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection):
Supported values:
- "QueryTable": Execute queries on the namespace server via
namespace.query_table() instead of locally.
namespace.query_table() instead of locally. Queries with a
nonempty ``order_by`` execute locally and require the client to
access the table storage.
- "CreateTable": Execute table creation on the namespace server via
namespace.create_table() instead of using declare_table + local write.
@@ -584,7 +586,7 @@ class LanceNamespaceDBConnection(DBConnection):
"storage_options": self.storage_options or None,
"read_consistency_interval_seconds": (
self.read_consistency_interval.total_seconds()
if self.read_consistency_interval
if self.read_consistency_interval is not None
else None
),
}
@@ -668,6 +670,7 @@ class LanceNamespaceDBConnection(DBConnection):
self,
name,
namespace_path=namespace_path,
storage_options=storage_options,
namespace_client=self._namespace_client,
pushdown_operations=self._namespace_client_pushdown_operations,
route_pushdown_to_rust=self._route_pushdown_to_rust,
@@ -706,6 +709,7 @@ class LanceNamespaceDBConnection(DBConnection):
self,
name,
namespace_path=namespace_path,
storage_options=storage_options,
namespace_client=self._namespace_client,
pushdown_operations=self._namespace_client_pushdown_operations,
route_pushdown_to_rust=self._route_pushdown_to_rust,
@@ -1132,6 +1136,7 @@ class LanceNamespaceDBConnection(DBConnection):
self,
name,
namespace_path=namespace_path,
storage_options=storage_options,
location=table_uri,
namespace_client=namespace_client,
managed_versioning=managed_versioning,
@@ -1205,7 +1210,9 @@ class AsyncLanceNamespaceDBConnection:
Supported values:
- "QueryTable": Execute queries on the namespace server via
namespace.query_table() instead of locally.
namespace.query_table() instead of locally. Queries with a
nonempty ``order_by`` execute locally and require the client to
access the table storage.
- "CreateTable": Execute table creation on the namespace server via
namespace.create_table() instead of using declare_table + local write.
@@ -1808,7 +1815,9 @@ def connect_namespace(
Supported values:
- "QueryTable": Execute queries on the namespace server via
namespace.query_table() instead of locally.
namespace.query_table() instead of locally. Queries with a nonempty
``order_by`` execute locally and require the client to access the
table storage.
- "CreateTable": Execute table creation on the namespace server via
namespace.create_table() instead of using declare_table + local write.
@@ -1899,7 +1908,9 @@ def connect_namespace_async(
Supported values:
- "QueryTable": Execute queries on the namespace server via
namespace.query_table() instead of locally.
namespace.query_table() instead of locally. Queries with a nonempty
``order_by`` execute locally and require the client to access the
table storage.
- "CreateTable": Execute table creation on the namespace server via
namespace.create_table() instead of using declare_table + local write.
+33 -10
View File
@@ -410,6 +410,8 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]:
from .remote.table import RemoteTable
if isinstance(table, RemoteTable):
# RemoteTable already owns its reopen state; keep the table object so
# pickle delegates to its __getstate__ without duplicating the fields.
return {
"kind": "remote",
"table": table,
@@ -418,20 +420,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]:
if not isinstance(table, LanceTable):
raise ValueError(f"Cannot pickle table of type {type(table)!r}")
base_uri = table._conn.uri
if base_uri.startswith("memory://"):
state = table.__getstate__()
if state.get("kind") == "memory":
return {
"kind": "memory",
"name": table.name,
"data": table.to_arrow(),
"state": state,
}
return {
"kind": "local",
"name": table.name,
"uri": base_uri,
"namespace": table._namespace_path,
"storage_options": table._conn.storage_options,
"kind": "lance",
"state": state,
}
@@ -444,13 +441,25 @@ def _drop_base_version(permutation_data: pa.Table) -> pa.Table:
return permutation_data.replace_schema_metadata(metadata)
def _lance_table_from_pickle_state(state: dict[str, Any]) -> LanceTable:
table = LanceTable.__new__(LanceTable)
table.__setstate__(state)
return table
def _table_from_pickle_state(state: dict[str, Any]) -> Table:
from . import connect
kind = state["kind"]
if kind == "remote":
return state["table"]
if kind == "lance":
return _lance_table_from_pickle_state(state["state"])
if kind == "memory":
if "state" in state:
return _lance_table_from_pickle_state(state["state"])
# Backward compatibility for pickles written before tables carried
# their own state.
return connect("memory://").create_table(state["name"], state["data"])
if kind == "local":
db = connect(state["uri"], storage_options=state["storage_options"])
@@ -779,6 +788,20 @@ class Permutation:
self.reader = None
self._pid = None
def __copy__(self) -> "Permutation":
"""Return a shallow copy without going through the pickle path.
The ``with_*`` builders use ``copy.copy`` to derive a new permutation.
The default copy protocol would use ``__getstate__``/``__setstate__``,
which materializes the permutation table with ``to_arrow()`` (not
supported for remote tables) and rebuilds the base table and reader.
A shallow copy instead keeps the existing table handles and reader;
the caller replaces only the attribute it is changing.
"""
new = self.__class__.__new__(self.__class__)
new.__dict__ = self.__dict__.copy()
return new
def _ensure_open(self) -> None:
pid = os.getpid()
if self.reader is not None and getattr(self, "_pid", None) == pid:
+429 -57
View File
@@ -273,6 +273,24 @@ def _query_needs_lance_scanner(builder: Any) -> bool:
)
def _raise_unsupported_fragment_constraints(
fragments: Optional[Any],
fragment_ids: Optional[List[int]],
*,
operation: str,
) -> None:
"""Reject fragment selection where execution would silently scan everything."""
if fragments is None and fragment_ids is None:
return
raise NotImplementedError(
"with_fragments() and fragment_ids() are only supported for embedded "
"plain-scan blob queries executed through to_pandas(). "
f"{operation} would ignore the fragment selection and scan the full "
"table. Remove the fragment constraint, or use table.to_lance() with "
"a Lance scanner for this query shape."
)
def _query_is_plain_scan(query: Query) -> bool:
return (
query.vector is None
@@ -571,11 +589,107 @@ def ensure_vector_query(
class ColumnOrdering(pydantic.BaseModel):
"""A single sort key for ``order_by``.
Attributes
----------
column_name: str
The column to sort by.
ascending: bool, default True
Sort ascending when true, descending otherwise.
nulls_first: bool, default False
Place null values before non-null values when true.
"""
column_name: str
ascending: bool = True
nulls_first: bool = False
_OrderingItem = Union[str, Tuple[str, str], ColumnOrdering, Dict[str, Any]]
_OrderingInput = Optional[Union[_OrderingItem, List[_OrderingItem]]]
_COLUMN_ORDERING_KEYS = frozenset({"column_name", "ascending", "nulls_first"})
_ORDERING_EXAMPLE = '[{"column_name": "uris", "ascending": True}]'
def _normalize_ordering(ordering: _OrderingInput) -> Optional[List[ColumnOrdering]]:
"""Normalize the accepted ``order_by`` inputs into ``ColumnOrdering`` models.
``None`` and an empty list clear the ordering. A tuple is always a single
``(column_name, "asc"|"desc")`` pair, while a list is always a sequence of
separate orderings, so ``("a", "desc")`` and ``["a", "desc"]`` differ.
"""
if ordering is None:
return None
if isinstance(ordering, tuple):
items: List[Any] = [ordering]
elif isinstance(ordering, list):
items = ordering
else:
items = [ordering]
normalized = [
_normalize_ordering_item(item, index) for index, item in enumerate(items)
]
return normalized or None
def _normalize_ordering_item(item: Any, index: int) -> ColumnOrdering:
prefix = f"order_by entry {index}"
if isinstance(item, ColumnOrdering):
if not item.column_name:
raise ValueError(f"{prefix} has an empty column_name")
return item
if isinstance(item, str):
if not item:
raise ValueError(f"{prefix} is an empty column name")
return ColumnOrdering(column_name=item)
if isinstance(item, tuple):
if len(item) != 2:
raise ValueError(
f"{prefix} must be a (column_name, 'asc'|'desc') tuple; got {item!r}"
)
column_name, direction = item
if not isinstance(column_name, str) or not column_name:
raise ValueError(
f"{prefix} must start with a non-empty column name; got {item!r}"
)
if not isinstance(direction, str) or direction.lower() not in ("asc", "desc"):
raise ValueError(
f"{prefix} has invalid direction {direction!r}; "
"expected 'asc' or 'desc'"
)
return ColumnOrdering(
column_name=column_name, ascending=direction.lower() == "asc"
)
if isinstance(item, dict):
unknown_keys = set(item) - _COLUMN_ORDERING_KEYS
if unknown_keys:
raise ValueError(
f"{prefix} has unsupported key(s) {sorted(map(str, unknown_keys))}; "
f"expected keys: {sorted(_COLUMN_ORDERING_KEYS)}. "
f"Example: {_ORDERING_EXAMPLE}"
)
if "column_name" not in item:
raise ValueError(
f"{prefix} is missing 'column_name'. Example: {_ORDERING_EXAMPLE}"
)
try:
normalized = ColumnOrdering(**item)
except pydantic.ValidationError as err:
raise ValueError(
f"{prefix} is not a valid ordering: {err}. Example: {_ORDERING_EXAMPLE}"
) from err
if not normalized.column_name:
raise ValueError(f"{prefix} has an empty column_name")
return normalized
raise TypeError(
f"{prefix} must be a column name, a (column_name, 'asc'|'desc') tuple, "
f"a ColumnOrdering, or a dict with 'column_name'; "
f"got {type(item).__name__}"
)
class FullTextQueryType(str, Enum):
MATCH = "match"
MATCH_PHRASE = "match_phrase"
@@ -1686,11 +1800,19 @@ class LanceQueryBuilder(ABC):
return self._user_requested_row_id() or self._blob_auto_row_id_enabled()
def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query:
self._ensure_fragment_constraints_supported("this query")
query = self.to_query_object()
if self._scan_needs_row_id() or blob_sources:
query.with_row_id = True
return query
def _ensure_fragment_constraints_supported(self, operation: str) -> None:
_raise_unsupported_fragment_constraints(
self._fragments,
self._fragment_ids,
operation=operation,
)
def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes":
return False
@@ -1826,12 +1948,51 @@ class LanceQueryBuilder(ABC):
return self
def with_fragments(self, fragments: Any) -> Self:
"""Set the Lance fragments to scan for plain scanner-backed queries."""
"""Restrict an embedded plain-scan blob query to the given Lance fragments.
Fragment selection is supported only when ``to_pandas()`` uses the
embedded Lance plain-scan path: the table is an embedded, non-memory
Lance dataset, the query is a plain scan (no vector, full-text, take,
postfilter, or ordering), and the selected output includes a blob
column. Other terminals and remote tables raise ``NotImplementedError``
before scanning instead of silently scanning the full table.
Blob-specific ``to_pandas()`` fallbacks keep their existing validation
errors.
Parameters
----------
fragments : list[lance.Fragment]
Fragments from ``table.to_lance().get_fragments()``. Pass fragments
from the same dataset snapshot.
Returns
-------
LanceQueryBuilder
The LanceQueryBuilder object.
"""
self._fragments = fragments
return self
def fragment_ids(self, fragment_ids: List[int]) -> Self:
"""Set the Lance fragment ids to scan for plain scanner-backed queries."""
"""Restrict an embedded plain-scan blob query to the given fragment ids.
Fragment selection uses the same supported ``to_pandas()`` path as
``with_fragments()``. On that path, an empty list selects no rows and
missing ids raise ``ValueError``. Other terminals and remote tables
raise ``NotImplementedError`` before scanning instead of silently
scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep
their existing validation errors.
Parameters
----------
fragment_ids : list[int]
Fragment ids from ``table.to_lance().get_fragments()``.
Returns
-------
LanceQueryBuilder
The LanceQueryBuilder object.
"""
self._fragment_ids = fragment_ids
return self
@@ -1887,24 +2048,40 @@ class LanceQueryBuilder(ABC):
-------
plan : str
""" # noqa: E501
self._ensure_fragment_constraints_supported("explain_plan()")
return self._table._explain_plan(self.to_query_object(), verbose=verbose)
def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self:
def order_by(self, ordering: _OrderingInput = None) -> Self:
"""
Set the ordering for the results.
Parameters
----------
ordering: Optional[List[ColumnOrdering]]
The ordering to use for the results. If None, then the default ordering
will be used.
ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
The ordering to use for the results. Each entry can be a column
name, a ``(column_name, "asc"|"desc")`` tuple, a
[ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a
``column_name`` key. A bare tuple is a single direction pair, while
a list contains separate orderings, so ``("a", "desc")`` sorts by
``a`` descending and ``["a", "desc"]`` sorts by both columns.
Pass ``None`` or an empty list to clear the ordering.
Returns
-------
LanceQueryBuilder
The LanceQueryBuilder object.
Examples
--------
>>> import lancedb
>>> db = lancedb.connect("memory://")
>>> table = db.create_table("ordering", [{"name": "b"}, {"name": "a"}])
>>> table.search().order_by(["name"]).to_list()
[{'name': 'a'}, {'name': 'b'}]
>>> table.search().order_by([("name", "desc")]).to_list()
[{'name': 'b'}, {'name': 'a'}]
"""
self._order_by = ordering
self._order_by = _normalize_ordering(ordering)
return self
def analyze_plan(
@@ -1961,6 +2138,7 @@ class LanceQueryBuilder(ABC):
plan : str
The physical query execution plan with runtime metrics.
"""
self._ensure_fragment_constraints_supported("analyze_plan()")
return self._table._analyze_plan(
self.to_query_object(), distributed_metrics=distributed_metrics
)
@@ -2389,10 +2567,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
columns and raises for blobs inside lists.
"""
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode != "lazy":
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
)
self._ensure_fragment_constraints_supported("to_arrow()")
results = self._table._execute_arrow(
self._query_for_scan(blob_sources), timeout=timeout
)
if self._reranker is not None:
source = results
results = self._reranker.rerank_vector(self._str_query, results)
check_reranker_result(results)
results = _merge_query_snapshot(results, source)
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
results, blob_mode=blob_mode, blob_sources=blob_sources
)
def to_query_object(self) -> Query:
@@ -2629,6 +2821,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
For example, ``table.search("gripper closed", query_type="fts",``
``operator="AND").where("active = true").count_rows()``.
"""
self._ensure_fragment_constraints_supported("count_rows()")
self._table._ensure_no_legacy_fts_index()
query = self._table._table._sync_query_to_async(self.to_query_object())
assert isinstance(query, AsyncFTSQuery)
@@ -2716,8 +2909,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
blob_sources = self._validated_blob_sources(blob_mode)
self._table._ensure_no_legacy_fts_index()
self._ensure_fragment_constraints_supported("to_arrow()")
query = self._query_for_scan(blob_sources)
results = self._table._execute_query(query, timeout=timeout).read_all()
if blob_mode == "lazy":
results = self._table._execute_arrow(query, timeout=timeout)
else:
results = self._table._execute_query(query, timeout=timeout).read_all()
if self._reranker is not None:
source = results
results = self._reranker.rerank_fts(self._query, results)
@@ -2766,8 +2963,18 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
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()
if blob_mode != "lazy":
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
)
self._ensure_fragment_constraints_supported("to_arrow()")
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
self._table._execute_arrow(
self._query_for_scan(blob_sources), timeout=timeout
),
blob_mode=blob_mode,
blob_sources=blob_sources,
)
@@ -2862,6 +3069,29 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
# the reranker's own use, so it cannot answer "did the caller ask?".
self._caller_requested_row_id = False
def order_by(self, ordering: _OrderingInput = None) -> Self:
"""
Set the ordering for the results.
Hybrid results are fused and reranked, so ordering the two search legs
does not define the final result order. Order the returned rows after
reranking instead.
Parameters
----------
ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
Must be ``None`` or an empty list. Any non-empty ordering raises
``NotImplementedError``.
"""
normalized = _normalize_ordering(ordering)
if normalized:
raise NotImplementedError(
"order_by is not supported for hybrid queries; "
"sort the returned results after reranking instead."
)
self._order_by = None
return self
def _validate_query(self, query, vector=None, text=None):
if query is not None and (vector is not None or text is not None):
raise ValueError(
@@ -3522,6 +3752,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
def _create_query_builders(self):
"""Set up and configure the vector and FTS query builders."""
self._ensure_fragment_constraints_supported("this hybrid query")
vector_query, fts_query = self._validate_query(
self._query, self._vector, self._text
)
@@ -3640,6 +3871,19 @@ class AsyncQueryBase(object):
def _user_requested_row_id(self) -> bool:
return self._with_row_id is True
def _ensure_fragment_constraints_supported(self, operation: str) -> None:
_raise_unsupported_fragment_constraints(
self._fragments,
self._fragment_ids,
operation=operation,
)
def _inherit_fragment_constraints(self, query: Any) -> Any:
"""Carry a fragment selection across an async query conversion."""
query._fragments = self._fragments
query._fragment_ids = self._fragment_ids
return query
def _blob_auto_row_id_enabled(self) -> bool:
return self._blob_auto_row_id
@@ -3750,15 +3994,30 @@ class AsyncQueryBase(object):
return self
def with_fragments(self, fragments: Any) -> Self:
"""
Restrict scanner-backed plain query results to the given Lance fragments.
"""Restrict an embedded plain-scan blob query to the given Lance fragments.
Fragment selection is supported only when ``to_pandas()`` uses the
embedded Lance plain-scan path: the table is an embedded, non-memory
Lance dataset, the query is a plain scan (no vector, full-text, take,
postfilter, or ordering), and the selected output includes a blob
column. The constraint is preserved when converting between async
query types. Other terminals and remote tables raise
``NotImplementedError`` before scanning instead of silently scanning
the full table. Blob-specific ``to_pandas()`` fallbacks keep their
existing validation errors.
"""
self._fragments = fragments
return self
def fragment_ids(self, fragment_ids: List[int]) -> Self:
"""
Restrict scanner-backed plain query results to the given Lance fragment ids.
"""Restrict an embedded plain-scan blob query to the given fragment ids.
Fragment selection uses the same supported ``to_pandas()`` path as
``with_fragments()``. On that path, an empty list selects no rows and
missing ids raise ``ValueError``. Other terminals and remote tables
raise ``NotImplementedError`` before scanning instead of silently
scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep
their existing validation errors.
"""
self._fragment_ids = fragment_ids
return self
@@ -3831,6 +4090,17 @@ class AsyncQueryBase(object):
return AsyncRecordBatchReader._from_batches(schema, batches())
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
"""Execute with the native eager collector used by ``to_arrow``."""
self._ensure_fragment_constraints_supported("to_arrow()")
await self._maybe_add_blob_row_id()
reader = await self._inner.execute_to_reader(None, timeout)
return pa.Table.from_batches(reader, schema=reader.schema)
async def _execute_batches(
self,
*,
@@ -3838,6 +4108,7 @@ class AsyncQueryBase(object):
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
self._ensure_fragment_constraints_supported("to_batches()")
if (
blob_sources
and not self._user_requested_row_id()
@@ -3955,10 +4226,17 @@ class AsyncQueryBase(object):
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)
)
if blob_mode != "lazy":
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
)
)
else:
tbl = self._finalize_blob_query_table(
await self._execute_eager(timeout=timeout)
)
return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
async def to_list(
@@ -4245,6 +4523,7 @@ class AsyncQueryBase(object):
-------
plan : str
""" # noqa: E501
self._ensure_fragment_constraints_supported("explain_plan()")
return await self._inner.explain_plan(verbose)
async def analyze_plan(
@@ -4262,6 +4541,7 @@ class AsyncQueryBase(object):
-------
plan : str
"""
self._ensure_fragment_constraints_supported("analyze_plan()")
return await self._inner.analyze_plan(distributed_metrics)
@@ -4334,20 +4614,36 @@ class AsyncStandardQuery(AsyncQueryBase):
self._inner.offset(offset)
return self
def order_by(self, ordering: Optional[List[ColumnOrdering]]) -> Self:
def order_by(self, ordering: _OrderingInput = None) -> Self:
"""
Set the ordering for the results.
Parameters
----------
ordering: Optional[List[ColumnOrdering]]
The ordering to use for the results. If None, then the default ordering
will be used.
ordering: Optional[Union[str, tuple, ColumnOrdering, dict, list]]
The ordering to use for the results. Each entry can be a column
name, a ``(column_name, "asc"|"desc")`` tuple, a
[ColumnOrdering][lancedb.query.ColumnOrdering], or a dict with a
``column_name`` key. A bare tuple is a single direction pair, while
a list contains separate orderings, so ``("a", "desc")`` sorts by
``a`` descending and ``["a", "desc"]`` sorts by both columns.
Pass ``None`` or an empty list to clear the ordering.
Examples
--------
>>> import lancedb
>>> db = await lancedb.connect_async("memory://") # doctest: +SKIP
>>> table = await db.create_table( # doctest: +SKIP
... "ordering", [{"name": "b"}, {"name": "a"}]
... )
>>> await table.query().order_by(["name"]).to_list() # doctest: +SKIP
[{'name': 'a'}, {'name': 'b'}]
"""
if ordering is None:
normalized = _normalize_ordering(ordering)
if normalized is None:
self._inner.order_by(None)
else:
self._inner.order_by([o.model_dump() for o in ordering])
self._inner.order_by([o.model_dump() for o in normalized])
return self
def fast_search(self) -> Self:
@@ -4501,11 +4797,17 @@ class AsyncQuery(AsyncStandardQuery):
new_self = self._inner.nearest_to(query_vectors[0])
for v in query_vectors[1:]:
new_self.add_query_vector(v)
return AsyncVectorQuery(new_self, self._table)
return self._inherit_fragment_constraints(
AsyncVectorQuery(new_self, self._table)
)
else:
return AsyncVectorQuery(
self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)),
self._table,
return self._inherit_fragment_constraints(
AsyncVectorQuery(
self._inner.nearest_to(
AsyncQuery._query_vec_to_array(query_vector)
),
self._table,
)
)
def nearest_to_text(
@@ -4545,18 +4847,22 @@ class AsyncQuery(AsyncStandardQuery):
columns = []
if isinstance(query, str):
return AsyncFTSQuery(
self._inner.nearest_to_text(
{
"query": query,
"columns": columns,
"operator": fts_query.operator,
}
),
self._table,
return self._inherit_fragment_constraints(
AsyncFTSQuery(
self._inner.nearest_to_text(
{
"query": query,
"columns": columns,
"operator": fts_query.operator,
}
),
self._table,
)
)
# FullTextQuery object
return AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table)
return self._inherit_fragment_constraints(
AsyncFTSQuery(self._inner.nearest_to_text({"query": query}), self._table)
)
class AsyncFTSQuery(AsyncStandardQuery):
@@ -4577,6 +4883,7 @@ class AsyncFTSQuery(AsyncStandardQuery):
For example, ``await table.query().nearest_to_text("gripper closed",``
``operator="AND").where("active = true").count_rows()``.
"""
self._ensure_fragment_constraints_supported("count_rows()")
try:
return await self._inner.count_rows()
except Exception as error:
@@ -4662,12 +4969,34 @@ class AsyncFTSQuery(AsyncStandardQuery):
new_self = self._inner.nearest_to(query_vectors[0])
for v in query_vectors[1:]:
new_self.add_query_vector(v)
return AsyncHybridQuery(new_self, self._table)
else:
return AsyncHybridQuery(
self._inner.nearest_to(AsyncQuery._query_vec_to_array(query_vector)),
self._table,
return self._inherit_fragment_constraints(
AsyncHybridQuery(new_self, self._table)
)
else:
return self._inherit_fragment_constraints(
AsyncHybridQuery(
self._inner.nearest_to(
AsyncQuery._query_vec_to_array(query_vector)
),
self._table,
)
)
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
try:
results = await super()._execute_eager(timeout=timeout)
except Exception as error:
_add_fts_position_error_note(error)
raise
if self._reranker:
source = results
results = self._reranker.rerank_fts(self.get_query(), results)
results = _merge_query_snapshot(results, source)
return results
async def _execute_batches(
self,
@@ -5002,17 +5331,35 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
columns = []
if isinstance(query, str):
return AsyncHybridQuery(
self._inner.nearest_to_text(
{"query": query, "columns": columns, "operator": fts_query.operator}
),
self._table,
return self._inherit_fragment_constraints(
AsyncHybridQuery(
self._inner.nearest_to_text(
{
"query": query,
"columns": columns,
"operator": fts_query.operator,
}
),
self._table,
)
)
# FullTextQuery object
return AsyncHybridQuery(
self._inner.nearest_to_text({"query": query}), self._table
return self._inherit_fragment_constraints(
AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table)
)
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
results = await super()._execute_eager(timeout=timeout)
if self._reranker:
source = results
results = self._reranker.rerank_vector(self._query_string, results)
results = _merge_query_snapshot(results, source)
return results
async def _execute_batches(
self,
*,
@@ -5021,8 +5368,12 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
)
if self._reranker is None:
return reader
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
source = results
@@ -5098,6 +5449,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
the hybrid query itself. The key the legs are fused on, if any, is left
on `self._pk_fusion`.
"""
self._ensure_fragment_constraints_supported("this hybrid query")
fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table)
vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table)
@@ -5147,6 +5499,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return fts_query, vec_query, limit, offset
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
self._ensure_fragment_constraints_supported("to_arrow()")
reader = await self._execute_batches(timeout=timeout)
return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
async def _execute_batches(
self,
*,
@@ -5394,15 +5755,26 @@ class BaseQueryBuilder(object):
return self
def with_fragments(self, fragments: Any) -> Self:
"""
Restrict scanner-backed plain query results to the given Lance fragments.
"""Restrict execution to the given Lance fragments.
Fragment selection is supported only by embedded plain-scan blob
queries through ``to_pandas()``. Other terminals and remote tables
raise ``NotImplementedError`` before scanning instead of silently
scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep
their existing validation errors.
"""
self._inner.with_fragments(fragments)
return self
def fragment_ids(self, fragment_ids: List[int]) -> Self:
"""
Restrict scanner-backed plain query results to the given Lance fragment ids.
"""Restrict execution to the given Lance fragment ids.
Fragment selection is supported only by embedded plain-scan blob
queries through ``to_pandas()``. On that path, an empty list selects no
rows and missing ids raise ``ValueError``. Other terminals and remote
tables raise ``NotImplementedError`` before scanning instead of
silently scanning the full table. Blob-specific ``to_pandas()``
fallbacks keep their existing validation errors.
"""
self._inner.fragment_ids(fragment_ids)
return self
+8
View File
@@ -927,6 +927,14 @@ class RemoteTable(Table):
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
return LOOP.run(self._table._execute_arrow(query, timeout=timeout))
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
return LOOP.run(self._table._explain_plan(query, verbose))
+20 -1
View File
@@ -30,7 +30,7 @@ import warnings
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from multiprocessing import RawArray, get_context
from multiprocessing import RawArray, get_all_start_methods, get_context
from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union
import pyarrow as pa
@@ -60,6 +60,13 @@ DEFAULT_PREFETCH_BATCHES = 4
_UNSET = object()
def _default_worker_start_method() -> str:
"""Return the worker start method used when the caller omits a context."""
if "forkserver" in get_all_start_methods():
return "forkserver"
return "spawn"
class _WorkerSample(NamedTuple):
data: Any
dataset: "StreamingDataset"
@@ -1999,6 +2006,14 @@ class StreamingDataLoader(DataLoader):
because the custom iterator cannot provide the exact per-yield checkpoint
snapshots required by this loader.
When ``num_workers > 0`` and ``multiprocessing_context`` is omitted or
``None``, workers default to the ``forkserver`` start method when the
platform provides it, and to ``spawn`` otherwise. Explicit start-method
names and context objects are used unchanged. With ``num_workers == 0``,
no context is selected, leaving PyTorch's single-process behavior intact.
Callbacks and worker state must be picklable under the selected start
method, following PyTorch's DataLoader rules.
Examples
--------
>>> # dataset = StreamingDataset(table, num_splits=2)
@@ -2028,6 +2043,10 @@ class StreamingDataLoader(DataLoader):
)
self._streaming_dataset = dataset
super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs)
# Fill the default only after DataLoader has handled an explicit context;
# num_workers=0 keeps whatever PyTorch decided.
if self.num_workers > 0 and self.multiprocessing_context is None:
self.multiprocessing_context = _default_worker_start_method()
if self.drop_last:
raise ValueError(
"StreamingDataLoader does not support drop_last=True because "
+221 -4
View File
@@ -146,6 +146,9 @@ def _requires_local_namespace_execution(query: Query) -> bool:
or query.take_row_ids is not None
or query.search_effort is not None
or query.approx_mode is not None
# The namespace QueryTable request has no order_by field. Pushing a
# nonempty ordering down would drop it and return the wrong top-K rows.
or bool(query.order_by)
or (
query.full_text_query is not None
and query.fast_search is True
@@ -299,7 +302,7 @@ def _maybe_add_fts_error_note(
if TYPE_CHECKING:
from .db import LanceDBConnection
from .db import DBConnection, LanceDBConnection
from ._lancedb import (
Table as LanceDBTable,
OptimizeStats,
@@ -2923,6 +2926,15 @@ class Table(ABC):
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader: ...
def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
"""Execute a query and collect the whole result eagerly."""
return self._execute_query(query, timeout=timeout).read_all()
@abstractmethod
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: ...
@@ -4191,7 +4203,10 @@ class LanceTable(Table):
namespace_path = []
self._conn = connection
self._namespace_path = namespace_path
self._storage_options = storage_options
self._index_cache_size = index_cache_size
self._location = location # Store location for use in _dataset_path
self._managed_versioning = managed_versioning
self._namespace_client = namespace_client
self._pushdown_operations = pushdown_operations or set()
# When the connection built the namespace client natively (e.g. an
@@ -4218,6 +4233,154 @@ class LanceTable(Table):
)
# Take queries read the pushdown set from the inner table.
self._table._pushdown_operations = self._pushdown_operations
# These coordinates live on the Python wrapper: the native table only
# reports its current branch and version, not whether it is pinned.
self._branch = self._table.current_branch()
self._checkout_version: Optional[int] = None
def _pickle_connection_state(self) -> str:
"""Serialize the connection, rejecting state a worker cannot recreate."""
connection = self._conn
namespace_client = getattr(connection, "_namespace_client", None)
namespace_impl = getattr(connection, "_namespace_client_impl", None)
if namespace_client is not None and namespace_impl is None:
raise TypeError(
f"Cannot pickle LanceTable {self.name!r} backed by a namespace "
"connection whose custom namespace_client cannot be "
"reconstructed. Connect through connect_namespace(impl, "
"properties) or provide a picklable worker-side namespace "
"connection instead."
)
pickle_state = getattr(connection, "_pickle_state", None)
if pickle_state is not None:
return pickle_state()
session = getattr(connection, "session", None)
if session is not None:
raise TypeError(
"Cannot pickle a LanceTable whose connection was created with a "
"Session; Session objects are not serializable. Create the "
"Session in each worker process instead."
)
return connection.serialize()
def _namespace_client_for_pickle(self) -> Optional[Any]:
"""Keep a table-level namespace client only when pickle can carry it."""
namespace_client = self._namespace_client
if namespace_client is None:
return None
if namespace_client is getattr(self._conn, "_namespace_client", None):
# The serialized connection rebuilds its own namespace client.
return None
if namespace_client is getattr(self._conn, "_cached_namespace_client", None):
# Local manifest-mode connections cache their namespace client here.
return None
import pickle
try:
pickle.dumps(namespace_client)
except Exception as error:
raise TypeError(
f"Cannot pickle LanceTable {self.name!r}: its custom "
f"namespace_client ({type(namespace_client).__name__}) is not "
"serializable. Reopen the table in the worker through a "
"picklable namespace connection instead."
) from error
return namespace_client
@classmethod
def _open_from_pickle_state(
cls, connection: "DBConnection", state: dict[str, Any]
) -> "LanceTable":
"""Reopen a table from the state returned by ``__getstate__``."""
async_connection = getattr(connection, "_conn", None)
if async_connection is None:
async_connection = connection._inner
# Only a table-level explicit client travels in the state. A connection
# namespace client must reopen through its own provider path so caller
# storage options keep their layering; passing the reconstructed client
# here would turn it into an explicit table provider.
namespace_client = state.get("namespace_client")
async_table = LOOP.run(
async_connection.open_table(
state["name"],
namespace_path=state["namespace_path"],
storage_options=state["storage_options"],
index_cache_size=state["index_cache_size"],
location=state["location"],
namespace_client=namespace_client,
managed_versioning=state["managed_versioning"],
)
)
table = cls(
connection,
state["name"],
namespace_path=state["namespace_path"],
storage_options=state["storage_options"],
index_cache_size=state["index_cache_size"],
location=state["location"],
namespace_client=namespace_client,
managed_versioning=state["managed_versioning"],
pushdown_operations=state["pushdown_operations"],
route_pushdown_to_rust=state["route_pushdown_to_rust"],
_async=async_table,
)
version = state["checkout_version"]
if state["branch"] is not None:
table = table.branches.checkout(state["branch"], version)
elif version is not None:
table.checkout(version)
return table
def __getstate__(self) -> dict[str, Any]:
"""Return a process-independent state for pickle-based workers."""
if self._conn.uri.startswith("memory://"):
# In-memory databases cannot be reopened by name in another process.
# Keep the established behavior of exporting the visible table.
return {"kind": "memory", "name": self.name, "data": self.to_arrow()}
# The native handle is authoritative: a tag checkout can move this
# wrapper onto another branch, so never trust the branch captured at
# construction time.
self._branch = self.current_branch()
return {
"kind": "lance",
"connection_state": self._pickle_connection_state(),
"name": self.name,
"namespace_path": list(self._namespace_path),
# Only caller-supplied overrides are safe to replay. Namespace-provided
# initial options may contain rotating credentials and must be fetched
# again by the reopened connection's storage-options provider.
"storage_options": self._storage_options,
"index_cache_size": self._index_cache_size,
"location": self._location,
"namespace_client": self._namespace_client_for_pickle(),
"managed_versioning": self._managed_versioning,
"pushdown_operations": set(self._pushdown_operations),
"route_pushdown_to_rust": self._route_pushdown_to_rust,
"branch": self._branch,
"checkout_version": self._checkout_version,
}
def __setstate__(self, state: dict[str, Any]) -> None:
"""Rebuild a table from ``__getstate__`` in the current process."""
if state.get("kind") == "memory":
from . import connect
rebuilt = connect("memory://").create_table(state["name"], state["data"])
self.__dict__.update(rebuilt.__dict__)
return
from . import deserialize_conn
connection = deserialize_conn(state["connection_state"], for_worker=True)
reopened = type(self)._open_from_pickle_state(connection, state)
self.__dict__.update(reopened.__dict__)
@property
def name(self) -> str:
@@ -4456,18 +4619,23 @@ class LanceTable(Table):
def _wrap_branch_handle(
self, async_table: "AsyncTable", version: Optional[int] = None
) -> "LanceTable":
# version is unused locally: the pin already lives on async_table and a
# local handle is not reopened via a serialized connection.
return LanceTable(
table = LanceTable(
self._conn,
async_table.name,
namespace_path=self._namespace_path,
storage_options=self._storage_options,
index_cache_size=self._index_cache_size,
namespace_client=self._namespace_client,
managed_versioning=self._managed_versioning,
pushdown_operations=self._pushdown_operations,
route_pushdown_to_rust=self._route_pushdown_to_rust,
location=self._location,
_async=async_table,
)
# The native handle knows its branch but not whether this wrapper is a
# pinned branch version, so carry that coordinate explicitly.
table._checkout_version = version
return table
def checkout(self, version: Union[int, str]):
"""Checkout a version of the table. This is an in-place operation.
@@ -4506,6 +4674,8 @@ class LanceTable(Table):
0 [1.1, 0.9] vector
"""
LOOP.run(self._table.checkout(version))
self._checkout_version = self.version
self._branch = self.current_branch()
def checkout_latest(self):
"""Checkout the latest version of the table. This is an in-place operation.
@@ -4514,6 +4684,8 @@ class LanceTable(Table):
version of the table.
"""
LOOP.run(self._table.checkout_latest())
self._checkout_version = None
self._branch = self.current_branch()
def restore(self, version: Optional[Union[int, str]] = None):
"""Restore a version of the table. This is an in-place operation.
@@ -4562,6 +4734,8 @@ class LanceTable(Table):
if version is not None:
LOOP.run(self._table.checkout(version))
LOOP.run(self._table.restore())
self._checkout_version = None
self._branch = self.current_branch()
def count_rows(self, filter: Optional[str] = None) -> int:
return LOOP.run(self._table.count_rows(filter))
@@ -5651,7 +5825,9 @@ class LanceTable(Table):
self = cls.__new__(cls)
self._conn = db
self._namespace_path = namespace_path
self._index_cache_size = None
self._location = location
self._managed_versioning = None
self._namespace_client = namespace_client
self._pushdown_operations = pushdown_operations or set()
self._route_pushdown_to_rust = route_pushdown_to_rust
@@ -5679,6 +5855,7 @@ class LanceTable(Table):
enable_v2_manifest_paths
).lower()
self._storage_options = storage_options
self._table = LOOP.run(
self._conn._conn.create_table(
name,
@@ -5695,6 +5872,8 @@ class LanceTable(Table):
namespace_client=namespace_client,
)
)
self._branch = self._table.current_branch()
self._checkout_version = None
return self
def delete(self, where: Union[str, Expr]) -> DeleteResult:
@@ -5798,6 +5977,26 @@ class LanceTable(Table):
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
# Keep the Python namespace pushdown path, including its branch rule.
if (
_should_push_down_query_table(
self._namespace_client, self._pushdown_operations
)
and not self._route_pushdown_to_rust
and self.current_branch() is None
and not _requires_local_namespace_execution(query)
):
return self._execute_query(query, timeout=timeout).read_all()
async_query = self._table._sync_query_to_async(query)
return LOOP.run(async_query._execute_eager(timeout=timeout))
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
return LOOP.run(self._table._explain_plan(query, verbose))
@@ -8315,6 +8514,24 @@ class AsyncTable:
max_batch_length=batch_size, timeout=timeout
)
async def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
if (
_should_push_down_query_table(
self._namespace_client, self._pushdown_operations
)
and not self._route_pushdown_to_rust
and not _requires_local_namespace_execution(query)
):
return (await self._execute_query(query, timeout=timeout)).read_all()
async_query = self._sync_query_to_async(query)
return await async_query._execute_eager(timeout=timeout)
async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str:
# This method is used by the sync table
async_query = self._sync_query_to_async(query)
+236
View File
@@ -0,0 +1,236 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import multiprocessing as mp
import os
import subprocess
import sys
import textwrap
import traceback
import pytest
BACKGROUND_THREAD_NAME = "LanceDBBackgroundEventLoop"
def _run_in_subprocess(code: str) -> subprocess.CompletedProcess:
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
return subprocess.run(
[sys.executable, "-c", textwrap.dedent(code)],
check=False,
capture_output=True,
text=True,
env=env,
timeout=30,
)
def _assert_subprocess_ok(result: subprocess.CompletedProcess) -> None:
assert result.returncode == 0, result.stderr or result.stdout
def test_import_and_inspection_do_not_start_background_loop():
result = _run_in_subprocess(
f"""
import threading
import lancedb
from lancedb.background_loop import BackgroundEventLoop, LOOP
def background_threads():
return [
thread
for thread in threading.enumerate()
if thread.name == {BACKGROUND_THREAD_NAME!r}
]
assert LOOP.thread is None
assert LOOP.loop is None
assert background_threads() == []
# Inspecting a fresh instance is also side-effect free.
loop = BackgroundEventLoop()
assert loop.thread is None
assert loop.loop is None
assert background_threads() == []
"""
)
_assert_subprocess_ok(result)
def test_first_sync_call_starts_one_daemon_thread():
result = _run_in_subprocess(
f"""
import threading
import lancedb
from lancedb.background_loop import LOOP
def background_threads():
return [
thread
for thread in threading.enumerate()
if thread.name == {BACKGROUND_THREAD_NAME!r}
]
assert LOOP.thread is None
assert LOOP.loop is None
db = lancedb.connect("memory://")
assert db.table_names() == []
worker = LOOP.thread
assert worker is not None
assert worker is background_threads()[0]
assert len(background_threads()) == 1
assert worker.daemon
assert worker.is_alive()
assert LOOP.loop is not None
"""
)
_assert_subprocess_ok(result)
def test_concurrent_first_use_initializes_one_background_thread():
result = _run_in_subprocess(
f"""
import asyncio
import threading
from lancedb.background_loop import LOOP
worker_count = 8
barrier = threading.Barrier(worker_count)
results = []
errors = []
results_lock = threading.Lock()
def submit(index):
try:
barrier.wait(timeout=10)
value = LOOP.run(asyncio.sleep(0.05, result=index))
with results_lock:
results.append(value)
except BaseException as exc:
with results_lock:
errors.append(repr(exc))
threads = [
threading.Thread(target=submit, args=(index,))
for index in range(worker_count)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=20)
assert all(not thread.is_alive() for thread in threads)
assert errors == []
assert sorted(results) == list(range(worker_count))
background_threads = [
thread
for thread in threading.enumerate()
if thread.name == {BACKGROUND_THREAD_NAME!r}
]
assert len(background_threads) == 1
assert background_threads[0].daemon
"""
)
_assert_subprocess_ok(result)
def _fork_child_starts_lazily(queue):
def background_threads():
import threading
return [
thread
for thread in threading.enumerate()
if thread.name == BACKGROUND_THREAD_NAME
]
try:
from lancedb.background_loop import LOOP
inherited_thread_is_none = LOOP.thread is None
inherited_loop_is_none = LOOP.loop is None
background_threads_before = [thread.name for thread in background_threads()]
import lancedb
db = lancedb.connect("memory://")
tables = db.table_names()
worker = LOOP.thread
queue.put(
{
"error": None,
"inherited_thread_is_none": inherited_thread_is_none,
"inherited_loop_is_none": inherited_loop_is_none,
"background_threads_before": background_threads_before,
"tables": tables,
"thread_alive": False if worker is None else worker.is_alive(),
"thread_daemon": False if worker is None else worker.daemon,
"background_thread_count": len(background_threads()),
}
)
except BaseException:
queue.put({"error": traceback.format_exc()})
@pytest.mark.skipif(
sys.platform != "linux",
reason=(
"fork() is unavailable on Windows and unsafe on macOS "
"(Apple frameworks/TLS are not fork-safe)"
),
)
def test_forked_child_starts_background_loop_lazily():
import asyncio
from lancedb.background_loop import LOOP
assert LOOP.run(asyncio.sleep(0, result="parent-before")) == "parent-before"
parent_thread = LOOP.thread
assert parent_thread is not None
ctx = mp.get_context("fork")
queue = ctx.Queue()
# Simulate forking while another thread held the initialization lock. The
# child must replace the inherited lock instead of trying to acquire it.
LOOP._start_lock.acquire()
try:
proc = ctx.Process(target=_fork_child_starts_lazily, args=(queue,))
proc.start()
finally:
LOOP._start_lock.release()
proc.join(timeout=20)
if proc.is_alive():
proc.terminate()
proc.join(timeout=5)
if proc.is_alive():
proc.kill()
proc.join()
pytest.fail("Forked child hung starting the background loop")
assert proc.exitcode == 0, f"child exited with code {proc.exitcode}"
payload = queue.get(timeout=5)
queue.close()
assert payload["error"] is None, payload["error"]
assert payload["inherited_thread_is_none"] is True
assert payload["inherited_loop_is_none"] is True
assert payload["background_threads_before"] == []
assert payload["tables"] == []
assert payload["thread_alive"] is True
assert payload["thread_daemon"] is True
assert payload["background_thread_count"] == 1
# The child's reset must not disturb the parent's loop.
assert LOOP.thread is parent_thread
assert parent_thread.is_alive()
assert LOOP.run(asyncio.sleep(0, result="parent-after")) == "parent-after"
+24
View File
@@ -4,6 +4,7 @@
import contextlib
import inspect
import pickle
import re
import sys
from datetime import timedelta
@@ -69,6 +70,29 @@ def test_basic(tmp_path):
assert db.open_table("test").name == db["test"].name
def test_lance_db_connection_pickle_roundtrip(tmp_path):
interval = timedelta(seconds=2)
db = lancedb.connect(tmp_path, read_consistency_interval=interval)
db.create_table("pickle_conn", pa.table({"id": [1, 2]}))
restored = pickle.loads(pickle.dumps(db))
assert restored.uri == str(tmp_path)
assert restored.read_consistency_interval == interval
assert restored.open_table("pickle_conn").to_arrow()["id"].to_pylist() == [1, 2]
def test_lance_db_connection_pickle_preserves_zero_read_consistency(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(0))
table = db.create_table("pickle_zero", pa.table({"id": [1]}))
restored_db, restored_table = pickle.loads(pickle.dumps((db, table)))
lancedb.connect(tmp_path).open_table("pickle_zero").add(pa.table({"id": [2]}))
assert restored_db.read_consistency_interval == timedelta(0)
assert restored_table.to_arrow()["id"].to_pylist() == [1, 2]
def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeypatch):
from lancedb.background_loop import LOOP
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from datetime import timedelta
import pyarrow as pa
import pytest
import lancedb
@pytest.mark.asyncio
async def test_execute_to_reader_collects_without_default_slicing(tmp_path):
db = await lancedb.connect_async(tmp_path)
rows = 5000
data = pa.table(
{
"id": pa.array(range(rows), type=pa.int64()),
"text": pa.array([f"row-{i}" for i in range(rows)]),
}
)
table = await db.create_table("test", data)
reader = await table._inner.query().execute_to_reader(None, None)
batches = list(reader)
assert sum(batch.num_rows for batch in batches) == rows
assert max(batch.num_rows for batch in batches) > 1024
@pytest.mark.asyncio
async def test_execute_to_reader_preserves_empty_schema(tmp_path):
db = await lancedb.connect_async(tmp_path)
data = pa.table(
{
"id": pa.array([1, 2], type=pa.int64()),
"text": pa.array(["a", "b"]),
}
)
table = await db.create_table("test", data)
query = table._inner.query()
query.where("id < 0")
reader = await query.execute_to_reader(None, None)
result = pa.Table.from_batches(reader, schema=reader.schema)
assert result.num_rows == 0
assert result.schema == await table.query().where("id < 0").output_schema()
@pytest.mark.asyncio
async def test_execute_to_reader_propagates_timeout(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("test", data=[{"id": 1}, {"id": 2}])
with pytest.raises(Exception, match="Query timeout"):
await table._inner.query().execute_to_reader(None, timedelta(0))
@@ -32,6 +32,7 @@ Parameters used throughout:
import dataclasses
import logging
import multiprocessing as mp
import threading
from unittest.mock import patch
@@ -1028,6 +1029,105 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table):
)
# ── Worker start method defaults ─────────────────────────────────────────────
def _loader_start_method(loader: StreamingDataLoader) -> str:
context = loader.multiprocessing_context
if isinstance(context, str):
return context
assert context is not None
return context.get_start_method()
def _platform_worker_start_method() -> str:
return "forkserver" if "forkserver" in mp.get_all_start_methods() else "spawn"
def test_default_worker_start_method_prefers_forkserver():
with patch.object(
streaming,
"get_all_start_methods",
return_value=["fork", "spawn", "forkserver"],
):
assert streaming._default_worker_start_method() == "forkserver"
def test_streaming_dataloader_falls_back_to_spawn_without_forkserver(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
with patch.object(streaming, "get_all_start_methods", return_value=["spawn"]):
loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1)
assert _loader_start_method(loader) == "spawn"
def test_streaming_dataloader_omitted_context_uses_platform_method(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
loader = StreamingDataLoader(dataset, batch_size=2, num_workers=1)
assert _loader_start_method(loader) == _platform_worker_start_method()
def test_streaming_dataloader_treats_none_context_as_omitted(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
loader = StreamingDataLoader(
dataset,
batch_size=2,
num_workers=1,
multiprocessing_context=None,
)
assert _loader_start_method(loader) == _platform_worker_start_method()
def test_streaming_dataloader_preserves_explicit_start_method(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
loader = StreamingDataLoader(
dataset,
batch_size=2,
num_workers=1,
multiprocessing_context="spawn",
)
assert _loader_start_method(loader) == "spawn"
def test_streaming_dataloader_preserves_explicit_context_object(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
context = mp.get_context("spawn")
loader = StreamingDataLoader(
dataset,
batch_size=2,
num_workers=1,
multiprocessing_context=context,
)
assert loader.multiprocessing_context is context
def test_streaming_dataloader_zero_workers_leave_context_unset(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
loader = StreamingDataLoader(dataset, batch_size=12, num_workers=0)
assert loader.multiprocessing_context is None
ids = [row_id for batch in loader for row_id in batch["id"].tolist()]
assert sorted(ids) == list(range(NUM_ROWS))
def test_streaming_dataloader_default_context_runs_real_worker(lance_table):
dataset = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle=False)
loader = StreamingDataLoader(dataset, batch_size=12, num_workers=1)
assert _loader_start_method(loader) == _platform_worker_start_method()
iterator = iter(loader)
try:
ids = [row_id for batch in iterator for row_id in batch["id"].tolist()]
finally:
iterator._shutdown_workers()
assert sorted(ids) == list(range(NUM_ROWS))
# ── Resumability with num_workers ─────────────────────────────────────────────
+4 -2
View File
@@ -1655,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object():
def test_fts_phrase_query_execution_preserves_user_text():
table = mock.Mock()
table.schema = pa.schema([])
table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader()
# to_arrow() collects through the eager path; keep a real Table so the
# reranker still receives and returns the real result contract.
table._execute_arrow.return_value = pa.table({"text": ["result"]})
class CapturingReranker:
score = "relevance"
@@ -1677,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text():
query.to_arrow()
backend_query = table._execute_query.call_args.args[0]
backend_query = table._execute_arrow.call_args.args[0]
assert (
backend_query.full_text_query.query,
reranker.queries,
@@ -20,6 +20,7 @@ from typing import Annotated, Optional, get_type_hints
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pytest
from lancedb import col
@@ -582,6 +583,48 @@ def test_array_batch_annotations_accept_explicit_schemas():
assert identity(values).equals(values)
def test_batch_functions_take_one_array_parameter_per_input_column():
@function(
input_schema=pa.schema(
[
pa.field("value", pa.float64(), nullable=False),
pa.field("weight", pa.float64(), nullable=False),
]
),
output_schema=pa.float64(),
)
def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array:
return pc.multiply(value, weight)
signature = weighted_score.registration_request.signature
assert [parameter.name for parameter in signature.inputs] == ["value", "weight"]
result = weighted_score(pa.array([1.0, 2.0]), pa.array([3.0, 4.0]))
assert result.to_pylist() == [3.0, 8.0]
@pytest.mark.parametrize(
"invoke",
[
lambda definition: definition(col("value")),
lambda definition: definition(value=col("value")),
lambda definition: definition(value=col("value") * 2),
],
ids=["positional", "keyword", "derived"],
)
def test_definition_calls_reject_expr_inputs_before_user_code(invoke):
@function
def double(value: float) -> float:
raise AssertionError("user code ran")
with pytest.raises(TypeError, match="registered FunctionVersion"):
invoke(double)
def test_class_definition_binds_initialization_only_on_a_version():
with pytest.raises(TypeError, match="registered FunctionVersion"):
scale(factor=col("factor"), label="x")
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("postponed", [False, True])
@pytest.mark.parametrize(
+25
View File
@@ -81,6 +81,31 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable):
assert result["_rowid"].to_pylist() == [0, 3]
def test_hybrid_fragment_constraints_fail_loud(sync_table: Table):
query = (
sync_table.search("dog", query_type="hybrid")
.vector([0.5, -0.5])
.fragment_ids([0])
)
with pytest.raises(NotImplementedError, match="fragment selection"):
query.to_arrow()
with pytest.raises(NotImplementedError, match="fragment selection"):
query.explain_plan()
@pytest.mark.asyncio
async def test_async_hybrid_fragment_constraints_fail_loud(table: AsyncTable):
query = (
table.query().nearest_to([0.5, -0.5]).nearest_to_text("dog").fragment_ids([0])
)
with pytest.raises(NotImplementedError, match="fragment selection"):
await query.to_arrow()
with pytest.raises(NotImplementedError, match="fragment selection"):
await query.analyze_plan()
@pytest.mark.asyncio
async def test_async_hybrid_query_filters(table: AsyncTable):
# test that query params are passed down from the regular builder to
+456 -1
View File
@@ -6,6 +6,8 @@
import tempfile
import shutil
import importlib
import asyncio
import pickle
import warnings
import http.server
import json
@@ -16,6 +18,7 @@ import copy
import pyarrow as pa
import lancedb
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
from lance_namespace import DescribeTableResponse
from utils import start_server_thread
from lancedb.listing import AsyncListing, Listing
from lancedb.index import FTS
@@ -26,7 +29,7 @@ from lancedb.namespace import (
LanceNamespaceDBConnection,
_query_to_namespace_request,
)
from lancedb.query import FullTextSearchQuery, Query
from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query
from lancedb.table import AsyncTable, LanceTable
@@ -35,6 +38,37 @@ PUSHDOWN_DATA = pa.table(
)
class _RefreshNamespaceWithExpiringOptions(LanceNamespace):
def __init__(self, root):
self.root = root
def namespace_id(self):
return f"refresh-test:{self.root}"
def describe_table(self, request):
from pathlib import Path
return DescribeTableResponse(
location=str(Path(self.root) / "t.lance"),
storage_options={"vended": "fresh", "expires_at_millis": "1"},
)
class _DeclaredNamespaceWithoutProperties(LanceNamespace):
root = None
def __init__(self):
from lance.namespace import DirectoryNamespace
self.client = DirectoryNamespace(root=self.root)
def namespace_id(self):
return self.client.namespace_id()
def describe_table(self, request):
return self.client.describe_table(request)
@pytest.mark.asyncio
@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]])
async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
@@ -56,6 +90,70 @@ async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
assert await adb.table_exists(table_id) is (table_id != ["missing"])
def test_table_pickle_rejects_custom_namespace_connection(tmp_path):
pytest.importorskip("lance")
from lance.namespace import DirectoryNamespace
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
"t", [{"id": 1}]
)
class UnserializableNamespace(LanceNamespace):
def __init__(self, root):
from threading import Lock
self.client = DirectoryNamespace(root=str(root))
self.lock = Lock()
def namespace_id(self):
return self.client.namespace_id()
def describe_table(self, request):
return self.client.describe_table(request)
db = LanceNamespaceDBConnection(UnserializableNamespace(tmp_path))
table = db.open_table("t")
with pytest.raises(TypeError, match="namespace"):
pickle.dumps(table)
def test_declared_namespace_pickle_keeps_caller_options_after_refresh(tmp_path):
lancedb.connect(tmp_path).create_table("t", [{"id": 1}])
db = lancedb.connect_namespace(
f"{__name__}._RefreshNamespaceWithExpiringOptions", {"root": str(tmp_path)}
)
table = db.open_table("t", storage_options={"caller_only": "keep"})
restored = pickle.loads(pickle.dumps(table))
for current in (table, restored):
options = current.latest_storage_options()
assert options["caller_only"] == "keep"
assert options["vended"] == "fresh"
def test_table_pickle_allows_declared_namespace_without_properties(tmp_path):
pytest.importorskip("lance")
lancedb.connect_namespace("dir", {"root": str(tmp_path)}).create_table(
"t", [{"id": 1}]
)
_DeclaredNamespaceWithoutProperties.root = str(tmp_path)
try:
impl = f"{__name__}._DeclaredNamespaceWithoutProperties"
db = LanceNamespaceDBConnection(
_DeclaredNamespaceWithoutProperties(), namespace_client_impl=impl
)
table = db.open_table("t")
restored = pickle.loads(pickle.dumps(table))
assert restored.to_arrow()["id"].to_pylist() == [1]
finally:
_DeclaredNamespaceWithoutProperties.root = None
class TestNamespaceCreateTableOptions:
@pytest.mark.parametrize("version", ["legacy", "stable"])
@pytest.mark.parametrize("empty", [False, True])
@@ -309,6 +407,328 @@ def paginated_rest_namespace():
thread.join()
def test_rest_namespace_table_pickle_keeps_live_storage_options(tmp_path):
from time import time
local = lancedb.connect(tmp_path)
local.create_table("t", [{"id": 1}])
location = str(tmp_path / "t.lance")
ipc = _ipc_file(pa.table({"id": [42]}))
seen = []
current_options = {
"block_size": "4096",
"expires_at_millis": str(int(time() * 1000) + 30_000),
}
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", "0")))
path = urlparse(self.path).path
seen.append(path)
if path.endswith("/describe"):
body = json.dumps(
{"location": location, "storage_options": current_options}
).encode()
content_type = "application/json"
elif path.endswith("/query"):
body = ipc
content_type = "application/vnd.apache.arrow.file"
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
db = lancedb.connect_namespace(
"rest",
{"uri": f"http://127.0.0.1:{server.server_port}"},
namespace_client_pushdown_operations=["QueryTable"],
)
table = db.open_table("t")
restored = pickle.loads(pickle.dumps(table))
seen.clear()
assert restored.search().limit(1).to_list() == [{"id": 42}]
assert seen == ["/v1/table/t/query"]
current_options = {
"block_size": "8192",
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
}
assert table.latest_storage_options()["block_size"] == "8192"
assert restored.latest_storage_options()["block_size"] == "8192"
finally:
server.shutdown()
thread.join()
def test_rest_namespace_create_empty_refresh_does_not_restore_expired_seed(tmp_path):
from time import time
location = str(tmp_path / "t.lance")
current_options = {
"vended_seed": "short-lived",
"expires_at_millis": str(int(time() * 1000) + 30_000),
}
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", "0")))
path = urlparse(self.path).path
if not (path.endswith("/declare") or path.endswith("/describe")):
self.send_error(404)
return
body = json.dumps(
{"location": location, "storage_options": current_options}
).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
db = lancedb.connect_namespace(
"rest", {"uri": f"http://127.0.0.1:{server.server_port}"}
)
table = db.create_table("t", [{"id": 1}])
payload = pickle.dumps(table)
assert b"short-lived" not in payload
restored = pickle.loads(payload)
current_options = {}
assert table.latest_storage_options() == {}
assert restored.latest_storage_options() == {}
finally:
server.shutdown()
thread.join()
@pytest.mark.parametrize("entrypoint", ["create", "open"])
def test_rest_namespace_pickle_layers_caller_storage_options(tmp_path, entrypoint):
from time import time
location = str(tmp_path / "t.lance")
caller_options = {"caller_option": "kept", "conflict": "caller"}
vended_options = {
"vended_1": "old",
"conflict": "vended",
"expires_at_millis": str(int(time() * 1000) + 30_000),
}
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", "0")))
path = urlparse(self.path).path
if path.endswith("/declare") or path.endswith("/describe"):
body = json.dumps(
{"location": location, "storage_options": vended_options}
).encode()
else:
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
db = lancedb.connect_namespace(
"rest",
{"uri": f"http://127.0.0.1:{server.server_port}"},
)
if entrypoint == "create":
table = db.create_table(
"t", [{"id": 1}], storage_options=caller_options
)
else:
db.create_table("t", [{"id": 1}])
table = db.open_table("t", storage_options=caller_options)
restored = pickle.loads(pickle.dumps(table))
for current in (table, restored):
options = current.latest_storage_options()
assert options["caller_option"] == "kept"
assert options["conflict"] == "vended"
vended_options.update(
{
"vended_2": "new",
"conflict": "vended-new",
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
}
)
for current in (table, restored):
options = current.latest_storage_options()
assert options["caller_option"] == "kept"
assert options["vended_2"] == "new"
assert options["conflict"] == "vended-new"
finally:
server.shutdown()
thread.join()
def test_namespace_open_uses_explicit_storage_options_provider(tmp_path):
from time import time
from lancedb._lancedb import connect_namespace as connect_namespace_inner
from lancedb.db import AsyncConnection
location = str(tmp_path / "t.lance")
seed_options = {
"vended_seed": "short-lived",
"expires_at_millis": str(int(time() * 1000) + 30_000),
}
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", "0")))
path = urlparse(self.path).path
if not (path.endswith("/declare") or path.endswith("/describe")):
self.send_error(404)
return
result = {"location": location, "storage_options": seed_options}
body = json.dumps(result).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class ExplicitClient(LanceNamespace):
calls = 0
def namespace_id(self):
return "explicit-storage-options-provider"
def describe_table(self, request):
self.calls += 1
return DescribeTableResponse(
location=location,
storage_options={
"explicit_provider": "fresh",
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
},
)
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
db = lancedb.connect_namespace("rest", properties)
db.create_table("t", [{"id": 1}])
async def check():
connection = AsyncConnection(
connect_namespace_inner("rest", properties)
)
client = ExplicitClient()
table = await connection.open_table("t", namespace_client=client)
options = await table.latest_storage_options()
assert client.calls > 0
assert options["explicit_provider"] == "fresh"
asyncio.run(check())
finally:
server.shutdown()
thread.join()
def test_namespace_create_without_seed_uses_connection_provider(tmp_path):
from time import time
from lancedb._lancedb import connect_namespace as connect_namespace_inner
from lancedb.db import AsyncConnection
location = str(tmp_path / "t.lance")
seed_options = {
"vended_seed": "short-lived",
"expires_at_millis": str(int(time() * 1000) + 30_000),
}
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", "0")))
path = urlparse(self.path).path
result = {"location": location}
if path.endswith("/describe"):
result["storage_options"] = seed_options
elif not path.endswith("/declare"):
self.send_error(404)
return
body = json.dumps(result).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class ExplicitClient(LanceNamespace):
calls = 0
def namespace_id(self):
return "explicit-storage-options-provider"
def describe_table(self, request):
self.calls += 1
return DescribeTableResponse(
location=location,
storage_options={
"explicit_provider": "fresh",
"expires_at_millis": str(int(time() * 1000) + 3_600_000),
},
)
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
properties = {"uri": f"http://127.0.0.1:{server.server_port}"}
async def check():
connection = AsyncConnection(
connect_namespace_inner("rest", properties)
)
client = ExplicitClient()
table = await connection.create_table(
"t", [{"id": 1}], namespace_client=client
)
options = await table.latest_storage_options()
assert client.calls == 0
assert options["vended_seed"] == "short-lived"
asyncio.run(check())
finally:
server.shutdown()
thread.join()
@pytest.mark.asyncio
@pytest.mark.parametrize("namespace_path", [[], ["n"]])
async def test_rest_namespace_table_names_collects_pages(
@@ -1352,6 +1772,23 @@ class TestPushdownOperations:
assert request.maximum_nprobes == 0
assert request.to_dict()["maximum_nprobes"] == 0
def test_lance_table_order_by_is_not_pushed_down(self, tmp_path):
namespace_client = _NamespaceClient()
db = lancedb.connect(str(tmp_path / "db"))
table = db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
table._namespace_path = ["geneva"]
table._namespace_client = namespace_client
table._pushdown_operations = {"QueryTable"}
table._route_pushdown_to_rust = False
result = table._execute_query(
Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
).read_all()
# Pushing this query down would drop order_by and return id 3.
assert result.column("id").to_pylist() == [1]
assert namespace_client.requests == []
@pytest.mark.asyncio
class TestAsyncPushdownOperations:
@@ -1414,6 +1851,24 @@ class TestAsyncPushdownOperations:
assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K]
assert all(r.k <= 2**31 - 1 for r in namespace_client.requests)
async def test_async_table_order_by_is_not_pushed_down(self, tmp_path):
namespace_client = _NamespaceClient()
db = await lancedb.connect_async(str(tmp_path / "db"))
table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}, {"id": 2}])
table._namespace_path = ["geneva"]
table._namespace_client = namespace_client
table._pushdown_operations = {"QueryTable"}
table._route_pushdown_to_rust = False
result = await table._execute_query(
Query(limit=1, order_by=[ColumnOrdering(column_name="id")])
)
# Pushing this query down would drop order_by and return id 3.
batches = await result.read_all()
assert pa.Table.from_batches(batches).column("id").to_pylist() == [1]
assert namespace_client.requests == []
@pytest.mark.parametrize(
"query_kwargs",
[
+79 -1
View File
@@ -7,7 +7,13 @@ import pytest
from lancedb import DBConnection, Table, connect
from lancedb.background_loop import LOOP
from lancedb.permutation import Permutation, Permutations, permutation_builder
from lancedb.permutation import (
DEFAULT_BATCH_SIZE,
Permutation,
Permutations,
Transforms,
permutation_builder,
)
from utils import (
MockPermutationServer,
assert_server_safe_row_id_requests,
@@ -81,6 +87,43 @@ def test_pickled_permutation_reads_pinned_version(tmp_path):
assert sorted(row["idx"] for row in rows) == list(range(20))
def test_builder_copy_is_shallow_and_does_not_materialize(
some_table: Table, some_perm_table: Table, monkeypatch
):
"""The with_* builders use copy.copy, which must stay a shallow copy.
Without ``Permutation.__copy__`` the copy falls back to the pickle path,
which materializes the permutation table with ``to_arrow()`` before
rebuilding the base table and reader. That is expensive for in-memory
tables and fails for remote permutation tables.
"""
permutation = Permutation.from_tables(some_table, some_perm_table)
def fail_materialize(*args, **kwargs):
raise AssertionError("copy.copy must not materialize the permutation table")
def fail_getstate(_self):
raise AssertionError("copy.copy must not pickle the permutation")
monkeypatch.setattr(permutation.permutation_table, "to_arrow", fail_materialize)
monkeypatch.setattr(Permutation, "__getstate__", fail_getstate)
formatted = permutation.with_format("arrow")
assert formatted is not permutation
assert formatted.transform_fn is Transforms.arrow2arrow
assert permutation.transform_fn is Transforms.arrow2python
assert formatted.base_table is permutation.base_table
assert formatted.permutation_table is permutation.permutation_table
assert formatted.reader is permutation.reader
resized = permutation.with_batch_size(7)
assert resized.batch_size == 7
assert permutation.batch_size == DEFAULT_BATCH_SIZE
assert resized.selection is permutation.selection
resized.selection = {"id": "id"}
assert permutation.selection is not resized.selection
def test_split_random_counts(mem_db):
"""Test random splitting with absolute counts."""
tbl = mem_db.create_table(
@@ -275,6 +318,41 @@ def test_split_hash(mem_db):
assert data["split_id"] == data2["split_id"] # Should be identical
def test_split_hash_default_discard_weight_matches_zero(mem_db):
"""Omitting discard_weight must assign every row like discard_weight=0."""
tbl = mem_db.create_table(
"test_table",
pa.table(
{
"id": range(100),
"category": (["A", "B", "C"] * 34)[:100],
"value": range(100),
}
),
)
default = (
permutation_builder(tbl)
.split_hash(["category"], [1, 1], split_names=["train", "test"])
.execute()
)
explicit_zero = (
permutation_builder(tbl)
.split_hash(
["category"], [1, 1], discard_weight=0, split_names=["train", "test"]
)
.execute()
)
default_data = default.search(None).to_arrow().to_pydict()
explicit_data = explicit_zero.search(None).to_arrow().to_pydict()
assert default.count_rows() == 100
assert default.count_rows() == explicit_zero.count_rows()
assert dict(zip(default_data["row_id"], default_data["split_id"])) == dict(
zip(explicit_data["row_id"], explicit_data["split_id"])
)
def test_split_hash_with_discard(mem_db):
"""Test hash-based splitting with discard weight."""
tbl = mem_db.create_table(
+339 -2
View File
@@ -69,6 +69,36 @@ def _blob_query_data():
)
def _fragment_query_data():
return pa.table(
{
"id": pa.array([1, 2, 3, 4], pa.int64()),
"text": pa.array(["one", "two", "three", "four"], pa.utf8()),
"vector": pa.array(
[[1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]],
type=pa.list_(pa.float32(), list_size=2),
),
}
)
def _fragment_query_table(db, name):
data = _fragment_query_data()
table = db.create_table(name, data.slice(0, 2))
table.add(data.slice(2, 2))
return table
def _apply_fragment_restriction(query, restriction, fragment):
if restriction == "ids":
return query.fragment_ids([fragment.fragment_id])
if restriction == "empty":
return query.fragment_ids([])
if restriction == "fragments":
return query.with_fragments([fragment])
raise AssertionError(f"unknown restriction: {restriction}")
def _create_blob_v2_query_table(db, name):
schema = pa.schema(
[
@@ -435,6 +465,207 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db):
)
assert df_by_fragment["id"].tolist() == [1, 2]
empty = (
table.search()
.select(["id", "blob"])
.fragment_ids([])
.to_pandas(blob_mode="descriptions")
)
assert empty.empty
with pytest.raises(ValueError, match="fragment_ids not found in dataset: 999"):
(
table.search()
.select(["id", "blob"])
.fragment_ids([999])
.to_pandas(blob_mode="descriptions")
)
@pytest.mark.parametrize(
"terminal",
[
"to_arrow",
"to_batches",
"to_pandas",
"to_polars",
"to_list",
"explain_plan",
"analyze_plan",
],
)
def test_fragment_constraints_fail_loud_on_unsupported_paths(tmp_db, terminal):
pytest.importorskip("lance")
table = _fragment_query_table(tmp_db, f"fragment_guard_{terminal}")
fragment_id = table.to_lance().get_fragments()[0].fragment_id
query = table.search().fragment_ids([fragment_id])
with pytest.raises(NotImplementedError, match="fragment selection"):
getattr(query, terminal)()
def test_with_fragments_fails_loud_on_plain_and_vector_queries(tmp_db):
pytest.importorskip("lance")
table = _fragment_query_table(tmp_db, "fragment_guard_with_fragments")
fragment = table.to_lance().get_fragments()[0]
for query in (
table.search().with_fragments([fragment]),
table.search([0.0, 0.0]).with_fragments([fragment]),
):
with pytest.raises(NotImplementedError, match="fragment selection"):
query.to_arrow()
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
def test_fts_count_rows_rejects_fragment_constraints(tmp_db, restriction):
pytest.importorskip("lance")
table = _fragment_query_table(tmp_db, f"fts_count_rows_{restriction}")
table.create_index("text", config=FTS(with_position=False))
fragment = table.to_lance().get_fragments()[1]
query = _apply_fragment_restriction(
table.search("one", query_type="fts"), restriction, fragment
)
with pytest.raises(NotImplementedError, match="fragment selection"):
query.count_rows()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"terminal",
[
"to_arrow",
"to_batches",
"to_pandas",
"to_polars",
"to_list",
"explain_plan",
"analyze_plan",
],
)
async def test_async_fragment_constraints_fail_loud_on_unsupported_paths(
tmp_db_async, terminal
):
pytest.importorskip("lance")
data = _fragment_query_data()
table = await tmp_db_async.create_table(
f"async_fragment_guard_{terminal}", data.slice(0, 2)
)
await table.add(data.slice(2, 2))
fragments = (await table.to_lance()).get_fragments()
query = table.query().fragment_ids([fragments[0].fragment_id])
with pytest.raises(NotImplementedError, match="fragment selection"):
await getattr(query, terminal)()
@pytest.mark.asyncio
async def test_async_with_fragments_fails_loud_on_plain_and_vector_queries(
tmp_db_async,
):
pytest.importorskip("lance")
data = _fragment_query_data()
table = await tmp_db_async.create_table(
"async_fragment_guard_with_fragments", data.slice(0, 2)
)
await table.add(data.slice(2, 2))
fragments = (await table.to_lance()).get_fragments()
for query in (
table.query().with_fragments([fragments[0]]),
table.query().nearest_to([0.0, 0.0]).with_fragments([fragments[0]]),
):
with pytest.raises(NotImplementedError, match="fragment selection"):
await query.to_arrow()
@pytest.mark.asyncio
async def test_async_plain_scan_fragment_constraints_preserved(tmp_db_async):
pytest.importorskip("lance")
data = _blob_query_data()
table = await tmp_db_async.create_table(
"async_fragment_supported",
data.slice(0, 2),
storage_options=LEGACY_BLOB_STORAGE_OPTIONS,
)
await table.add(data.slice(2, 2))
fragments = (await table.to_lance()).get_fragments()
df = await (
table.query()
.select(["id", "blob"])
.fragment_ids([fragments[1].fragment_id])
.to_pandas(blob_mode="descriptions")
)
assert df["id"].tolist() == [3, 4]
@pytest.mark.asyncio
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
async def test_async_fts_count_rows_rejects_fragment_constraints(
tmp_db_async, restriction
):
pytest.importorskip("lance")
data = _fragment_query_data()
table = await tmp_db_async.create_table(
f"async_fts_count_rows_{restriction}", data.slice(0, 2)
)
await table.add(data.slice(2, 2))
await table.create_index("text", config=FTS(with_position=False))
fragment = (await table.to_lance()).get_fragments()[1]
query = _apply_fragment_restriction(
table.query().nearest_to_text("one"), restriction, fragment
)
with pytest.raises(NotImplementedError, match="fragment selection"):
await query.count_rows()
transitioned = _apply_fragment_restriction(
table.query(), restriction, fragment
).nearest_to_text("one")
with pytest.raises(NotImplementedError, match="fragment selection"):
await transitioned.count_rows()
@pytest.mark.asyncio
@pytest.mark.parametrize("restriction", ["ids", "empty", "fragments"])
@pytest.mark.parametrize(
"transition",
["query_to_vector", "query_to_fts", "fts_to_hybrid", "vector_to_hybrid"],
)
async def test_async_fragment_constraints_survive_query_transitions(
tmp_db_async, transition, restriction
):
pytest.importorskip("lance")
data = _fragment_query_data()
table = await tmp_db_async.create_table(
f"async_transition_{transition}_{restriction}", data.slice(0, 2)
)
await table.add(data.slice(2, 2))
await table.create_index("text", config=FTS(with_position=False))
fragment = (await table.to_lance()).get_fragments()[1]
if transition == "query_to_vector":
query = _apply_fragment_restriction(
table.query(), restriction, fragment
).nearest_to([0.0, 0.0])
elif transition == "query_to_fts":
query = _apply_fragment_restriction(
table.query(), restriction, fragment
).nearest_to_text("one")
elif transition == "fts_to_hybrid":
query = _apply_fragment_restriction(
table.query().nearest_to_text("one"), restriction, fragment
).nearest_to([0.0, 0.0])
else:
query = _apply_fragment_restriction(
table.query().nearest_to([0.0, 0.0]), restriction, fragment
).nearest_to_text("one")
with pytest.raises(NotImplementedError, match="fragment selection"):
await query.to_arrow()
@pytest.mark.asyncio
async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async):
@@ -811,6 +1042,113 @@ async def test_order_by_async_query(mem_db_async: AsyncConnection):
]
def test_order_by_accepts_strings_tuples_and_dicts(mem_db):
table = mem_db.create_table(
"test_order_by_forms",
pa.table(
{
"group": [1, 1, 1, 2],
"score": [None, 1.0, 1.0, 0.5],
"name": ["z", "b", "a", "c"],
}
),
)
rows = (
table.search()
.order_by(
[
"group",
("score", "desc"),
{"column_name": "name", "ascending": True},
]
)
.select(["name"])
.to_list()
)
assert rows == [{"name": "a"}, {"name": "b"}, {"name": "z"}, {"name": "c"}]
# A bare tuple is one direction pair; a list holds separate orderings.
assert table.search().order_by("name").select(["name"]).to_list() == [
{"name": "a"},
{"name": "b"},
{"name": "c"},
{"name": "z"},
]
assert table.search().order_by(("name", "desc")).select(["name"]).to_list() == [
{"name": "z"},
{"name": "c"},
{"name": "b"},
{"name": "a"},
]
assert table.search().order_by(["group", "name"]).select(["name"]).to_list() == [
{"name": "a"},
{"name": "b"},
{"name": "z"},
{"name": "c"},
]
def test_order_by_clears_with_none_and_empty_list(mem_db):
table = mem_db.create_table("test_order_by_clear", [{"name": "a"}])
query = table.search().order_by("name")
assert query.to_query_object().order_by is not None
assert query.order_by(None).to_query_object().order_by is None
assert query.order_by([]).to_query_object().order_by is None
def test_order_by_rejects_invalid_input_early(mem_db):
table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}])
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
table.search().order_by([{"column": "name", "ascending": True}])
with pytest.raises(ValueError, match="missing 'column_name'"):
table.search().order_by({"ascending": True})
with pytest.raises(ValueError, match="invalid direction"):
table.search().order_by([("name", "sideways")])
with pytest.raises(TypeError, match="must be a column name"):
table.search().order_by([42])
@pytest.mark.asyncio
async def test_order_by_async_accepts_dicts_and_clears(mem_db_async: AsyncConnection):
table = await mem_db_async.create_table(
"test_order_by_async_forms",
pa.table({"name": ["z", "b", "a", "c"]}),
)
rows = await (
table.query().order_by([{"column_name": "name", "ascending": False}]).to_arrow()
)
assert rows["name"].to_pylist() == ["z", "c", "b", "a"]
query = table.query().order_by("name")
assert query.to_query_object().order_by is not None
assert query.order_by(None).to_query_object().order_by is None
assert query.order_by([]).to_query_object().order_by is None
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
table.query().order_by([{"column": "name"}])
def test_column_ordering_is_exported_at_top_level():
assert lancedb.ColumnOrdering is ColumnOrdering
def test_order_by_hybrid_sync_is_explicitly_unsupported(table):
query = table.search(query_type="hybrid").vector([1.0, 2.0]).text("a")
with pytest.raises(NotImplementedError, match="order_by is not supported"):
query.order_by(["id"])
# Clearing is still allowed, and invalid input still fails on its own terms.
query.order_by(None)
query.order_by([])
with pytest.raises(ValueError, match="unsupported key\\(s\\)"):
query.order_by([{"column": "id"}])
def test_query_builder(table):
rs = (
LanceVectorQueryBuilder(table, [0, 0], "vector")
@@ -1401,7 +1739,7 @@ def test_query_builder_with_different_vector_column():
ds = mock.Mock()
table.to_lance.return_value = ds
builder.to_arrow()
table._execute_query.assert_called_once_with(
table._execute_arrow.assert_called_once_with(
Query(
vector=query,
filter="b < 10",
@@ -1410,7 +1748,6 @@ def test_query_builder_with_different_vector_column():
columns=["b"],
vector_column="foo_vector",
),
batch_size=None,
timeout=None,
)
+32 -4
View File
@@ -4163,6 +4163,36 @@ def query_test_table(
yield table
def test_remote_fragment_constraints_fail_before_query():
query_calls = 0
def query_handler(body):
nonlocal query_calls
query_calls += 1
return pa.table({"text": ["unexpected"]})
with query_test_table(query_handler) as table:
with pytest.raises(NotImplementedError, match="fragment selection"):
table.search().fragment_ids([0]).to_arrow()
assert query_calls == 0
def test_remote_fts_count_rows_rejects_fragment_constraints():
query_calls = 0
def query_handler(body):
nonlocal query_calls
query_calls += 1
return pa.table({"text": ["unexpected"]})
with query_test_table(query_handler) as table:
with pytest.raises(NotImplementedError, match="fragment selection"):
table.search("hello", query_type="fts").fragment_ids([0]).count_rows()
assert query_calls == 0
@pytest.mark.parametrize(
"query,search_kwargs,expected_column",
[
@@ -5340,12 +5370,10 @@ def test_background_loop_cancellation(exception):
mock_future = MagicMock()
mock_future.result.side_effect = exception()
with (
patch.object(BackgroundEventLoop, "__init__", return_value=None),
patch("asyncio.run_coroutine_threadsafe", return_value=mock_future),
):
with patch("asyncio.run_coroutine_threadsafe", return_value=mock_future):
loop = BackgroundEventLoop()
loop.loop = MagicMock()
loop.thread = MagicMock()
with pytest.raises(exception):
loop.run(None)
mock_future.cancel.assert_called_once()
+123
View File
@@ -6,6 +6,7 @@ import ctypes
import gc
import json
import os
import pickle
import sys
import threading
import warnings
@@ -1228,6 +1229,128 @@ def test_list_versions_timestamp_precision_remote():
assert versions[0]["timestamp"].microsecond == 274000
def test_lance_table_is_picklable(tmp_db: DBConnection):
table = tmp_db.create_table("pickle_table", pa.table({"id": [1, 2, 3]}))
payload = pickle.dumps(table)
# A standard-mode handle must reopen at latest, not freeze the version that
# happened to be current when pickle.dumps ran.
tmp_db.open_table("pickle_table").add(pa.table({"id": [4]}))
restored = pickle.loads(payload)
assert restored.name == "pickle_table"
assert restored.count_rows() == 4
assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3, 4]
def test_lance_table_pickle_preserves_checkout(tmp_db: DBConnection):
table = tmp_db.create_table("pickle_checkout", pa.table({"id": [1]}))
table.add(pa.table({"id": [2]}))
table.checkout(1)
payload = pickle.dumps(table)
tmp_db.open_table("pickle_checkout").add(pa.table({"id": [3]}))
restored = pickle.loads(payload)
assert restored.version == 1
assert restored.to_arrow()["id"].to_pylist() == [1]
restored.checkout_latest()
assert restored.version == 3
assert restored.to_arrow()["id"].to_pylist() == [1, 2, 3]
def test_lance_table_pickle_preserves_cross_branch_tag_checkout(tmp_path):
db = lancedb.connect(tmp_path)
main = db.create_table("pickle_tag_branch", pa.table({"id": [0]}))
branch = main.branches.create("exp")
branch.add(pa.table({"id": [1]}))
branch.tags.create("exp_tag", branch.version)
# Advance main independently, then resolve a tag that points into exp.
main.add(pa.table({"id": [9]}))
main.checkout("exp_tag")
assert main.current_branch() == "exp"
assert main.version == 2
assert main.to_arrow()["id"].to_pylist() == [0, 1]
restored = pickle.loads(pickle.dumps(main))
assert restored.current_branch() == "exp"
assert restored.version == 2
assert restored.to_arrow()["id"].to_pylist() == [0, 1]
def test_lance_table_pickle_preserves_branch_and_version(tmp_path):
db = lancedb.connect(tmp_path)
main = db.create_table("pickle_branch", pa.table({"id": [0]}))
branch = main.branches.create("exp")
branch.add(pa.table({"id": [1]}))
branch_version = branch.version
branch_payload = pickle.dumps(branch)
pinned = db.open_table("pickle_branch", branch="exp", version=branch_version)
pinned_payload = pickle.dumps(pinned)
db.open_table("pickle_branch", branch="exp").add(pa.table({"id": [2]}))
restored_branch = pickle.loads(branch_payload)
assert restored_branch.current_branch() == "exp"
assert restored_branch.to_arrow()["id"].to_pylist() == [0, 1, 2]
restored_pinned = pickle.loads(pinned_payload)
assert restored_pinned.current_branch() == "exp"
assert restored_pinned.version == branch_version
assert restored_pinned.to_arrow()["id"].to_pylist() == [0, 1]
assert main.count_rows() == 1
def test_lance_table_pickle_memory_uses_arrow_snapshot(mem_db: DBConnection):
table = mem_db.create_table("pickle_memory", pa.table({"id": [1, 2]}))
payload = pickle.dumps(table)
table.add(pa.table({"id": [3]}))
restored = pickle.loads(payload)
assert restored.name == "pickle_memory"
assert restored.to_arrow()["id"].to_pylist() == [1, 2]
def test_memory_connection_pickle_requires_a_table_snapshot(mem_db: DBConnection):
with pytest.raises(TypeError, match="in-memory LanceDBConnection"):
pickle.dumps(mem_db)
def test_pickle_rejects_session_backed_connection(tmp_path):
db = lancedb.connect(tmp_path, session=lancedb.Session())
table = db.create_table("pickle_session", pa.table({"id": [1]}))
with pytest.raises(TypeError, match="Session"):
pickle.dumps(db)
with pytest.raises(TypeError, match="Session"):
pickle.dumps(table)
def test_pickle_rejects_custom_namespace_client(tmp_db: DBConnection):
table = tmp_db.create_table("pickle_custom_ns", pa.table({"id": [1]}))
table._namespace_client = threading.Lock()
with pytest.raises(TypeError, match="namespace_client"):
pickle.dumps(table)
def test_lance_table_pickle_preserves_namespace_path(tmp_path):
pytest.importorskip("lance")
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
db.create_namespace(["ns1"])
table = db.create_table("pickle_ns", pa.table({"id": [1]}), namespace_path=["ns1"])
restored = pickle.loads(pickle.dumps(table))
assert restored.namespace == ["ns1"]
assert restored.count_rows() == 1
assert restored._conn._namespace_client_properties == {"root": str(tmp_path)}
def test_versioning(mem_db: DBConnection):
table = mem_db.create_table(
"test",
+41
View File
@@ -135,6 +135,23 @@ def _open_native_table(uri: str, table_name: str):
return lancedb.connect(uri).open_table(table_name)
class _DatasetHoldingConnectionAndTable(torch.utils.data.Dataset):
"""User-style Dataset that keeps both the connection and table."""
def __init__(self, db, table):
self._db = db
self._table = table
def __len__(self):
return self._table.count_rows()
def __getitem__(self, index):
row = self._table.take_offsets([index]).to_arrow().to_pylist()[0]
# Touch the connection too, so workers prove both objects were restored.
row["db_uri"] = self._db.uri
return row
def test_table_dataloader(mem_db):
table = mem_db.create_table("test_table", pa.table({"a": range(1000)}))
dataloader = torch.utils.data.DataLoader(
@@ -229,6 +246,30 @@ def test_permutation_with_memory_base_is_picklable(mem_db):
assert restored.__getitems__([0, 10, 49]) == [{"a": 0}, {"a": 10}, {"a": 49}]
@pytest.mark.parametrize("start_method", ["spawn", "forkserver"])
def test_dataset_with_connection_and_table_dataloader(tmp_path, start_method):
if start_method not in mp.get_all_start_methods():
pytest.skip(f"{start_method} start method is not available")
db = lancedb.connect(tmp_path)
table = db.create_table("test_table", pa.table({"a": range(20)}))
dataset = _DatasetHoldingConnectionAndTable(db, table)
dataloader = torch.utils.data.DataLoader(
dataset,
batch_size=4,
num_workers=2,
multiprocessing_context=start_method,
)
seen = []
expected_uri = str(tmp_path)
for batch in dataloader:
seen.extend(batch["a"].tolist())
assert all(uri == expected_uri for uri in batch["db_uri"])
assert sorted(seen) == list(range(20))
def test_permutation_dataloader_multiprocessing(tmp_db):
"""Using a Permutation with a PyTorch DataLoader that has num_workers > 0
must work end-to-end. Each worker process gets a pickled copy of the
+43 -2
View File
@@ -2,6 +2,7 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use std::sync::Arc;
use std::time::Duration;
use crate::error::PythonErrorExt;
use crate::runtime::future_into_py;
@@ -9,9 +10,13 @@ use arrow::{
array::RecordBatch,
datatypes::SchemaRef,
pyarrow::{IntoPyArrow, ToPyArrow},
record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader},
};
use futures::{TryStreamExt, stream::StreamExt};
use lancedb::{
arrow::SendableRecordBatchStream,
query::{ExecutableQuery, QueryExecutionOptions},
};
use futures::stream::StreamExt;
use lancedb::arrow::SendableRecordBatchStream;
use pyo3::{
Bound, Py, PyAny, PyRef, PyResult, Python,
exceptions::{PyRuntimeError, PyStopAsyncIteration},
@@ -74,6 +79,42 @@ impl RecordBatchStream {
}
}
/// Execute `query` and collect every batch in Rust before returning to Python.
///
/// `to_arrow()` needs the complete table, so the default 1024-row output
/// slicing only adds work. Returning an Arrow C Stream reader also avoids a
/// Python future per batch while python materializes the table.
///
/// The stream is collected inside the returned future, so timeout and
/// cancellation keep the same observable behavior as reading the stream from
/// Python: errors surface from the awaited call and dropping the future drops
/// the underlying stream.
pub fn execute_to_reader<Q>(
py: Python<'_>,
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Bound<'_, PyAny>>
where
Q: ExecutableQuery + Send + 'static,
{
future_into_py(py, async move {
let mut options = QueryExecutionOptions::default();
// `None` means the caller wants one eager result, not the core's
// default batch size. An explicit value is still honored.
options.max_batch_length = max_batch_length.unwrap_or(0);
options.timeout = timeout;
let stream = query.execute_with_options(options).await.infer_error()?;
let schema = stream.schema();
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
let reader: Box<dyn ArrowRecordBatchReader + Send> = Box::new(RecordBatchIterator::new(
batches.into_iter().map(Ok),
schema,
));
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
})
}
#[cfg(test)]
mod tests {
use super::*;
+3 -2
View File
@@ -123,14 +123,15 @@ impl PyAsyncPermutationBuilder {
})
}
#[pyo3(signature = (columns, split_weights, *, discard_weight=0, split_names=None))]
#[pyo3(signature = (columns, split_weights, *, discard_weight=None, split_names=None))]
pub fn split_hash(
slf: PyRefMut<'_, Self>,
columns: Vec<String>,
split_weights: Vec<u64>,
discard_weight: u64,
discard_weight: Option<u64>,
split_names: Option<Vec<String>>,
) -> PyResult<Self> {
let discard_weight = discard_weight.unwrap_or(0);
slf.modify(|builder| {
builder.with_split_strategy(
SplitStrategy::Hash {
+64
View File
@@ -696,6 +696,20 @@ impl Query {
})
}
/// Execute this query eagerly and return an Arrow C Stream reader.
///
/// The returned reader exposes batches already collected in Rust, so
/// `pyarrow` can build a table without a Python future per batch. `None`
/// leaves out the core's default 1024-row output slicing.
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Bound<'_, PyAny>> {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
@@ -784,6 +798,20 @@ impl TakeQuery {
})
}
/// Execute this query eagerly and return an Arrow C Stream reader.
///
/// The returned reader exposes batches already collected in Rust, so
/// `pyarrow` can build a table without a Python future per batch. `None`
/// leaves out the core's default 1024-row output slicing.
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Bound<'_, PyAny>> {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
@@ -909,6 +937,28 @@ impl FTSQuery {
})
}
/// Execute this query eagerly and return an Arrow C Stream reader.
///
/// The returned reader exposes batches already collected in Rust, so
/// `pyarrow` can build a table without a Python future per batch. `None`
/// leaves out the core's default 1024-row output slicing.
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Bound<'_, PyAny>> {
crate::arrow::execute_to_reader(
self_.py(),
self_
.inner
.clone()
.full_text_search(self_.fts_query.clone()),
max_batch_length,
timeout,
)
}
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let mut inner = self_
.inner
@@ -1148,6 +1198,20 @@ impl VectorQuery {
})
}
/// Execute this query eagerly and return an Arrow C Stream reader.
///
/// The returned reader exposes batches already collected in Rust, so
/// `pyarrow` can build a table without a Python future per batch. `None`
/// leaves out the core's default 1024-row output slicing.
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Bound<'_, PyAny>> {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
+475 -62
View File
@@ -21,37 +21,47 @@
//! rests on three separate mechanisms, each solving one problem the others
//! cannot:
//!
//! **`OUTSTANDING`, not `Arc::strong_count`, decides when the runtime is
//! idle.** Early versions tried to infer "is anything still using this
//! runtime" from how many `Arc<Runtime>` clones existed. That signal is
//! wrong in both directions: a clone taken only for the instant a task is
//! *submitted* says nothing about whether that task has actually finished
//! running (`Runtime::shutdown_timeout` gives spawned, non-blocking tasks
//! no grace period at all -- a task "keeps running until it yields, then is
//! dropped" -- so a reclaim landing right after submission would silently
//! abandon it before it ever got to run); and a clone held for a task's
//! *whole* lifetime can end up making that task the final owner of the
//! `Runtime`, so completing it drops the `Runtime` from inside one of its
//! own worker threads, which tokio itself forbids ("cannot drop a runtime
//! in a context where blocking is not allowed") and panics. `OUTSTANDING`
//! is an explicit courtesy counter instead: every top-level `spawn`,
//! `spawn_blocking`, or `block_on` call increments it before it starts and
//! decrements it (via [`OutstandingGuard`]) when it is truly done, entirely
//! decoupled from how many `Arc` clones exist at any instant. `shutdown`
//! waits for it to reach zero before ever touching the runtime, which also
//! closes a narrower race: because the counter is incremented *before*
//! `get_runtime()` is even called, an install already in progress when
//! `shutdown` runs is never invisible to it the way an empty slot would be.
//! If the counter never reaches zero within the bound, `shutdown` stops
//! waiting and forces the retirement attempt anyway -- silently returning
//! with the runtime and its workers still fully alive would just recreate
//! the exact race this function exists to close, for any call slower than
//! the grace period.
//! **A per-generation counter, not `Arc::strong_count`, decides when the
//! runtime is idle.** Early versions tried to infer "is anything still
//! using this runtime" from how many `Arc<Runtime>` clones existed. That
//! signal is wrong in both directions: a clone taken only for the instant a
//! task is *submitted* says nothing about whether that task has actually
//! finished running (`Runtime::shutdown_timeout` gives spawned, non-blocking
//! tasks no grace period at all -- a task "keeps running until it yields,
//! then is dropped" -- so a reclaim landing right after submission would
//! silently abandon it before it ever got to run); and a clone held for a
//! task's *whole* lifetime can end up making that task the final owner of
//! the `Runtime`, so completing it drops the `Runtime` from inside one of
//! its own worker threads, which tokio itself forbids ("cannot drop a
//! runtime in a context where blocking is not allowed") and panics.
//! [`GenerationCalls`] is an explicit courtesy counter instead: every
//! top-level `spawn`, `spawn_blocking`, or `block_on` call increments it
//! before it starts and decrements it (via [`OutstandingGuard`]) when it is
//! truly done, entirely decoupled from how many `Arc` clones exist at any
//! instant. `shutdown` waits for the current generation's counter to reach
//! zero before ever touching the runtime, which also closes a narrower
//! race: because the counter is incremented *before* `get_runtime()` is
//! even called, an install already in progress when `shutdown` runs is
//! never invisible to it the way an empty slot would be. If the counter
//! never reaches zero within the bound, `shutdown` stops waiting and forces
//! the retirement attempt anyway -- silently returning with the runtime and
//! its workers still fully alive would just recreate the exact race this
//! function exists to close, for any call slower than the grace period.
//!
//! **Tasks never hold an `Arc<Runtime>`.** Because `OUTSTANDING` (not
//! reference counting) is what `shutdown` waits on, a top-level task only
//! needs to carry an `OutstandingGuard` -- a token whose `Drop` is a plain
//! atomic decrement -- not a clone of the runtime itself. That is what
//! **The counter is scoped to a fork generation, not the process.** A
//! single process-wide count cannot survive `fork()`: the child inherits the
//! parent's in-flight value, but the tasks that would decrement it do not
//! run there, and a guard copied onto the forking thread would later
//! decrement the child's count even though it belongs to the parent. Every
//! [`OutstandingGuard`] therefore holds an `Arc<GenerationCalls>` for the
//! generation it was created in. A stale guard can only decrement its own
//! counter, while the child's first call lazily creates a fresh counter, and
//! `shutdown` only waits on the counter matching the live generation.
//!
//! **Tasks never hold an `Arc<Runtime>`.** Because the generation counter
//! (not reference counting) is what `shutdown` waits on, a top-level task
//! only needs to carry an `OutstandingGuard` -- a token whose `Drop` is a
//! plain atomic decrement -- not a clone of the runtime itself. That is what
//! makes it impossible for a task's completion to become the final,
//! worker-thread-side drop of the `Runtime`: nothing a task holds ever
//! *is* the `Runtime`.
@@ -74,11 +84,18 @@
//! installed runtime was built in against the live counter on every call,
//! from ordinary (non-signal) context, and treats a mismatch as "stale,
//! rebuild" -- exactly the check `atfork_child` used to perform directly.
//! [`shutdown`] makes the same comparison, because a child that exits
//! without ever installing its own runtime still finds the parent's stale
//! [`Tagged`] in the slot. It removes that slot and deliberately leaks the
//! instance instead of calling `shutdown_timeout` on it: its worker threads
//! do not exist in this process, so waiting for its counter or trying to
//! join them would hang, and a leaked reference prevents any inherited
//! `Arc` clone from becoming the final owner that drops it.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use arc_swap::ArcSwapOption;
@@ -110,12 +127,21 @@ static RUNTIME: ArcSwapOption<Tagged> = ArcSwapOption::const_empty();
/// access -- just one atomic add, which is all a `pthread_atfork` child
/// handler is ever safe to do.
static GENERATION: AtomicU64 = AtomicU64::new(0);
/// Count of top-level `spawn`/`spawn_blocking`/`block_on` calls that have
/// started but not yet finished. See the module docs for why this, and not
/// `Arc::strong_count`, is what `shutdown` waits on.
static OUTSTANDING: AtomicU64 = AtomicU64::new(0);
/// In-flight top-level calls for one fork generation. Guards hold an `Arc`
/// to this object for their whole lifetime, so one inherited across `fork()`
/// can only decrement the counter it was created against, never the child's
/// fresh one.
struct GenerationCalls {
generation: u64,
outstanding: AtomicUsize,
}
static CALLS: ArcSwapOption<GenerationCalls> = ArcSwapOption::const_empty();
static ATFORK_INSTALLED: AtomicBool = AtomicBool::new(false);
#[cfg(test)]
static TEST_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0);
#[cfg(not(test))]
fn create_runtime() -> runtime::Runtime {
runtime::Builder::new_multi_thread()
.enable_all()
@@ -124,9 +150,68 @@ fn create_runtime() -> runtime::Runtime {
.expect("Failed to build tokio runtime")
}
#[cfg(test)]
fn create_runtime() -> runtime::Runtime {
let mut builder = runtime::Builder::new_multi_thread();
builder.enable_all().thread_name("lancedb-tokio-worker");
// Fork tests hold two runtimes open at once. Keeping their worker count
// small avoids turning an unrelated parallel build on the same host into
// an apparent hang when the process thread limit is close to full.
let worker_threads = TEST_WORKER_THREADS.load(Ordering::Relaxed);
if worker_threads != 0 {
builder.worker_threads(worker_threads);
}
builder.build().expect("Failed to build tokio runtime")
}
/// Register the fork-child handler once, before any generation-scoped state
/// is created.
///
/// The first top-level call deliberately installs the hook before it starts
/// counting itself. Otherwise a fork between taking that first counter and
/// `get_runtime()` installing the hook would leave the child sharing the
/// parent's counter with no generation change to separate them.
fn ensure_atfork_installed() {
if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) {
install_atfork();
}
}
/// Get the in-flight counter for the current fork generation, creating it on
/// the first top-level call after a fork.
fn current_calls() -> Arc<GenerationCalls> {
ensure_atfork_installed();
let current_gen = GENERATION.load(Ordering::SeqCst);
loop {
let existing = CALLS.load_full();
if let Some(existing) = &existing
&& existing.generation == current_gen
{
return Arc::clone(existing);
}
let candidate = Arc::new(GenerationCalls {
generation: current_gen,
outstanding: AtomicUsize::new(0),
});
let previous = CALLS.compare_and_swap(&existing, Some(Arc::clone(&candidate)));
let won = match (&*previous, &existing) {
(None, None) => true,
(Some(prev), Some(exist)) => Arc::ptr_eq(prev, exist),
_ => false,
};
if won {
// A stale counter is only an integer: unlike a runtime it has no
// worker threads to join, so letting the slot's old reference go
// here is safe even in a forked child.
return candidate;
}
}
}
/// Get a live, owned handle to the shared runtime, rebuilding it if the
/// installed one predates the most recent `fork()`.
fn get_runtime() -> Arc<Tagged> {
ensure_atfork_installed();
let current_gen = GENERATION.load(Ordering::SeqCst);
loop {
let existing = RUNTIME.load_full();
@@ -135,9 +220,6 @@ fn get_runtime() -> Arc<Tagged> {
{
return Arc::clone(existing);
}
if !ATFORK_INSTALLED.fetch_or(true, Ordering::SeqCst) {
install_atfork();
}
// Built optimistically, outside any lock: on the rare race where two
// threads both find the slot empty (or stale), one candidate wins
// the compare-and-swap below and the other is simply dropped here,
@@ -167,23 +249,26 @@ fn get_runtime() -> Arc<Tagged> {
}
}
/// RAII token tracked by [`OUTSTANDING`]. Held for the duration of a
/// top-level `block_on` call, or moved into a top-level `spawn`/
/// `spawn_blocking` task so it decrements only once that task's *entire*
/// body -- including anything it nested-spawns and awaits -- has run to
/// completion or been dropped without completing.
struct OutstandingGuard;
/// RAII token tracked by the current [`GenerationCalls`] counter. Held for
/// the duration of a top-level `block_on` call, or moved into a top-level
/// `spawn`/`spawn_blocking` task so it decrements only once that task's
/// *entire* body -- including anything it nested-spawns and awaits -- has run
/// to completion or been dropped without completing.
struct OutstandingGuard {
calls: Arc<GenerationCalls>,
}
impl OutstandingGuard {
fn new() -> Self {
OUTSTANDING.fetch_add(1, Ordering::SeqCst);
Self
let calls = current_calls();
calls.outstanding.fetch_add(1, Ordering::SeqCst);
Self { calls }
}
}
impl Drop for OutstandingGuard {
fn drop(&mut self) {
OUTSTANDING.fetch_sub(1, Ordering::SeqCst);
self.calls.outstanding.fetch_sub(1, Ordering::SeqCst);
}
}
@@ -219,13 +304,15 @@ where
/// Gracefully quiesce the shared runtime, meant to run at normal process exit.
///
/// Waits (bounded by `timeout`) for [`OUTSTANDING`] to reach zero -- i.e.
/// for every top-level call already under way to actually finish, not just
/// for `Arc::strong_count` to look low -- before ever touching the runtime.
/// If the bound elapses first, it stops waiting and attempts retirement
/// anyway: leaving the runtime and its worker threads untouched would just
/// recreate the exact race this function exists to close, for any call
/// slower than the grace period.
/// Waits (bounded by `timeout`) for the current generation's
/// [`GenerationCalls`] counter to reach zero -- i.e. for every top-level call
/// already under way in *this* process to actually finish, not just for
/// `Arc::strong_count` to look low -- before ever touching the runtime. Work
/// inherited from a parent process at `fork()` belongs to an older
/// generation and is never waited on. If the bound elapses first, it stops
/// waiting and attempts retirement anyway: leaving the runtime and its worker
/// threads untouched would just recreate the exact race this function exists
/// to close, for any call slower than the grace period.
///
/// Retirement itself removes the runtime from the slot and calls
/// `shutdown_timeout` rather than a bare `drop`: dropping a tokio `Runtime`
@@ -238,14 +325,22 @@ where
/// the slot and finishing its own call, this abandons the runtime instead
/// of forcing the issue -- the same trade `atfork_child` already makes.
///
/// A runtime tagged with a generation older than the live counter was
/// inherited through `fork()` and is never retired here; see the module docs.
///
/// Neither of the two ways this can fail to cleanly retire the runtime --
/// the wait timing out, or `try_unwrap` losing that race -- has any other
/// signal to report through (`shutdown_timeout` itself returns nothing),
/// so both log a warning instead of failing silently.
pub fn shutdown(timeout: Duration) {
let deadline = Instant::now() + timeout;
let generation = GENERATION.load(Ordering::SeqCst);
let calls = CALLS.load_full();
let calls = calls
.as_ref()
.filter(|calls| calls.generation == generation);
loop {
let outstanding = OUTSTANDING.load(Ordering::SeqCst);
let outstanding = calls.map_or(0, |calls| calls.outstanding.load(Ordering::SeqCst));
if outstanding == 0 {
break;
}
@@ -260,6 +355,18 @@ pub fn shutdown(timeout: Duration) {
let Some(current) = RUNTIME.load_full() else {
return;
};
if current.generation != generation {
// The child inherited the parent's installed runtime. Its worker
// threads do not exist here, so waiting on its counter or calling
// `shutdown_timeout` would wait for work that can never finish and
// join threads that can never exit. Remove the slot in ordinary
// context and deliberately leak the instance: inherited `Arc` clones
// may still be dropped in this process, and the leaked reference
// keeps a dropped clone from becoming the final owner.
RUNTIME.compare_and_swap(&Some(Arc::clone(&current)), None);
std::mem::forget(current);
return;
}
RUNTIME.compare_and_swap(&Some(Arc::clone(&current)), None);
match Arc::try_unwrap(current) {
Ok(tagged) => {
@@ -320,7 +427,7 @@ impl Runtime for LanceRuntime {
/// awaits its `JoinHandle`. `Handle::try_current` pins that nested call
/// to whatever runtime is already executing it, so only the first,
/// outermost call of a chain -- one running on a thread outside any
/// runtime -- ever consults [`get_runtime`] or [`OUTSTANDING`].
/// runtime -- ever consults [`get_runtime`] or [`OutstandingGuard`].
fn spawn<F>(fut: F) -> Self::JoinHandle
where
F: Future<Output = ()> + Send + 'static,
@@ -391,14 +498,14 @@ where
mod tests {
use super::*;
// RUNTIME, GENERATION, OUTSTANDING, and ATFORK_INSTALLED are process-wide
// RUNTIME, CALLS, GENERATION, and ATFORK_INSTALLED are process-wide
// statics, and Rust's test harness runs tests in parallel by default,
// so separate test functions below would otherwise race each other
// through this shared state (this reproduced in CI: one test's
// in-flight task got reclaimed by a *different* test's concurrent
// `shutdown()` call, and another observed `OUTSTANDING` left non-zero
// by a still-running sibling). Every test takes this lock first so
// only one of them touches the shared runtime state at a time; a
// `shutdown()` call, and another observed the in-flight counter left
// non-zero by a still-running sibling). Every test takes this lock first
// so only one of them touches the shared runtime state at a time; a
// poisoned lock (a previous test's genuine failure) is still honored
// rather than cascading into every later test as an unrelated panic.
static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
@@ -570,7 +677,7 @@ mod tests {
use std::sync::mpsc;
let _lock = lock_runtime_state_for_test();
// Clean slate: no runtime installed, OUTSTANDING at zero.
// Clean slate: no runtime installed, no in-flight calls.
shutdown(Duration::from_secs(5));
let (installer_ready_tx, installer_ready_rx) = mpsc::channel::<()>();
@@ -596,6 +703,312 @@ mod tests {
// shutdown must have waited for the install to finish and then
// retired it, not returned early and left it stranded.
assert!(RUNTIME.load_full().is_none());
assert_eq!(OUTSTANDING.load(Ordering::SeqCst), 0);
let calls = CALLS
.load_full()
.expect("install race left no generation counter");
assert_eq!(calls.outstanding.load(Ordering::SeqCst), 0);
}
/// Keep fork-test runtimes small; see [`TEST_WORKER_THREADS`].
#[cfg(target_os = "linux")]
struct TestWorkerThreads(usize);
#[cfg(target_os = "linux")]
impl TestWorkerThreads {
fn new(worker_threads: usize) -> Self {
Self(TEST_WORKER_THREADS.swap(worker_threads, Ordering::SeqCst))
}
}
#[cfg(target_os = "linux")]
impl Drop for TestWorkerThreads {
fn drop(&mut self) {
TEST_WORKER_THREADS.store(self.0, Ordering::SeqCst);
}
}
/// Run `f` in a forked child and return the `i32` it reports, or `None`
/// if the child did not report within the bound. The child leaves with
/// `_exit` so it never runs destructors inherited from the test process.
#[cfg(target_os = "linux")]
fn run_in_forked_child<F>(f: F) -> Option<i32>
where
F: FnOnce() -> i32,
{
let mut pipe = [0; 2];
assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0, "pipe failed");
let (read_fd, write_fd) = (pipe[0], pipe[1]);
let pid = unsafe { libc::fork() };
assert!(pid >= 0, "fork failed");
if pid == 0 {
unsafe { libc::close(read_fd) };
let result = f();
let bytes = result.to_ne_bytes();
let written = unsafe { libc::write(write_fd, bytes.as_ptr().cast(), bytes.len()) };
unsafe { libc::close(write_fd) };
unsafe {
libc::_exit(if written == bytes.len() as isize {
0
} else {
1
})
};
}
unsafe { libc::close(write_fd) };
let mut poll_fd = libc::pollfd {
fd: read_fd,
events: libc::POLLIN,
revents: 0,
};
let ready = loop {
let ready = unsafe { libc::poll(&mut poll_fd, 1, 10_000) };
if ready >= 0 {
break ready;
}
let error = std::io::Error::last_os_error();
assert_eq!(
error.kind(),
std::io::ErrorKind::Interrupted,
"poll failed: {error}"
);
};
if ready == 0 {
unsafe { libc::kill(pid, libc::SIGKILL) };
}
let mut result = None;
if ready == 1 {
let mut bytes = [0u8; std::mem::size_of::<i32>()];
let read = loop {
let read = unsafe { libc::read(read_fd, bytes.as_mut_ptr().cast(), bytes.len()) };
if read >= 0 {
break read;
}
let error = std::io::Error::last_os_error();
assert_eq!(
error.kind(),
std::io::ErrorKind::Interrupted,
"read failed: {error}"
);
};
if read == bytes.len() as isize {
result = Some(i32::from_ne_bytes(bytes));
}
}
unsafe { libc::close(read_fd) };
let mut status = 0;
loop {
let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
if waited == pid {
break;
}
let error = std::io::Error::last_os_error();
assert_eq!(
error.kind(),
std::io::ErrorKind::Interrupted,
"waitpid failed: {error}"
);
}
if ready == 0 {
return None;
}
assert_eq!(status, 0, "forked child did not exit successfully");
result
}
// The child inherits the parent's installed runtime and its outstanding
// count, but not the worker thread that would ever release that count.
// Its exit-time shutdown must therefore ignore both: waiting for parent
// work would burn the whole grace period, and retiring the inherited
// runtime would try to join worker threads that do not exist here.
#[cfg(target_os = "linux")]
#[test]
fn test_forked_child_shutdown_does_not_wait_for_parent_work() {
use std::sync::mpsc;
use tokio::sync::oneshot;
let _lock = lock_runtime_state_for_test();
let _worker_threads = TestWorkerThreads::new(2);
shutdown(Duration::from_secs(5));
let (started_tx, started_rx) = mpsc::channel();
let (release_tx, release_rx) = oneshot::channel::<()>();
let (done_tx, done_rx) = mpsc::channel::<()>();
drop(LanceRuntime::spawn(async move {
started_tx.send(()).unwrap();
let _ = release_rx.await;
let _ = done_tx.send(());
}));
started_rx
.recv_timeout(Duration::from_secs(5))
.expect("parent task did not start");
let child_result = run_in_forked_child(|| {
// Much longer than the watchdog: if this waits for inherited
// parent work at all, the child fails to report in time instead
// of the test comparing two elapsed durations.
shutdown(Duration::from_secs(30));
i32::from(RUNTIME.load_full().is_some())
});
assert_eq!(
child_result,
Some(0),
"child shutdown waited for parent work or retired the inherited runtime"
);
release_tx.send(()).unwrap();
done_rx
.recv_timeout(Duration::from_secs(5))
.expect("parent task was disturbed by the forked child");
shutdown(Duration::from_secs(5));
}
// A child that builds its own runtime must drain that runtime's own
// work, and only that work: the parent's held task is still outstanding
// in the inherited copy of the counter but can never finish here.
#[cfg(target_os = "linux")]
#[test]
fn test_forked_child_drains_its_own_runtime_without_waiting_for_parent_work() {
use std::sync::mpsc;
use tokio::sync::oneshot;
let _lock = lock_runtime_state_for_test();
let _worker_threads = TestWorkerThreads::new(2);
shutdown(Duration::from_secs(5));
let (started_tx, started_rx) = mpsc::channel();
let (release_tx, release_rx) = oneshot::channel::<()>();
let (done_tx, done_rx) = mpsc::channel::<()>();
drop(LanceRuntime::spawn(async move {
started_tx.send(()).unwrap();
let _ = release_rx.await;
let _ = done_tx.send(());
}));
started_rx
.recv_timeout(Duration::from_secs(5))
.expect("parent task did not start");
let child_result = run_in_forked_child(|| {
let child_done = Arc::new(AtomicBool::new(false));
let child_done_flag = Arc::clone(&child_done);
let (task_started_tx, task_started_rx) = mpsc::channel();
let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
let (child_tx, child_rx) = mpsc::channel();
drop(LanceRuntime::spawn(async move {
task_started_tx.send(()).unwrap();
let _ = release_rx.await;
child_done_flag.store(true, Ordering::SeqCst);
let _ = child_tx.send(());
}));
task_started_rx
.recv_timeout(Duration::from_secs(5))
.expect("child task did not start");
// Keep the child's own task outstanding while shutdown starts,
// then release it once the shutdown thread is about to enter.
let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel();
let shutdown_thread = std::thread::spawn(move || {
shutdown_ready_tx.send(()).unwrap();
shutdown(Duration::from_secs(30));
});
shutdown_ready_rx.recv().unwrap();
release_tx.send(()).unwrap();
shutdown_thread.join().unwrap();
let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok()
&& child_done.load(Ordering::SeqCst);
let retired = RUNTIME.load_full().is_none();
let rebuilt = block_on(async { 40 + 2 }) == 42;
shutdown(Duration::from_secs(30));
i32::from(!(drained && retired && rebuilt))
});
assert_eq!(
child_result,
Some(0),
"child did not drain its own runtime or waited for parent work"
);
release_tx.send(()).unwrap();
done_rx
.recv_timeout(Duration::from_secs(5))
.expect("parent task was disturbed by the forked child");
shutdown(Duration::from_secs(5));
}
// A guard created before `fork()` belongs to the parent generation. If
// the child drops that inherited guard, it must decrement the counter it
// was created against, not the child's fresh counter (a naive reset in
// the child would underflow here and make shutdown wait forever). The
// second parent guard stays held across the fork without being dropped
// in the child, so this also proves the child does not wait for work
// that can only finish in the parent.
#[cfg(target_os = "linux")]
#[test]
fn test_inherited_guard_does_not_corrupt_child_generation_counter() {
use std::sync::mpsc;
use tokio::sync::oneshot;
let _lock = lock_runtime_state_for_test();
let _worker_threads = TestWorkerThreads::new(2);
shutdown(Duration::from_secs(5));
// This test forks before any runtime exists, so make the hook
// initialization explicit through the same path the first top-level
// call uses; otherwise this test only works after a preceding test
// has installed the process-wide hook.
ensure_atfork_installed();
// Stands in for a top-level call that was in progress when the
// parent forked and is dropped by the child after it starts work.
let inherited_guard = OutstandingGuard::new();
// Stays outstanding in the parent for the whole fork, as parent work
// that no child task can ever complete.
let parent_guard = OutstandingGuard::new();
let child_result = run_in_forked_child(move || {
let child_done = Arc::new(AtomicBool::new(false));
let child_done_flag = Arc::clone(&child_done);
let (task_started_tx, task_started_rx) = mpsc::channel();
let (release_tx, release_rx) = oneshot::channel::<()>();
let (child_tx, child_rx) = mpsc::channel();
drop(LanceRuntime::spawn(async move {
task_started_tx.send(()).unwrap();
let _ = release_rx.await;
child_done_flag.store(true, Ordering::SeqCst);
let _ = child_tx.send(());
}));
task_started_rx
.recv_timeout(Duration::from_secs(5))
.expect("child task did not start");
// Drop the inherited guard while the child has its own task
// outstanding, so a shared or reset counter would visibly
// perturb the child's accounting.
drop(inherited_guard);
let (shutdown_ready_tx, shutdown_ready_rx) = mpsc::channel();
let shutdown_thread = std::thread::spawn(move || {
shutdown_ready_tx.send(()).unwrap();
shutdown(Duration::from_secs(30));
});
shutdown_ready_rx.recv().unwrap();
release_tx.send(()).unwrap();
shutdown_thread.join().unwrap();
let drained = child_rx.recv_timeout(Duration::from_secs(5)).is_ok()
&& child_done.load(Ordering::SeqCst);
let retired = RUNTIME.load_full().is_none();
i32::from(!(drained && retired))
});
assert_eq!(
child_result,
Some(0),
"inherited guard corrupted the child generation counter"
);
drop(parent_guard);
shutdown(Duration::from_secs(5));
}
}