mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(python): add two-phase shuffled reads (2PSR) to elastic dataloader (#5066)
Supersedes #4263, which I can no longer push to. This PR continues the same branch, so the review history is there. ## Summary Adds two-phase shuffled reads (2PSR) to `StreamingDataset`, enabled with `block_size`: 1. **Block shuffle:** contiguous blocks of `block_size` live rows are shuffled and assigned to splits. This replaces 1-phase's per-row take with mostly contiguous range scans, which are much cheaper on object storage. 2. **Bounded row shuffle:** each split shuffles rows over a rolling window of `window_blocks` blocks. `max_shuffle_distance` bounds how far a row can move. The feature also supports `filter` (sparse takes of live rows), `reshuffle_blocks_per_epoch`, resume and checkpointing, background block prefetch, and multi-worker DataLoaders. 2PSR stays opt-in: `block_size=None` keeps today's 1-phase behavior. Since the last review round: - **Fixed worker startup with small blocks.** The pickled dataset no longer grows with the number of blocks; the block order is rebuilt in `__setstate__`. Once that pickle passed the 64 KiB pipe buffer, spawned DataLoader workers started one at a time (~280 s with 128 workers at ≤2,048-row blocks). - **Fixed per-call block copies.** Each loaded block is combined into a single chunk. Before, `take` on a multi-chunk block concatenated the whole block on every call. - **Fixed early eviction.** Blocks are evicted only behind the contiguous prefix of rows already served. With `io_queue_depth > 1`, calls can arrive out of order and previously evicted blocks that were still needed, causing 5–40% extra reads. - **New default:** `window_blocks` now defaults to 8, and the docstring recommends `block_size=512` with DataLoader workers. None of these fixes changes which rows are read or their order. A check across 12 config, epoch and seed combinations on 8 ranks gave identical per-rank order before and after. ## Benchmarks Throughput was measured on EC2 i4i.32xlarge in us-west-2, reading a FineWeb-Edu table of 4,096 B rows. Each number is the median of 3 trials, and each trial is a full pass. 2PSR used 512-row blocks, 256 splits, 128 workers and `io_queue_depth=4`. 1-phase used 32 splits, 8 workers and `io_queue_depth=32`. | Storage | Rows | 2PSR | 1-phase | Speedup | |---|---|---|---|---| | S3 | 8.4M (34 GB) | 16.9 s | 230 s | 13.6× | | S3 | 33.6M (137 GB) | 45.6 s | 781 s | 17.1× | | S3 | 134M (550 GB) | 168 s | 3,098 s | 18.4× | | Local NVMe | 8.4M | 16.4 s | 116 s | 7.1× | On the 8.4M-row S3 table, 2PSR reads 1.5–2.0 GB/s at every block size from 128 to 65,536 rows. A fit across the three S3 sizes gives 2PSR about 7 s fixed cost plus 3.4 GB/s, and 1-phase about 39 s plus 0.18 GB/s. That puts the large-table limit near 19×. Quality was measured by pretraining GPT-2 124M on 2^21 FineWeb-Edu docs for 16 epochs on 8×H100. The table shows final validation loss, mean ± SD over 3 seeds: | Reader | Final val loss | |---|---| | 1-phase | 2.8464 ± 0.0006 | | 2PSR, `block_size=128`, msd 4,096 | 2.8457 ± 0.0011 | | 2PSR, `block_size=512`, msd 4,096 | 2.8457 ± 0.0007 | | 2PSR, `block_size=2048`, msd 32,768 | 2.8466 ± 0.0009 | | No shuffle (1 seed) | 2.8606 | Every 2PSR config is within seed noise of 1-phase. The 95% confidence intervals of the difference all include zero and are at most 13% of the no-shuffle penalty. Training throughput was the same for every reader (3.15–3.18M tok/s, GPU-bound). ## Testing - `test_elastic_dataloader.py` and `test_permutation.py`: all 324 tests pass after merging `main`. The new tests cover: - pickle size independent of block count; - single-chunk blocks; - no re-reads under out-of-order calls; - window defaults; - resume, filter, worker and checkpoint behavior. - `ruff check` and `ruff format --check` are clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
co-authored by
Claude Opus 5
Xuanwo
parent
4d9fd358f8
commit
147fdb25a0
@@ -54,7 +54,7 @@ ds = StreamingDataset(
|
||||
|
||||
## Shuffling Rows {#shuffling-rows}
|
||||
|
||||
In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles at one of two granularities, selected by the `shuffle_clump_size` parameter.
|
||||
In model training, model quality can be hurt by unintentionally learning patterns in the ordering of the source data. Shuffling the dataset before training alleviates this problem. However, fetching rows with scattered sparse reads across object storage can be dramatically slower than fetching contiguous batches. `StreamingDataset` shuffles rows individually by default; `shuffle_clump_size` and `block_size` each trade some randomness for more contiguous reads.
|
||||
|
||||
<Note>
|
||||
`StreamingDataset` shuffle seeds combine `shuffle_seed` with `epoch`; each epoch produces a different permutation while runs
|
||||
@@ -109,6 +109,34 @@ for sample in eval_ds:
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Block Shuffle {#block-shuffle}
|
||||
|
||||
Setting `block_size` enables a two-phase shuffled read. First, contiguous blocks of `block_size` rows are shuffled and read with range scans. Then each split shuffles rows across a rolling window of `window_blocks` blocks (default `8`). Unlike a clump, a block does not stay together: a row can move up to `max_shuffle_distance` positions (default `window_blocks * block_size`) from its place in the block order. Every split serves the same number of rows, so a split can start or end partway through a block, and fewer than `num_splits` rows are left out per epoch.
|
||||
|
||||
`block_size=512` is a good starting point. Use [DataLoader workers](#dataloader-workers), because throughput comes from reading many splits in parallel; `num_splits` must be divisible by `world_size * num_workers`. Keep in mind:
|
||||
|
||||
- The table needs at least `num_splits * block_size` live rows (after `filter`), so that each split gets at least one full block. The example below needs at least 32,768.
|
||||
- `block_size` cannot be combined with `shuffle_clump_size` or `split_strategy`; passing both raises `ValueError`.
|
||||
- On LanceDB Embedded, reading on-disk tables requires the optional `pylance` package (`pip install "lancedb[pylance]"`).
|
||||
|
||||
<CodeGroup>
|
||||
```py Python icon=Python
|
||||
# Block shuffle: shuffle contiguous blocks, then rows within a bounded window.
|
||||
for epoch in range(num_epochs):
|
||||
ds = StreamingDataset(
|
||||
table,
|
||||
shuffle_seed=42,
|
||||
epoch=epoch,
|
||||
num_splits=64,
|
||||
block_size=512, # rows per contiguous block read
|
||||
window_blocks=8, # blocks per split whose rows are mixed together
|
||||
)
|
||||
loader = StreamingDataLoader(ds, batch_size=32, num_workers=16)
|
||||
for batch in loader:
|
||||
train_step(batch)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Fetching {#fetching}
|
||||
|
||||
Traditional datasets have often been designed to yield a single sample at a time upon iteration. However, in modern use cases, accessing data on object storage one row at a time introduces too much per-call overhead. Thus, `StreamingDataset` fetches data in read batches, whose size is controlled by the `read_batch_size` parameter (defaults = `64`).
|
||||
|
||||
+990
-125
File diff suppressed because it is too large
Load Diff
@@ -4433,17 +4433,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
|
||||
|
||||
@@ -4512,13 +4517,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
|
||||
@@ -4527,7 +4539,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,
|
||||
@@ -4535,6 +4546,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":
|
||||
|
||||
@@ -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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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())}))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user