From 747a62114cbc3b687d3ced5b4f194f1f38425b1c Mon Sep 17 00:00:00 2001 From: Aiman Malib <84276911+aimanmalib@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:20:01 +0800 Subject: [PATCH] fix(python): keep rows when Permutation.iter gets short reader batches (#5156) ## What changed `Permutation.iter()` now passes the reader batches through a small `_rebatch()` helper in `python/python/lancedb/permutation.py`. It regroups short batches into batches of exactly `batch_size` rows before `transform_fn` runs. Full batches with nothing pending are passed through without a copy, and empty batches are dropped. Only the final remainder is subject to `skip_last_batch`. The `iter()` docstring now states this. ## Why Fixes #5155 `iter()` checked `batch.num_rows == batch_size` on every batch, but the Rust `PermutationReader` only bounds batches by `batch_size`. When a split is read, the plan batches are filtered, so short batches show up in the middle of the stream. `for batch in permutation` (`skip_last_batch=True`) then dropped them silently: with `split_hash` it returned 0 of 502 rows, and a shuffled random split lost a batch in the middle. With `skip_last_batch=False` the rows came through but in batches smaller than `batch_size`. The fix is in Python because the exact batch size is a promise of the Python API (`test_iter_basic`, `test_iter_skip_last_batch`); the Rust reader tests assert `<=`. The TypeScript SDK has no `Permutation`. ## How it was tested Run in a `python:3.12-slim` container with the `0.42.0b21` nightly wheel and the Python sources from this branch copied over it (no Rust change, so no `maturin develop`). - New test `test_iter_keeps_rows_from_short_reader_batches` iterates a `split_hash` permutation with and without `skip_last_batch` and checks batch sizes and row ids. On `main` it fails with `assert [18, 18, 19, 20, 18, 20, ...] == [37, 37, 37, 37, 37, 37, ...]`. - New test `test_rebatch_regroups_short_and_empty_batches` covers empty batches in the middle and at the end, a batch larger than `batch_size`, the final remainder, an empty stream, and the schema. - With the fix: both new tests pass in 5 consecutive runs, and `test_permutation.py` passes (96 passed). - With `permutation.py` restored from `main`, only `test_iter_keeps_rows_from_short_reader_batches` fails (1 failed, 94 passed). - `ruff format --check .` and `ruff check .` in `python/` with ruff 0.9.9: clean. - `pyright` CI config does not include `permutation.py` or the tests. Running it on the file directly reports no new errors in the changed code. `test_torch.py` was skipped because torch is not installed in the container. Written with help from Claude Code. --------- Co-authored-by: Claude Opus 5.5 --- python/python/lancedb/permutation.py | 70 +++++++++-- python/python/tests/test_permutation.py | 151 ++++++++++++++++++++++++ 2 files changed, 212 insertions(+), 9 deletions(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index d92a5a22d..6ef96c149 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -1302,9 +1302,12 @@ class Permutation: """ Iterate over the permutation in batches - If skip_last_batch is True, the last batch will be skipped if it is not a - multiple of batch_size. + Every batch except the last one has exactly batch_size rows. If + skip_last_batch is True, the last batch will be skipped if it has fewer + than batch_size rows. """ + if batch_size <= 0: + raise ValueError("batch_size must be greater than 0") self._ensure_open() async def get_iter(): @@ -1315,13 +1318,15 @@ class Permutation: async def get_next(): return await async_iter.__anext__() - try: - while True: - batch = LOOP.run(get_next()) - if batch.num_rows == batch_size or not skip_last_batch: - yield self.transform_fn(batch) - except StopAsyncIteration: - return + def reader_batches(): + try: + while True: + yield LOOP.run(get_next()) + except StopAsyncIteration: + return + + for batch in _rebatch(reader_batches(), batch_size, skip_last_batch): + yield self.transform_fn(batch) def with_format( self, @@ -1688,3 +1693,50 @@ class Permutation: Repeat the permutation `times` times """ raise Exception("with_repeat is not yet implemented") + + +def _rebatch( + batches: Iterator[pa.RecordBatch], batch_size: int, skip_last_batch: bool = False +) -> Iterator[pa.RecordBatch]: + """Regroup batches so every batch except the last has batch_size rows. + + The permutation reader only bounds batches by batch_size; a filtered + split read can yield short batches before the end of the stream. With + skip_last_batch, a final batch shorter than batch_size is dropped + without being built. + """ + if batch_size <= 0: + raise ValueError("batch_size must be greater than 0") + pending: list[pa.RecordBatch] = [] + pending_rows = 0 + for batch in batches: + if batch.num_rows == 0: + continue + if not pending and batch.num_rows == batch_size: + yield batch + continue + pending.append(batch) + pending_rows += batch.num_rows + if pending_rows < batch_size: + continue + table = pa.Table.from_batches(pending) + offset = 0 + while pending_rows - offset >= batch_size: + yield _single_batch(table.slice(offset, batch_size)) + offset += batch_size + rest = table.slice(offset) + pending = rest.to_batches() if rest.num_rows else [] + pending_rows = rest.num_rows + if pending_rows and not skip_last_batch: + yield _single_batch(pa.Table.from_batches(pending)) + + +def _single_batch(table: pa.Table) -> pa.RecordBatch: + batches = table.combine_chunks().to_batches() + if len(batches) != 1 or batches[0].num_rows != table.num_rows: + raise ValueError( + f"A batch of {table.num_rows} rows cannot be represented as a single " + "Arrow record batch (column data exceeds Arrow's size limits); " + "use a smaller batch_size" + ) + return batches[0] diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index a032226c8..cd6b19a20 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -1306,6 +1306,36 @@ def test_iter_skip_last_batch(some_permutation: Permutation): assert len(batch) == batch_size +def test_iter_keeps_rows_from_short_reader_batches(some_table: Table): + """A filtered split read can yield short batches before the end.""" + perm_tbl = ( + permutation_builder(some_table) + .split_hash(["id"], [1, 1], discard_weight=0) + .execute() + ) + permutation = Permutation.from_tables(some_table, perm_tbl, 0) + num_rows = permutation.num_rows + expected_ids = [ + row["id"] for row in permutation.__getitems__(list(range(num_rows))) + ] + batch_size = 37 + assert num_rows % batch_size != 0 + + batches = list(permutation.iter(batch_size, skip_last_batch=False)) + assert [len(batch) for batch in batches[:-1]] == [batch_size] * (len(batches) - 1) + assert [row["id"] for batch in batches for row in batch] == expected_ids + + num_full = num_rows // batch_size + full_batches = list(permutation.iter(batch_size, skip_last_batch=True)) + assert [len(batch) for batch in full_batches] == [batch_size] * num_full + assert [row["id"] for batch in full_batches for row in batch] == expected_ids[ + : num_full * batch_size + ] + + dunder_batches = list(permutation.with_batch_size(batch_size)) + assert [len(batch) for batch in dunder_batches] == [batch_size] * num_full + + def test_iter_different_batch_sizes(some_permutation: Permutation): """Test iteration with different batch sizes.""" @@ -2384,3 +2414,124 @@ def test_map_pickle_round_trip(some_permutation: Permutation, fn, batched): explicit = pickle.loads(pickle.dumps(some_permutation.with_format("arrow"))) with pytest.raises(ValueError, match="map cannot be combined"): explicit.map(fn, batched=batched) + + +def test_rebatch_regroups_short_and_empty_batches(): + """_rebatch fills batches from short, empty and oversized input batches.""" + from lancedb.permutation import _rebatch + + def make(start, n): + return pa.record_batch({"id": pa.array(range(start, start + n), pa.int64())}) + + sizes = [3, 0, 4, 10, 1, 2, 4, 0] + batches, start = [], 0 + for n in sizes: + batches.append(make(start, n)) + start += n + + out = list(_rebatch(iter(batches), 4)) + assert [b.num_rows for b in out] == [4, 4, 4, 4, 4, 4] + assert [v for b in out for v in b.column("id").to_pylist()] == list(range(24)) + assert all(b.schema == batches[0].schema for b in out) + + out = list(_rebatch(iter(batches[:3]), 4)) + assert [b.num_rows for b in out] == [4, 3] + + assert list(_rebatch(iter([make(0, 0)]), 4)) == [] + assert list(_rebatch(iter([]), 4)) == [] + + +def test_rebatch_rejects_non_positive_batch_size(): + """_rebatch raises before consuming any input when batch_size <= 0.""" + from lancedb.permutation import _rebatch + + consumed = [] + + def tracking(): + consumed.append(True) + yield pa.record_batch({"id": pa.array([0], pa.int64())}) + + for batch_size in (0, -1): + with pytest.raises(ValueError, match="batch_size must be greater than 0"): + next(_rebatch(tracking(), batch_size)) + assert consumed == [] + + +def test_iter_rejects_non_positive_batch_size(some_permutation: Permutation): + for batch_size in (0, -1): + with pytest.raises(ValueError, match="batch_size must be greater than 0"): + next(some_permutation.iter(batch_size)) + + +def test_single_batch_rejects_multi_chunk_combine(): + """_single_batch raises instead of dropping rows Arrow cannot fit in one batch.""" + from lancedb.permutation import _single_batch + + parts = [ + pa.record_batch({"id": pa.array([0], pa.int64())}), + pa.record_batch({"id": pa.array([1], pa.int64())}), + ] + + class Combined: + def to_batches(self): + return parts + + class Table: + num_rows = 2 + + def combine_chunks(self): + return Combined() + + with pytest.raises(ValueError, match="smaller batch_size"): + _single_batch(Table()) + + +def test_rebatch_skip_last_batch_does_not_build_the_tail(monkeypatch): + """A short final batch that will be skipped is never passed to _single_batch.""" + import lancedb.permutation as permutation + + built = [] + single_batch = permutation._single_batch + + def spy(table): + built.append(table.num_rows) + return single_batch(table) + + monkeypatch.setattr(permutation, "_single_batch", spy) + + def make(start, n): + return pa.record_batch({"id": pa.array(range(start, start + n), pa.int64())}) + + out = list(permutation._rebatch(iter([make(0, 1), make(1, 1)]), 3, True)) + assert out == [] + assert built == [] + + # Short batches before the end still combine; only the tail is dropped. + batches = [make(0, 1), make(1, 2), make(3, 1)] + out = list(permutation._rebatch(iter(batches), 3, True)) + assert [b.column("id").to_pylist() for b in out] == [[0, 1, 2]] + assert built == [3] + + built.clear() + out = list(permutation._rebatch(iter(batches), 3)) + assert [b.column("id").to_pylist() for b in out] == [[0, 1, 2], [3]] + assert built == [3, 1] + + +def test_iter_skip_last_batch_does_not_build_the_tail( + some_permutation: Permutation, monkeypatch +): + import lancedb.permutation as permutation + + built = [] + single_batch = permutation._single_batch + + def spy(table): + built.append(table.num_rows) + return single_batch(table) + + monkeypatch.setattr(permutation, "_single_batch", spy) + + assert list(some_permutation.iter(1000, skip_last_batch=True)) == [] + assert built == [] + assert len(list(some_permutation.iter(1000, skip_last_batch=False))) == 1