mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 20:44:00 +00:00
Merge main and align cosine patch with Lance 15.1.0-beta.2
This commit is contained in:
+2
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.30"
|
||||
version = "0.42.0-beta.32"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
@@ -8,7 +8,7 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
keywords.workspace = true
|
||||
categories.workspace = true
|
||||
rust-version = "1.95.0"
|
||||
rust-version = "1.98.0"
|
||||
|
||||
[lib]
|
||||
name = "_lancedb"
|
||||
|
||||
@@ -64,7 +64,7 @@ tests = [
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b35",
|
||||
"pylance==15.1.0b2",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
|
||||
@@ -775,8 +775,7 @@ class Table:
|
||||
) -> AddColumnsResult: ...
|
||||
async def add_function_columns(
|
||||
self,
|
||||
application_json: str,
|
||||
output_name: Optional[str],
|
||||
bindings: list[tuple[str, Optional[str]]],
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[int] = None,
|
||||
total_cpu_millis: Optional[int] = None,
|
||||
|
||||
+990
-125
File diff suppressed because it is too large
Load Diff
@@ -2887,6 +2887,11 @@ class Table(ABC):
|
||||
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
|
||||
resulting ``_rowid`` values.
|
||||
|
||||
On Enterprise clusters that enable direct Blob reads, large values and
|
||||
ranges may be fetched from short-lived object-store URLs. The client then
|
||||
needs network access to the object-store endpoint, including private
|
||||
endpoint routing, DNS, TLS trust and egress rules, in addition to the
|
||||
LanceDB endpoint. Small reads stay on the LanceDB proxy.
|
||||
Blobs inside lists cannot be fetched by row id yet.
|
||||
|
||||
LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob
|
||||
@@ -2921,6 +2926,11 @@ class Table(ABC):
|
||||
One missing or deleted row ID rejects the entire batch; no partial
|
||||
results are returned.
|
||||
|
||||
On Enterprise clusters that enable direct Blob reads, large values and
|
||||
ranges may be fetched from short-lived object-store URLs. The client then
|
||||
needs network access to the object-store endpoint, including private
|
||||
endpoint routing, DNS, TLS trust and egress rules, in addition to the
|
||||
LanceDB endpoint. Small reads stay on the LanceDB proxy.
|
||||
Row IDs can be obtained from a query with ``with_row_id(True)``.
|
||||
LanceDB Enterprise uses the batched endpoint when the server advertises
|
||||
support, partitioning at 1024 ranges and 64 MiB, including individual
|
||||
@@ -2949,6 +2959,11 @@ class Table(ABC):
|
||||
``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB).
|
||||
Set it to 0 for sparse reads. Explicit range reads bypass this buffer.
|
||||
|
||||
On Enterprise clusters that enable direct Blob reads, large values and
|
||||
ranges may be fetched from short-lived object-store URLs. The client then
|
||||
needs network access to the object-store endpoint, including private
|
||||
endpoint routing, DNS, TLS trust and egress rules, in addition to the
|
||||
LanceDB endpoint. Small reads stay on the LanceDB proxy.
|
||||
``_rowid`` values stay valid after compaction when the table has stable
|
||||
row ids.
|
||||
One missing or deleted row ID rejects the entire batch; no partial
|
||||
@@ -3480,10 +3495,11 @@ class Table(ABC):
|
||||
new columns with the specified data types. The new columns will
|
||||
be initialized with null values.
|
||||
|
||||
A mapping with one ``FunctionApplication`` value keeps its scalar
|
||||
or named-struct result in the named table column. A bare
|
||||
named-struct application expands its ordered result fields as one
|
||||
atomic binding; aliases come from ``rename(columns=...)``.
|
||||
A mapping of column names to ``FunctionApplication`` values declares
|
||||
all bindings in one schema commit. Each column holds its scalar
|
||||
or entire named-struct result. A bare named-struct application expands
|
||||
its ordered result fields as one atomic binding. Set field aliases
|
||||
with ``rename(columns=...)``.
|
||||
Function columns are supported only in LanceDB
|
||||
Enterprise.
|
||||
|
||||
@@ -4432,17 +4448,22 @@ class LanceTable(Table):
|
||||
)
|
||||
return connection.serialize()
|
||||
|
||||
def _namespace_client_for_pickle(self) -> Optional[Any]:
|
||||
"""Keep a table-level namespace client only when pickle can carry it."""
|
||||
def _table_namespace_client(self) -> Optional[Any]:
|
||||
"""The namespace client set on this table rather than its connection."""
|
||||
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.
|
||||
# The 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
|
||||
return namespace_client
|
||||
|
||||
def _namespace_client_for_pickle(self) -> Optional[Any]:
|
||||
"""Keep a table-level namespace client only when pickle can carry it."""
|
||||
namespace_client = self._table_namespace_client()
|
||||
if namespace_client is None:
|
||||
return None
|
||||
|
||||
import pickle
|
||||
|
||||
@@ -4511,13 +4532,20 @@ class LanceTable(Table):
|
||||
# Keep the established behavior of exporting the visible table.
|
||||
return {"kind": "memory", "name": self.name, "data": self.to_arrow()}
|
||||
|
||||
return {
|
||||
"kind": "lance",
|
||||
"connection_state": self._pickle_connection_state(),
|
||||
"namespace_client": self._namespace_client_for_pickle(),
|
||||
**self._reopen_state(),
|
||||
}
|
||||
|
||||
def _reopen_state(self) -> dict[str, Any]:
|
||||
"""Arguments for ``_open_from_pickle_state``, minus the connection."""
|
||||
# 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
|
||||
@@ -4526,7 +4554,6 @@ class LanceTable(Table):
|
||||
"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,
|
||||
@@ -4534,6 +4561,23 @@ class LanceTable(Table):
|
||||
"checkout_version": self._checkout_version,
|
||||
}
|
||||
|
||||
def _private_copy(self) -> "LanceTable":
|
||||
"""A new handle on the same table, branch and checkout, over this
|
||||
handle's own connection.
|
||||
|
||||
``checkout()`` on the copy leaves this handle untouched. Unlike a
|
||||
pickle round trip, the connection need not be serializable (for
|
||||
example, one created with a ``Session``), and an in-memory table keeps
|
||||
its version history.
|
||||
"""
|
||||
return type(self)._open_from_pickle_state(
|
||||
self._conn,
|
||||
{
|
||||
**self._reopen_state(),
|
||||
"namespace_client": self._table_namespace_client(),
|
||||
},
|
||||
)
|
||||
|
||||
def __setstate__(self, state: dict[str, Any]) -> None:
|
||||
"""Rebuild a table from ``__getstate__`` in the current process."""
|
||||
if state.get("kind") == "memory":
|
||||
@@ -9110,10 +9154,11 @@ class AsyncTable:
|
||||
Alternatively, you can pass a pyarrow field or schema to add
|
||||
new columns with NULLs.
|
||||
|
||||
A mapping with one ``FunctionApplication`` value keeps its scalar
|
||||
or named-struct result in the named table column. A bare
|
||||
named-struct application expands its ordered result fields as one
|
||||
atomic binding; aliases come from ``rename(columns=...)``.
|
||||
A mapping of column names to ``FunctionApplication`` values declares
|
||||
all bindings in one schema commit. Each column holds its scalar
|
||||
or entire named-struct result. A bare named-struct application expands
|
||||
its ordered result fields as one atomic binding. Set field aliases
|
||||
with ``rename(columns=...)``.
|
||||
Function columns are supported only in LanceDB
|
||||
Enterprise.
|
||||
|
||||
@@ -9207,31 +9252,30 @@ class AsyncTable:
|
||||
or gpu_class is not None
|
||||
or gpu_count is not None
|
||||
)
|
||||
function_application = None
|
||||
function_output_name = None
|
||||
bindings: list[tuple[FunctionApplication, str | None]] = []
|
||||
if isinstance(transforms, FunctionApplication):
|
||||
function_application = transforms
|
||||
bindings.append((transforms, None))
|
||||
elif isinstance(transforms, Mapping) and any(
|
||||
isinstance(value, FunctionApplication) for value in transforms.values()
|
||||
):
|
||||
if len(transforms) != 1 or not all(
|
||||
isinstance(value, FunctionApplication) for value in transforms.values()
|
||||
):
|
||||
raise ValueError(
|
||||
"one add_columns call declares exactly one Function binding"
|
||||
)
|
||||
function_output_name, function_application = next(iter(transforms.items()))
|
||||
for name, application in transforms.items():
|
||||
if not isinstance(application, FunctionApplication):
|
||||
raise ValueError(
|
||||
"add_columns cannot mix Function applications and SQL "
|
||||
"expressions"
|
||||
)
|
||||
bindings.append((application, name))
|
||||
|
||||
if function_application is not None:
|
||||
if bindings:
|
||||
if computed:
|
||||
raise ValueError(
|
||||
"add_columns cannot mix a Function application with SQL "
|
||||
"computed columns"
|
||||
)
|
||||
function_application._ensure_declarable()
|
||||
for application, _ in bindings:
|
||||
application._ensure_declarable()
|
||||
return await self._inner.add_function_columns(
|
||||
function_application.to_canonical_json(),
|
||||
function_output_name,
|
||||
[(app.to_canonical_json(), name) for app, name in bindings],
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
|
||||
@@ -31,12 +31,15 @@ Parameters used throughout:
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import functools
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
import threading
|
||||
from unittest.mock import patch
|
||||
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from utils import (
|
||||
@@ -1179,6 +1182,74 @@ def test_streaming_dataloader_commits_only_consumed_worker_batches(tmp_path):
|
||||
assert remaining == uninterrupted == [[3, 4], [30, 40]]
|
||||
|
||||
|
||||
def test_block_size_dataloader_workers_reconnect(tmp_path):
|
||||
"""Block-mode datasets pickle with no permutation table and reopen per worker."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("block_workers", pa.table({"id": list(range(8))}))
|
||||
dataset = StreamingDataset(
|
||||
table,
|
||||
num_splits=2,
|
||||
shuffle=False,
|
||||
block_size=2,
|
||||
)
|
||||
loader = StreamingDataLoader(
|
||||
dataset,
|
||||
batch_size=2,
|
||||
num_workers=2,
|
||||
multiprocessing_context="spawn",
|
||||
)
|
||||
iterator = iter(loader)
|
||||
try:
|
||||
batches = [batch["id"].tolist() for batch in iterator]
|
||||
finally:
|
||||
iterator._shutdown_workers()
|
||||
|
||||
assert sorted(row for batch in batches for row in batch) == list(range(8))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filter", [None, "id % 2 = 0"])
|
||||
@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False])
|
||||
def test_block_size_pickle_does_not_grow_with_block_count(
|
||||
tmp_path, reshuffle_blocks_per_epoch, filter
|
||||
):
|
||||
"""Spawned workers start serially once the pickle outgrows a pipe buffer."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("block_pickle", pa.table({"id": list(range(1 << 16))}))
|
||||
|
||||
def make(block_size):
|
||||
return StreamingDataset(
|
||||
table,
|
||||
num_splits=2,
|
||||
shuffle_seed=7,
|
||||
epoch=3,
|
||||
block_size=block_size,
|
||||
reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch,
|
||||
filter=filter,
|
||||
)
|
||||
|
||||
def pickled_state(dataset):
|
||||
# The fixed-size shared-memory counters only pickle while spawning a
|
||||
# child, and their size does not depend on the block count.
|
||||
state = dataset.__getstate__()
|
||||
for key in ("_worker_stats", "_untracked_worker_iteration", "_filled_count"):
|
||||
del state[key]
|
||||
return pickle.dumps(state)
|
||||
|
||||
few_blocks, many_blocks = make(1 << 12), make(4)
|
||||
few_size = len(pickled_state(few_blocks))
|
||||
many_size = len(pickled_state(many_blocks))
|
||||
assert many_size - few_size < 1024, (few_size, many_size)
|
||||
# A filter's per-live-row offsets must not ride along either.
|
||||
assert many_size < 64 * 1024, many_size
|
||||
|
||||
restored = StreamingDataset.__new__(StreamingDataset)
|
||||
restored.__setstate__(pickle.loads(pickled_state(many_blocks)))
|
||||
assert restored._block_perm == many_blocks._block_perm
|
||||
assert restored._block_perm != sorted(restored._block_perm)
|
||||
if filter is not None:
|
||||
np.testing.assert_array_equal(restored._live_offsets, many_blocks._live_offsets)
|
||||
|
||||
|
||||
def test_distributed_checkpoint_uses_rank_local_worker_boundary(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("rank_boundary", pa.table({"id": list(range(8))}))
|
||||
@@ -3093,6 +3164,36 @@ def _packed_dataset(table, pack_sequences, *, blocks_per_epoch, pad_id=0, **kwar
|
||||
)
|
||||
|
||||
|
||||
def test_pack_sequences_checkpoint_with_block_size(tmp_path):
|
||||
table = _create_token_table(
|
||||
tmp_path,
|
||||
[[1], [2], [10, 11, 12, 13, 14, 15, 16, 17], [20]],
|
||||
)
|
||||
kwargs = dict(
|
||||
pack_sequences=5,
|
||||
blocks_per_epoch=4,
|
||||
num_splits=2,
|
||||
block_size=2,
|
||||
)
|
||||
reference = [
|
||||
block["input_ids"].tolist() for block in _packed_dataset(table, **kwargs)
|
||||
]
|
||||
|
||||
dataset = _packed_dataset(table, **kwargs)
|
||||
iterator = iter(dataset)
|
||||
first_cycle = [next(iterator), next(iterator)]
|
||||
checkpoint = dataset.state_dict()
|
||||
iterator.close()
|
||||
|
||||
resumed = _packed_dataset(table, **kwargs)
|
||||
resumed.load_state_dict(checkpoint)
|
||||
remaining = [block["input_ids"].tolist() for block in resumed]
|
||||
|
||||
assert [block["input_ids"].tolist() for block in first_cycle] == reference[:2]
|
||||
assert checkpoint["blocks_emitted_per_split"] == [1, 1]
|
||||
assert remaining == reference[2:]
|
||||
|
||||
|
||||
def test_pack_sequences_emits_blocks_and_pads_final_tail(tmp_path):
|
||||
table = _create_token_table(tmp_path, [[1, 2], [3, 4], [5]])
|
||||
dataset = _packed_dataset(table, 6, blocks_per_epoch=2)
|
||||
@@ -3572,6 +3673,732 @@ def test_streaming_dataset_over_remote_table():
|
||||
assert_server_safe_row_id_requests(server)
|
||||
|
||||
|
||||
class _ReorderingOffsetScanServer(MockPermutationServer):
|
||||
"""Answers offset/limit pages as if the table's two fragments complete in a
|
||||
different order on each request, which remote scans are allowed to do."""
|
||||
|
||||
def _query(self, request, body):
|
||||
if "offset" in body and not body.get("filter"):
|
||||
rows = list(range(self.num_rows))
|
||||
half = self.num_rows // 2
|
||||
if body["offset"] >= half:
|
||||
rows = rows[half:] + rows[:half]
|
||||
start = body["offset"]
|
||||
return self._arrow(
|
||||
request, pa.table({"id": rows[start : start + body["k"]]})
|
||||
)
|
||||
return super()._query(request, body)
|
||||
|
||||
|
||||
def test_two_phase_over_remote_table():
|
||||
"""Unfiltered 2-phase reads of a remote table name each block's rows by
|
||||
_rowoffset: offset/limit pages have no cross-request order guarantee."""
|
||||
server = _ReorderingOffsetScanServer(num_rows=16)
|
||||
|
||||
with mock_remote_table(server) as table:
|
||||
ds = StreamingDataset(table, num_splits=2, block_size=4, shuffle=False)
|
||||
ids = [row["id"] for row in ds]
|
||||
|
||||
assert sorted(ids) == list(range(server.num_rows)), (
|
||||
"Every row of the remote table must be yielded exactly once"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_over_remote_table_filtered_and_shuffled():
|
||||
"""2-phase's filtered live-offset precompute and take_offsets-based
|
||||
block reads both work against a remote table, including restoring
|
||||
take_offsets' unspecified order via the _rowoffset it also selects."""
|
||||
server = MockPermutationServer(num_rows=20)
|
||||
live_ids = list(range(16)) # 16 live rows -> 4 blocks, divides num_splits=2
|
||||
|
||||
with mock_remote_table(server) as table:
|
||||
ds = StreamingDataset(
|
||||
table,
|
||||
num_splits=2,
|
||||
block_size=4,
|
||||
shuffle=True,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
filter="id IN (" + ",".join(str(i) for i in live_ids) + ")",
|
||||
columns=["id"],
|
||||
)
|
||||
ids = [row["id"] for row in ds]
|
||||
|
||||
assert sorted(ids) == live_ids, "only live rows, each exactly once"
|
||||
|
||||
|
||||
def test_two_phase_over_remote_table_does_not_pin_callers_handle():
|
||||
"""_open_pinned_table() must not mutate the caller's own RemoteTable.
|
||||
|
||||
Without a connection_factory, the reopen helpers used for local/memory
|
||||
tables return the *same* RemoteTable object for the remote case (correct
|
||||
for their original cross-process pickling purpose, wrong for same-process
|
||||
reuse here). Checking that object out to the block-mode pin would
|
||||
therefore pin -- and, since checkout_version != None marks a handle
|
||||
version-pinned -- effectively make read-only the caller's own live table,
|
||||
not an unrelated copy.
|
||||
"""
|
||||
server = MockPermutationServer(num_rows=8)
|
||||
|
||||
with mock_remote_table(server) as table:
|
||||
assert table._checkout_version is None, "caller's table starts unpinned"
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
list(ds) # drive at least one _open_pinned_table() call
|
||||
assert table._checkout_version is None, (
|
||||
"iterating a 2-phase dataset must not pin the caller's own "
|
||||
"table handle to a fixed version"
|
||||
)
|
||||
|
||||
|
||||
@functools.lru_cache
|
||||
def _cached_open_table(uri, name):
|
||||
return lancedb.connect(uri).open_table(name)
|
||||
|
||||
|
||||
@functools.lru_cache
|
||||
def _cached_open_table_with_session(uri, name):
|
||||
return lancedb.connect(uri, session=lancedb.Session()).open_table(name)
|
||||
|
||||
|
||||
class _ReturnsTable:
|
||||
def __init__(self, table):
|
||||
self.table = table
|
||||
|
||||
def __call__(self, name):
|
||||
return self.table
|
||||
|
||||
|
||||
@pytest.mark.parametrize("connection", ["local", "session", "memory"])
|
||||
def test_two_phase_does_not_pin_cached_factory_handle(tmp_path, connection):
|
||||
"""A connection_factory may return a cached, caller-owned handle: pinning
|
||||
the dataset's snapshot must leave that handle writable, must not need a
|
||||
picklable connection, and must keep reading the construction snapshot
|
||||
after the handle's table changes."""
|
||||
if connection == "memory":
|
||||
table = lancedb.connect("memory://").create_table(
|
||||
"t", pa.table({"id": list(range(8))})
|
||||
)
|
||||
table.add(pa.table({"id": [100]}))
|
||||
table.delete("id = 100") # the snapshot is at a version above 1
|
||||
factory = _ReturnsTable(table)
|
||||
else:
|
||||
lancedb.connect(tmp_path).create_table("t", pa.table({"id": list(range(8))}))
|
||||
open_table = (
|
||||
_cached_open_table_with_session
|
||||
if connection == "session"
|
||||
else _cached_open_table
|
||||
)
|
||||
factory = functools.partial(open_table, str(tmp_path))
|
||||
table = factory("t")
|
||||
|
||||
ds = StreamingDataset(
|
||||
table, block_size=4, shuffle=False, connection_factory=factory
|
||||
)
|
||||
table.delete("id = 0")
|
||||
table.add(pa.table({"id": [8]}))
|
||||
|
||||
assert table.count_rows() == 8
|
||||
assert [row["id"] for row in ds] == list(range(8))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2-phase shuffled reads (block_size)
|
||||
# ---------------------------------------------------------------------------
|
||||
# block_size switches StreamingDataset from 1-phase (per-row permutation) to
|
||||
# 2-phase (block-granularity shuffle + a row-level shuffle bounded by
|
||||
# max_shuffle_distance). NUM_ROWS=120 with block_size=10 gives 12 blocks,
|
||||
# which divides NUM_SPLITS=12 evenly, so most tests below reuse lance_table
|
||||
# and those constants without the runt blocks and mid-block split boundaries
|
||||
# covered explicitly by their own tests.
|
||||
|
||||
|
||||
def test_two_phase_full_coverage_no_duplicates(lance_table):
|
||||
"""Every sample ID appears exactly once across a full 2-phase epoch."""
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=10,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert len(ids) == NUM_ROWS
|
||||
assert sorted(ids) == list(range(NUM_ROWS)), "every row must appear exactly once"
|
||||
|
||||
|
||||
def test_two_phase_reads_runt_block(lance_table):
|
||||
"""A trailing partial block (block_size doesn't evenly divide the row
|
||||
count) is read like any other block."""
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=13, # NUM_ROWS=120 -> 9 full blocks and a 3-row runt
|
||||
shuffle=False,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(NUM_ROWS))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reshuffle_blocks_per_epoch", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"block_size,num_splits,filter",
|
||||
[
|
||||
# 12 blocks over 5 splits: split boundaries fall mid-block.
|
||||
pytest.param(10, 5, None, id="whole_blocks_uneven_splits"),
|
||||
# 9 full blocks plus a 3-row runt over 7 splits: 120 // 7 = 17 rows
|
||||
# per split, so exactly 1 row is dropped.
|
||||
pytest.param(13, 7, None, id="runt_and_uneven_splits"),
|
||||
# 60 live rows in 9 blocks of 7 (the last a 4-row runt) over 4 splits.
|
||||
pytest.param(7, 4, "id % 2 = 0", id="filtered"),
|
||||
],
|
||||
)
|
||||
def test_two_phase_drops_fewer_rows_than_splits(
|
||||
lance_table, block_size, num_splits, filter, reshuffle_blocks_per_epoch
|
||||
):
|
||||
"""Splits are cut by rows, not whole blocks, so each epoch drops fewer than
|
||||
num_splits rows (as 1-phase does) and every split serves the same count."""
|
||||
live_ids = set(range(NUM_ROWS)) if filter is None else set(range(0, NUM_ROWS, 2))
|
||||
rows_per_split = len(live_ids) // num_splits
|
||||
for epoch in range(2):
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=num_splits,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
epoch=epoch,
|
||||
block_size=block_size,
|
||||
filter=filter,
|
||||
reshuffle_blocks_per_epoch=reshuffle_blocks_per_epoch,
|
||||
)
|
||||
for split in range(num_splits):
|
||||
assert sum(b.stop - b.start for b in ds._split_blocks(split)) == (
|
||||
rows_per_split
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert len(ids) == len(set(ids)) == rows_per_split * num_splits
|
||||
assert set(ids) <= live_ids
|
||||
assert len(live_ids) - len(ids) < num_splits
|
||||
|
||||
|
||||
def test_two_phase_no_shuffle_preserves_order(lance_table):
|
||||
"""shuffle=False yields rows in exact original storage order."""
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=10,
|
||||
shuffle=False,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(NUM_ROWS)), (
|
||||
"shuffle=False must preserve original row order block-by-block"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_respects_max_shuffle_distance(lance_table):
|
||||
"""No row moves farther than max_shuffle_distance from its natural
|
||||
(block, then row) position within its split's own block assignment.
|
||||
|
||||
White-box: reconstructs the expected natural-rank order directly from
|
||||
ds._block_perm (the shuffled block order), since that's the reference
|
||||
frame the displacement bound is defined against, not raw table order.
|
||||
"""
|
||||
block_size = 10 # NUM_ROWS=120 -> 12 blocks
|
||||
max_shuffle_distance = 25
|
||||
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
max_shuffle_distance=max_shuffle_distance,
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
|
||||
natural_order = [
|
||||
row_id
|
||||
for bp in ds._block_perm
|
||||
for row_id in range(bp * block_size, (bp + 1) * block_size)
|
||||
]
|
||||
assert sorted(ids) == list(range(NUM_ROWS))
|
||||
assert sorted(natural_order) == list(range(NUM_ROWS))
|
||||
|
||||
natural_rank = {row_id: rank for rank, row_id in enumerate(natural_order)}
|
||||
for output_pos, row_id in enumerate(ids):
|
||||
displacement = abs(output_pos - natural_rank[row_id])
|
||||
assert displacement < max_shuffle_distance, (
|
||||
f"row {row_id} displaced {displacement} positions from its natural "
|
||||
f"rank, exceeding max_shuffle_distance={max_shuffle_distance}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs,expected_window,expected_distance",
|
||||
[
|
||||
pytest.param({}, 8, 80, id="defaults"),
|
||||
pytest.param({"window_blocks": 2}, 2, 20, id="window_override"),
|
||||
pytest.param({"max_shuffle_distance": 15}, 8, 15, id="distance_override"),
|
||||
],
|
||||
)
|
||||
def test_two_phase_window_defaults(
|
||||
lance_table, kwargs, expected_window, expected_distance
|
||||
):
|
||||
ds = StreamingDataset(
|
||||
lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10, **kwargs
|
||||
)
|
||||
assert ds._window_blocks == expected_window
|
||||
assert ds._max_shuffle_distance == expected_distance
|
||||
|
||||
|
||||
def test_two_phase_filter_counts_live_rows(tmp_path):
|
||||
"""block_size counts only rows passing filter; dead rows never appear."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"t",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(NUM_ROWS)),
|
||||
"category": ["train"] * 60 + ["val"] * 60,
|
||||
}
|
||||
),
|
||||
)
|
||||
ds = StreamingDataset(
|
||||
table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=10, # 60 live (train) rows -> 6 blocks exactly, no runt
|
||||
filter="category = 'train'",
|
||||
)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert all(i < 60 for i in ids), "only live (train) rows should appear"
|
||||
assert sorted(ids) == list(range(60))
|
||||
|
||||
|
||||
def test_two_phase_resume_checkpoint_round_trip(lance_table):
|
||||
"""state_dict/load_state_dict resumes a 2-phase dataset without gaps or
|
||||
repeats, the same guarantee test_doc_example_checkpoint verifies for
|
||||
1-phase."""
|
||||
steps_before_checkpoint = 5
|
||||
block_size = 10 # NUM_ROWS=120 -> 12 blocks, divides NUM_SPLITS=12 evenly
|
||||
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
)
|
||||
it = iter(ds)
|
||||
consumed = [next(it)["id"] for _ in range(steps_before_checkpoint * NUM_SPLITS)]
|
||||
checkpoint = ds.state_dict()
|
||||
remaining_original = [s["id"] for s in it]
|
||||
|
||||
ds_resumed = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
)
|
||||
ds_resumed.load_state_dict(checkpoint)
|
||||
remaining_resumed = [s["id"] for s in ds_resumed]
|
||||
|
||||
assert remaining_original == remaining_resumed, (
|
||||
"Resumed 2-phase dataset must continue from exactly the same position"
|
||||
)
|
||||
assert sorted(consumed + remaining_original) == list(range(NUM_ROWS)), (
|
||||
"Consumed + remaining must cover every row exactly once"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"saved,resumed,mismatched_key",
|
||||
[
|
||||
pytest.param(
|
||||
{"block_size": 10}, {"block_size": 5}, "block_size", id="block_size"
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10}, {}, "block_size", id="two_phase_into_one_phase"
|
||||
),
|
||||
pytest.param(
|
||||
{}, {"block_size": 10}, "block_size", id="one_phase_into_two_phase"
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10},
|
||||
{"block_size": 10, "max_shuffle_distance": 15},
|
||||
"max_shuffle_distance",
|
||||
id="max_shuffle_distance",
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10},
|
||||
{"block_size": 10, "reshuffle_blocks_per_epoch": False},
|
||||
"reshuffle_blocks_per_epoch",
|
||||
id="reshuffle_blocks_per_epoch",
|
||||
),
|
||||
pytest.param(
|
||||
{"block_size": 10},
|
||||
{"block_size": 10, "shuffle": False},
|
||||
"shuffle",
|
||||
id="shuffle",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_two_phase_checkpoint_rejects_different_read_order(
|
||||
lance_table, saved, resumed, mismatched_key
|
||||
):
|
||||
"""Saved positions index one 2-phase read order; resuming them under
|
||||
another would replay consumed rows and skip unread ones. The error names
|
||||
the setting to change."""
|
||||
|
||||
def make(options):
|
||||
return StreamingDataset(
|
||||
lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED, **options
|
||||
)
|
||||
|
||||
source = make(saved)
|
||||
it = iter(source)
|
||||
for _ in range(2 * NUM_SPLITS):
|
||||
next(it)
|
||||
checkpoint = source.state_dict()
|
||||
|
||||
with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch: checkpoint"):
|
||||
make(resumed).load_state_dict(checkpoint)
|
||||
with pytest.raises(ValueError, match=f"^{mismatched_key} mismatch across"):
|
||||
StreamingDataset.merge_state_dicts([checkpoint, make(resumed).state_dict()])
|
||||
|
||||
|
||||
def test_two_phase_failed_reader_build_closes_built_readers(lance_table, monkeypatch):
|
||||
"""A resume position past a split's end fails while building readers; the
|
||||
readers built before it must still release their prefetch executors."""
|
||||
ds = StreamingDataset(
|
||||
lance_table, num_splits=2, shuffle_seed=SHUFFLE_SEED, block_size=10
|
||||
)
|
||||
checkpoint = ds.state_dict()
|
||||
checkpoint["positions_consumed_per_split"] = [0, NUM_ROWS]
|
||||
ds.load_state_dict(checkpoint)
|
||||
|
||||
closed = []
|
||||
close = streaming._TwoPhaseSplitReader.close
|
||||
|
||||
def counting_close(reader):
|
||||
closed.append(reader)
|
||||
close(reader)
|
||||
|
||||
monkeypatch.setattr(streaming._TwoPhaseSplitReader, "close", counting_close)
|
||||
with pytest.raises(ValueError, match="out of range"):
|
||||
list(ds)
|
||||
assert len(closed) == 1
|
||||
|
||||
|
||||
def test_two_phase_pinned_version_survives_concurrent_write(tmp_path):
|
||||
"""The block plan is pinned to the table version at construction; a
|
||||
write between construction and iteration must not change what an
|
||||
in-progress epoch reads."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", pa.table({"id": list(range(8))}))
|
||||
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
table.delete("id = 0") # mutate after construction, before iteration
|
||||
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(8)), (
|
||||
"must read the version pinned at construction, not the live, since-mutated one"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_pinned_memory_table_survives_concurrent_write():
|
||||
"""Same guarantee as the on-disk test above, but for a memory:// table.
|
||||
|
||||
A memory table's "pickle state" is its row data (to_arrow()), not just
|
||||
reopen coordinates, so it must be captured once at construction -- not
|
||||
recomputed from the live table on every _open_pinned_table() call --
|
||||
or a write made after construction would leak into every later read.
|
||||
"""
|
||||
db = lancedb.connect("memory://")
|
||||
table = db.create_table("t", pa.table({"id": list(range(8))}))
|
||||
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
table.delete("id = 0")
|
||||
table.add(pa.table({"id": [8]}))
|
||||
|
||||
ids = [s["id"] for s in ds]
|
||||
assert ids == list(range(8)), (
|
||||
"must read the snapshot captured at construction, not the live, "
|
||||
"since-mutated one"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_memory_table_already_at_a_later_version():
|
||||
"""Constructing over a memory table already past version 1 must not
|
||||
fail: the pin is the snapshot's data, not a version number to replay
|
||||
against a freshly rebuilt (always version-1) in-memory table."""
|
||||
db = lancedb.connect("memory://")
|
||||
table = db.create_table("t", pa.table({"id": list(range(4))}))
|
||||
table.add(pa.table({"id": [4, 5, 6, 7]})) # now at version 2, 8 live rows
|
||||
|
||||
ds = StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
ids = [s["id"] for s in ds]
|
||||
assert sorted(ids) == list(range(8))
|
||||
|
||||
|
||||
def test_two_phase_reader_plan_arrays_are_int32(lance_table):
|
||||
"""_plan_block_pos/_plan_local_offset are retained for the reader's
|
||||
whole lifetime, one entry per row in the entire split (the open
|
||||
whole-split-memory review thread) -- so their dtype is a real, constant
|
||||
memory-footprint decision, not an implementation detail. Pinned here at
|
||||
int32 (half of int64) so a future change can't silently regress it."""
|
||||
ds = StreamingDataset(
|
||||
lance_table, num_splits=1, shuffle_seed=SHUFFLE_SEED, block_size=10
|
||||
)
|
||||
reader = ds._make_two_phase_reader(0, ds._open_pinned_table(), None)
|
||||
assert reader._plan_block_pos.dtype == np.int32
|
||||
assert reader._plan_local_offset.dtype == np.int32
|
||||
# Values must still be correct, not just narrower -- e.g. a block index
|
||||
# silently wrapping around int32 would be a far worse regression than
|
||||
# the memory this dtype choice saves.
|
||||
assert reader._plan_block_pos.max() < len(ds._split_blocks(0))
|
||||
assert reader._plan_local_offset.max() < 10 # block_size
|
||||
|
||||
|
||||
class _LookupCountingDict(dict):
|
||||
def __init__(self, *args):
|
||||
super().__init__(*args)
|
||||
self.lookups = 0
|
||||
|
||||
def __getitem__(self, key):
|
||||
self.lookups += 1
|
||||
return super().__getitem__(key)
|
||||
|
||||
def get(self, key, default=None):
|
||||
self.lookups += 1
|
||||
return super().get(key, default)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"skip,swap_calls",
|
||||
[
|
||||
pytest.param(0, False, id="fresh"),
|
||||
pytest.param(1500, False, id="resumed"),
|
||||
# io_queue_depth lets calls take the reader's lock out of order.
|
||||
pytest.param(0, True, id="out_of_order"),
|
||||
],
|
||||
)
|
||||
def test_two_phase_reader_sequential_read_is_linear_in_blocks(skip, swap_calls):
|
||||
"""A sequential read must fetch each block once and keep per-call
|
||||
bookkeeping bounded by the resident window, not by how many blocks the
|
||||
split has already passed -- otherwise prefetch cost grows quadratically
|
||||
with split size."""
|
||||
num_blocks, block_size, batch = 400, 8, 8
|
||||
block_ids = list(range(1000, 1000 + num_blocks))
|
||||
reads = []
|
||||
|
||||
def read_block(block_id):
|
||||
reads.append(block_id)
|
||||
# Two record batches per block, as a multi-batch scan returns.
|
||||
half = block_size // 2
|
||||
return pa.concat_tables(
|
||||
pa.table({"block": [block_id] * half, "row": range(lo, lo + half)})
|
||||
for lo in (0, half)
|
||||
)
|
||||
|
||||
reader = streaming._TwoPhaseSplitReader(
|
||||
block_ids=block_ids,
|
||||
block_live_counts=[block_size] * num_blocks,
|
||||
shuffle=True,
|
||||
max_shuffle_distance=4 * block_size,
|
||||
seed=SHUFFLE_SEED,
|
||||
read_block_fn=read_block,
|
||||
columns=None,
|
||||
skip=skip,
|
||||
prefetch_depth=2,
|
||||
)
|
||||
try:
|
||||
# Later positions overwrite earlier ones, leaving each block's last.
|
||||
expected_last_pos = {
|
||||
bp: pos for pos, bp in enumerate(reader._plan_block_pos.tolist())
|
||||
}
|
||||
assert reader._block_last_pos == expected_last_pos
|
||||
|
||||
reader._block_last_pos = _LookupCountingDict(reader._block_last_pos)
|
||||
starts = list(range(0, reader.num_rows, batch))
|
||||
if swap_calls:
|
||||
starts[0::2], starts[1::2] = starts[1::2], starts[0::2]
|
||||
outputs = {}
|
||||
for start in starts:
|
||||
out = reader.__getitems__(range(start, min(start + batch, reader.num_rows)))
|
||||
outputs[start] = list(
|
||||
zip(out.column("block").to_pylist(), out.column("row").to_pylist())
|
||||
)
|
||||
assert all(
|
||||
t.column("block").num_chunks == 1 for t in reader._loaded.values()
|
||||
)
|
||||
rows = [row for start in sorted(outputs) for row in outputs[start]]
|
||||
num_calls = len(starts)
|
||||
finally:
|
||||
reader.close()
|
||||
|
||||
expected_rows = [
|
||||
(block_ids[bp], off)
|
||||
for bp, off in zip(
|
||||
reader._plan_block_pos.tolist(), reader._plan_local_offset.tolist()
|
||||
)
|
||||
]
|
||||
assert rows == expected_rows
|
||||
if skip == 0:
|
||||
assert sorted(rows) == [
|
||||
(bid, off) for bid in block_ids for off in range(block_size)
|
||||
]
|
||||
needed_blocks = {block_ids[bp] for bp in expected_last_pos}
|
||||
assert sorted(reads) == sorted(needed_blocks)
|
||||
# Rescanning every already-passed block on each prefetch top-up grows
|
||||
# quadratically (~29k lookups fresh here); a bounded walk stays linear
|
||||
# (~2k).
|
||||
assert reader._block_last_pos.lookups < 10 * (num_calls + num_blocks)
|
||||
|
||||
|
||||
def test_two_phase_auto_blocks_per_epoch_reads_only_sampled_blocks(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
"""blocks_per_epoch='auto' must sample whole blocks: a scattered row
|
||||
sample touches nearly every block and so reads the whole token column."""
|
||||
table = _create_token_table(tmp_path, [[1, 2, 3]] * 1000)
|
||||
reads = []
|
||||
read_block = StreamingDataset._read_block
|
||||
|
||||
def counting_read_block(self, pinned_table, block, columns):
|
||||
reads.append(block)
|
||||
return read_block(self, pinned_table, block, columns)
|
||||
|
||||
monkeypatch.setattr(StreamingDataset, "_read_block", counting_read_block)
|
||||
with pytest.warns(UserWarning, match="approximate token-count sample"):
|
||||
dataset = _packed_dataset(
|
||||
table, 4, blocks_per_epoch="auto", num_splits=2, block_size=10
|
||||
)
|
||||
|
||||
# 1% of each 500-row split rounds up to a single 10-row block per split.
|
||||
assert len(reads) == 2
|
||||
assert reads[0] in dataset._split_blocks(0)
|
||||
assert reads[1] in dataset._split_blocks(1)
|
||||
# Every document is 3 tokens plus EOS, so the sample is exact: 4000 / 4.
|
||||
assert dataset.state_dict()["blocks_per_epoch"] == 1000
|
||||
|
||||
|
||||
def test_two_phase_rejects_rte_write_spec_table(tmp_path):
|
||||
"""An RTE write spec means some acknowledged writes live only in the
|
||||
MemWAL, invisible to a version-pinned read; block_size must refuse the
|
||||
table at construction rather than silently reading stale base-table
|
||||
values (mirroring the row-id rejection 1-phase already applies)."""
|
||||
from lancedb import RTEWriteSpec
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64(), nullable=False),
|
||||
pa.field("value", pa.int64(), nullable=False),
|
||||
]
|
||||
)
|
||||
table = db.create_table(
|
||||
"t",
|
||||
pa.Table.from_pydict({"id": list(range(8)), "value": [0] * 8}, schema=schema),
|
||||
)
|
||||
table.set_unenforced_primary_key("id")
|
||||
table.enable_rte(RTEWriteSpec.bucket("id", 1))
|
||||
table.merge_insert(
|
||||
"id"
|
||||
).when_matched_update_all().when_not_matched_insert_all().execute(
|
||||
pa.Table.from_pydict({"id": list(range(8)), "value": [99] * 8}, schema=schema)
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="RTE write spec"):
|
||||
StreamingDataset(table, num_splits=1, block_size=4, shuffle=False)
|
||||
|
||||
|
||||
def test_two_phase_rejects_fingerprinted_checkpoint(lance_table):
|
||||
"""A checkpoint tied to a split_strategy permutation cannot resume block mode."""
|
||||
source = StreamingDataset(
|
||||
lance_table,
|
||||
split_strategy=lambda b: b.bootstrap_sample(
|
||||
2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED
|
||||
),
|
||||
num_splits=NUM_SPLITS,
|
||||
)
|
||||
checkpoint = source.state_dict()
|
||||
assert "perm_fingerprint" in checkpoint
|
||||
|
||||
target = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=checkpoint["shuffle_seed"],
|
||||
block_size=10,
|
||||
)
|
||||
with pytest.raises(ValueError, match="no permutation table"):
|
||||
target.load_state_dict(checkpoint)
|
||||
|
||||
|
||||
def test_two_phase_reshuffle_blocks_per_epoch_toggle(lance_table):
|
||||
"""reshuffle_blocks_per_epoch=False keeps each split's blocks fixed
|
||||
across epochs; the default (True) reassigns them every epoch."""
|
||||
block_size = 10 # NUM_ROWS=120 -> 12 blocks
|
||||
|
||||
def block_perm_for(epoch, reshuffle):
|
||||
ds = StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=1,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
block_size=block_size,
|
||||
epoch=epoch,
|
||||
reshuffle_blocks_per_epoch=reshuffle,
|
||||
)
|
||||
return list(ds._block_perm)
|
||||
|
||||
assert block_perm_for(0, False) == block_perm_for(1, False), (
|
||||
"blocks must stay pinned to the same split across epochs when disabled"
|
||||
)
|
||||
assert block_perm_for(0, True) != block_perm_for(1, True), (
|
||||
"blocks should be reassigned across epochs by default"
|
||||
)
|
||||
|
||||
|
||||
def test_two_phase_too_few_blocks_for_num_splits_raises(tmp_path):
|
||||
"""Fewer blocks than num_splits would leave some splits with no data."""
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("t", pa.table({"id": list(range(20))})) # 2 blocks
|
||||
with pytest.raises(ValueError):
|
||||
StreamingDataset(table, num_splits=4, shuffle_seed=SHUFFLE_SEED, block_size=10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"extra_kwargs",
|
||||
[
|
||||
pytest.param(
|
||||
{"block_size": 10, "shuffle_clump_size": 5},
|
||||
id="shuffle_clump_size_with_block_size",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"block_size": 10,
|
||||
"split_strategy": lambda b: b.split_sequential(fixed=NUM_SPLITS),
|
||||
},
|
||||
id="split_strategy_with_block_size",
|
||||
),
|
||||
pytest.param({"block_size": 1}, id="block_size_too_small"),
|
||||
pytest.param({"window_blocks": 2}, id="window_blocks_without_block_size"),
|
||||
pytest.param(
|
||||
{"max_shuffle_distance": 5}, id="max_shuffle_distance_without_block_size"
|
||||
),
|
||||
pytest.param(
|
||||
{"reshuffle_blocks_per_epoch": True},
|
||||
id="reshuffle_blocks_per_epoch_without_block_size",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_two_phase_constructor_validation_raises(lance_table, extra_kwargs):
|
||||
"""Invalid 2-phase parameter combinations raise ValueError at construction."""
|
||||
with pytest.raises(ValueError):
|
||||
StreamingDataset(
|
||||
lance_table,
|
||||
num_splits=NUM_SPLITS,
|
||||
shuffle_seed=SHUFFLE_SEED,
|
||||
**extra_kwargs,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# split_strategy escape hatch
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -611,8 +611,7 @@ class _FunctionDeclarationInner:
|
||||
|
||||
async def add_function_columns(
|
||||
self,
|
||||
application_json,
|
||||
output_name,
|
||||
bindings,
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
@@ -623,8 +622,7 @@ class _FunctionDeclarationInner:
|
||||
):
|
||||
self.calls.append(
|
||||
(
|
||||
json.loads(application_json),
|
||||
output_name,
|
||||
[(json.loads(app), name) for app, name in bindings],
|
||||
auto_refresh_enabled,
|
||||
auto_refresh_interval_seconds,
|
||||
total_cpu_millis,
|
||||
@@ -654,8 +652,9 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
mapping_type({"features": application._copy(update={"columns": {}})})
|
||||
)
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] == "features"
|
||||
assert inner.calls[-1][2:] == (None, None, None, None, None)
|
||||
[(_, name)], *options = inner.calls[-1]
|
||||
assert name == "features"
|
||||
assert options == [None, None, None, None, None]
|
||||
|
||||
bare = application._copy(update={"columns": {}}).rename(
|
||||
columns={"normalized_text": "search_text"}
|
||||
@@ -668,19 +667,30 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
|
||||
total_gpu_count=0,
|
||||
)
|
||||
assert result == "declared"
|
||||
assert inner.calls[-1][1] is None
|
||||
assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"}
|
||||
assert inner.calls[-1][2:] == (False, 300, 8000, None, 0)
|
||||
[(payload, name)], *options = inner.calls[-1]
|
||||
assert name is None
|
||||
assert payload["columns"] == {"normalized_text": "search_text"}
|
||||
assert options == [False, 300, 8000, None, 0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_rejects_multiple_bindings_and_unknown_newer_application():
|
||||
async def test_add_columns_routes_multiple_bindings_in_one_call():
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()._copy(update={"columns": {}})
|
||||
assert await table.add_columns({"a": application, "b": application}) == "declared"
|
||||
assert len(inner.calls) == 1
|
||||
assert [name for _, name in inner.calls[0][0]] == ["a", "b"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_columns_rejects_mixed_bindings_and_unknown_newer_application():
|
||||
inner = _FunctionDeclarationInner()
|
||||
table = AsyncTable(inner)
|
||||
application = known_application()
|
||||
|
||||
with pytest.raises(ValueError, match="exactly one Function binding"):
|
||||
await table.add_columns({"a": application, "b": application})
|
||||
with pytest.raises(ValueError, match="cannot mix Function applications"):
|
||||
await table.add_columns({"a": application, "b": "1+1"})
|
||||
|
||||
future = json.loads(fixture("remote_function_application.json"))
|
||||
application = FunctionApplication(**future)
|
||||
|
||||
@@ -36,6 +36,15 @@ def is_row_id_take(body) -> bool:
|
||||
return "_rowid" in (body.get("filter") or "")
|
||||
|
||||
|
||||
def is_row_offset_take(body) -> bool:
|
||||
"""True when a query body fetches specific rows by ``_rowoffset``.
|
||||
|
||||
This is the request shape ``Table.take_offsets`` sends on the remote
|
||||
backend, distinct from ``is_row_id_take``'s ``_rowid IN (...)``.
|
||||
"""
|
||||
return "_rowoffset" in (body.get("filter") or "")
|
||||
|
||||
|
||||
def arrow_file_bytes(table: pa.Table) -> bytes:
|
||||
"""Serialize to the Arrow IPC *file* framing the /query/ route answers with."""
|
||||
sink = pa.BufferOutputStream()
|
||||
@@ -175,6 +184,37 @@ class MockPermutationServer:
|
||||
pa.table({"_rowid": pa.array(row_ids, pa.uint64())}),
|
||||
)
|
||||
|
||||
if is_row_offset_take(body):
|
||||
# A _rowoffset take (2-phase's filtered block reads): this
|
||||
# table's rows are never deleted/reordered, so id == _rowoffset
|
||||
# for every row, same invariant as id == _rowid above.
|
||||
row_offsets = sorted(parse_in_list(body["filter"]))
|
||||
columns = body.get("columns") or ["id", "_rowoffset"]
|
||||
values = {"id": row_offsets, "_rowoffset": row_offsets}
|
||||
return self._arrow(
|
||||
request,
|
||||
pa.table(
|
||||
{
|
||||
col: pa.array(
|
||||
values[col],
|
||||
pa.uint64() if col == "_rowoffset" else pa.int64(),
|
||||
)
|
||||
for col in columns
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
if body.get("columns") == ["_rowoffset"] and "IN" in (body.get("filter") or ""):
|
||||
# 2-phase's live-offset precompute scan: a user filter over
|
||||
# "_rowoffset" alone. This mock only understands `<col> IN
|
||||
# (...)` filters (not arbitrary SQL), and since id == _rowoffset
|
||||
# for every row here, reuses parse_in_list regardless of which
|
||||
# column the filter actually names.
|
||||
row_offsets = sorted(parse_in_list(body["filter"]))
|
||||
return self._arrow(
|
||||
request, pa.table({"_rowoffset": pa.array(row_offsets, pa.uint64())})
|
||||
)
|
||||
|
||||
# The schema probe: filtered to nothing, so it carries schema and no rows.
|
||||
return self._arrow(request, pa.table({"id": pa.array([], pa.int64())}))
|
||||
|
||||
|
||||
+14
-10
@@ -2708,12 +2708,11 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (application_json, output_name, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))]
|
||||
#[pyo3(signature = (bindings, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, total_cpu_millis=None, total_memory_bytes=None, total_gpu_count=None, gpu_class=None, gpu_count=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn add_function_columns<'py>(
|
||||
self_: PyRef<'py, Self>,
|
||||
application_json: String,
|
||||
output_name: Option<String>,
|
||||
bindings: Vec<(String, Option<String>)>,
|
||||
auto_refresh_enabled: Option<bool>,
|
||||
auto_refresh_interval_seconds: Option<u64>,
|
||||
total_cpu_millis: Option<u64>,
|
||||
@@ -2722,8 +2721,15 @@ impl Table {
|
||||
gpu_class: Option<String>,
|
||||
gpu_count: Option<u32>,
|
||||
) -> PyResult<Bound<'py, PyAny>> {
|
||||
let application =
|
||||
lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?;
|
||||
let bindings = bindings
|
||||
.into_iter()
|
||||
.map(|(json, name)| {
|
||||
Ok((
|
||||
lancedb::function::FunctionApplication::from_json(&json).infer_error()?,
|
||||
name,
|
||||
))
|
||||
})
|
||||
.collect::<PyResult<Vec<_>>>()?;
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let options = ComputedColumnOptions {
|
||||
auto_refresh_enabled: auto_refresh_enabled.unwrap_or(true),
|
||||
@@ -2736,11 +2742,9 @@ impl Table {
|
||||
};
|
||||
options.validate().infer_error()?;
|
||||
future_into_py(self_.py(), async move {
|
||||
let builder = match output_name {
|
||||
Some(name) => inner.add_columns().function_as(name, application),
|
||||
None => inner.add_columns().function(application),
|
||||
};
|
||||
let result = builder
|
||||
let result = inner
|
||||
.add_columns()
|
||||
.function_bindings(bindings)
|
||||
.computed_options(options)
|
||||
.execute()
|
||||
.await
|
||||
|
||||
Generated
+9
-9
@@ -1912,7 +1912,7 @@ requires-dist = [
|
||||
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
|
||||
{ name = "pydantic", specifier = ">=2.7.4,<3" },
|
||||
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b35" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.1.0b2" },
|
||||
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
|
||||
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
|
||||
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
|
||||
@@ -3649,20 +3649,20 @@ crypto = [
|
||||
|
||||
[[package]]
|
||||
name = "pylance"
|
||||
version = "15.0.0b35"
|
||||
version = "15.1.0b2"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
dependencies = [
|
||||
{ name = "lance-namespace" },
|
||||
{ name = "pyarrow" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_cEkBo/pylance-15.0.0b35-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:d00bacc2903b668d0bddca9edd35e4edfbfc9d53502191cfa3335a2c10fd9e8d" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_YjJ2V/pylance-15.0.0b35-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5550a9d22338b87330c9c215e5f12a070e48db5bc71f9d34d87ac2a396434dfe" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1fUTKP/pylance-15.0.0b35-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21e857d1c875827c4668d40b173fe449d3cbeb681f1316fd034a4e99291b745d" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1EvL1C/pylance-15.0.0b35-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:816bda4b4bd81fed9804a47a67554c1f15a966b6353f9f9f176804eeeaea0b70" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1NluEu/pylance-15.0.0b35-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:9368979eb74292d0a7df72f82b6f6084ea9444473b4270f444e7a1219ee401d3" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1ts9EU/pylance-15.0.0b35-cp310-abi3-win_amd64.whl", hash = "sha256:054bb67bee04d9dd17a01294314f6b078bbbe2a2b0a143ac6a5fba06b875de4b" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_Z0b20/pylance-15.0.0b35-cp310-abi3-win_arm64.whl", hash = "sha256:34fd81da55e96da50ef0f3cb658de55f526ff989cd86270372cc6dd454c684ba" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_vSWFg/pylance-15.1.0b2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:297f8d3059be999ade63b04d9ce592b71f3c6d5d7fd70cdbb3d2f6a65bc310f2" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_28KJav/pylance-15.1.0b2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:414bfef47bd01a159f392a8e8e099fee7c9ab1be2c847ca2cd224f623fdd277e" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_7FE7R/pylance-15.1.0b2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:841c44301b060aeb4309bc64c8b60be17b5a12c4801aca2a7f6ded1dd2e414e9" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2jMYDF/pylance-15.1.0b2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5979250018dc7ccabb8193f9f4c01b3c581d48adedd7a73b9ebfcc0104bb7d19" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1XQt8E/pylance-15.1.0b2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd67e0ada56f9574c12a4300e0ceccb16830d2b16ebc7dabaf1ced38cc7d8593" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_H8fyY/pylance-15.1.0b2-cp310-abi3-win_amd64.whl", hash = "sha256:120ed03b30176db76fa1c25223531a59abb77e5a80a9c85923914ad161132904" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_zdLur/pylance-15.1.0b2-cp310-abi3-win_arm64.whl", hash = "sha256:5eebf0d2eba1d32ab3ef43c1d69614e265bf7e428480601a4287e3fb33290292" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user