From 3c66bc952f558fd717485655c7968ac2071896d6 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Fri, 27 Nov 2026 19:21:16 +0000 Subject: [PATCH 1/2] Core: Split oversized record batches when streaming writes bin_pack_record_batches never split an incoming batch, so a streamed input that exports a single large batch (for example a Polars DataFrame through the PyCapsule interface) was written as one data file regardless of write.target-file-size-bytes. Slice a batch that would push the buffer past the target size so streamed writes honor the target file size like Table input does. --- mkdocs/docs/api.md | 2 +- pyiceberg/io/pyarrow.py | 62 +++++++++++++++++++++++++++++++++++----- tests/io/test_pyarrow.py | 38 ++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 8 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index d0d6d08332..25a3362d8e 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -418,7 +418,7 @@ import polars as pl tbl.append(pl.DataFrame({"city": ["Groningen"], "lat": [53.21917], "long": [6.56667]})) ``` -Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. A streamed batch is never split, so a dataframe that exports one large batch is written as one file. +Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. A streamed batch that is larger than the target file size is split across files, so a dataframe that exports one large batch is not written as one oversized file. The stream's schema must match the table's, including nullability. Polars exports every column as optional, so a Polars dataframe cannot be written to a table with required fields. diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 8aff1f7e73..bebded1118 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3210,6 +3210,17 @@ def bin_pack_arrow_table(tbl: pa.Table, target_file_size: int) -> Iterator[list[ return bin_packed_record_batches +def _rows_fitting(batch: pa.RecordBatch, max_bytes: int) -> int: + lo, hi = 0, batch.num_rows + while lo < hi: + mid = (lo + hi + 1) // 2 + if batch.slice(0, mid).nbytes <= max_bytes: + lo = mid + else: + hi = mid - 1 + return lo + + def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: int) -> Iterator[list[pa.RecordBatch]]: """Microbatch a single-pass stream of RecordBatches into target-sized groups. @@ -3221,7 +3232,12 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: Each yielded list of batches is intended to be written as a single Parquet data file. Because this is single-pass FIFO accumulation (no lookback), the - last bin may be smaller than ``target_file_size``. + last bin may be smaller than ``target_file_size``. A batch that would push + the buffer past ``target_file_size`` is sliced with + ``RecordBatch.slice`` (zero copy), so a single large batch is split across + bins instead of forcing one oversized file. A batch that cannot be sliced + to fit, such as a single row larger than ``target_file_size``, is kept + whole. Note: ``target_file_size`` is measured in **uncompressed in-memory** Arrow @@ -3235,12 +3251,44 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: buffer: list[pa.RecordBatch] = [] buffer_bytes = 0 for batch in batches: - buffer.append(batch) - buffer_bytes += batch.nbytes - if buffer_bytes >= target_file_size: - yield buffer - buffer = [] - buffer_bytes = 0 + if batch.num_rows == 0: + buffer.append(batch) + continue + offset = 0 + while offset < batch.num_rows: + remaining = batch.slice(offset) + space = target_file_size - buffer_bytes + if remaining.nbytes <= space: + buffer.append(remaining) + buffer_bytes += remaining.nbytes + offset = batch.num_rows + if buffer_bytes >= target_file_size: + yield buffer + buffer = [] + buffer_bytes = 0 + else: + fit = _rows_fitting(remaining, space) + if fit > 0: + piece = remaining.slice(0, fit) + buffer.append(piece) + buffer_bytes += piece.nbytes + offset += fit + yield buffer + buffer = [] + buffer_bytes = 0 + elif remaining.num_rows == 1 or not buffer: + piece = remaining.slice(0, 1) + buffer.append(piece) + buffer_bytes += piece.nbytes + offset += 1 + if buffer_bytes >= target_file_size: + yield buffer + buffer = [] + buffer_bytes = 0 + else: + yield buffer + buffer = [] + buffer_bytes = 0 if buffer: yield buffer diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 92d533651c..b7f8601c16 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3167,6 +3167,44 @@ def test_bin_pack_record_batches_microbatched(arrow_table_with_null: pa.Table) - assert sum(b.nbytes for b in bin_) >= bin_size +def test_bin_pack_record_batches_splits_oversized_batch() -> None: + table = pa.table({"x": list(range(10_000))}) + batch = table.to_batches()[0] + target = table.nbytes // 4 + bins = list(bin_pack_record_batches(iter([batch]), target_file_size=target)) + assert len(bins) == 4 + for bin_ in bins: + assert sum(b.nbytes for b in bin_) <= target + assert pa.Table.from_batches([b for bin_ in bins for b in bin_]).equals(table) + + +def test_bin_pack_record_batches_splits_batch_after_partial_buffer() -> None: + small = pa.table({"x": list(range(10))}).to_batches()[0] + table = pa.table({"x": list(range(10_000))}) + bins = list(bin_pack_record_batches(iter([small, table.to_batches()[0]]), target_file_size=table.nbytes // 4)) + assert len(bins) > 1 + assert sum(b.num_rows for bin_ in bins for b in bin_) == table.num_rows + small.num_rows + for bin_ in bins[:-1]: + assert sum(b.nbytes for b in bin_) <= table.nbytes // 4 + + +def test_bin_pack_record_batches_exact_target_flushes_without_reading_ahead() -> None: + table = pa.table({"x": list(range(100))}) + single_row = pa.table({"x": [100]}).to_batches()[0] + consumed: list[int] = [] + + def tracking_iter() -> Iterator[pa.RecordBatch]: + for i, batch in enumerate([table.to_batches()[0], single_row]): + consumed.append(i) + yield batch + + bins_iter = bin_pack_record_batches(tracking_iter(), target_file_size=table.nbytes) + first_bin = next(bins_iter) + assert sum(b.nbytes for b in first_bin) == table.nbytes + assert consumed == [0] + assert [sum(b.num_rows for b in bin_) for bin_ in bins_iter] == [1] + + def test_bin_pack_record_batches_empty() -> None: assert list(bin_pack_record_batches(iter([]), target_file_size=1024)) == [] From 5d745f70ed0d4a8e26db8d2b45b1809e7bf1bc1d Mon Sep 17 00:00:00 2001 From: TEJA P C <39472754+PCTEJA@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:12:40 -0600 Subject: [PATCH 2/2] Core: Size streamed bins by average row size Sizing slices by slice(...).nbytes counts a batch's dictionary in every slice, so a dictionary-encoded batch whose dictionary exceeds the target degenerated to one row per bin. Slice by the batch's average row size instead, like bin_pack_arrow_table, and account bins in estimated bytes. Bins are now kept at or below the target for every batch shape; the previous num_rows == 1 exception let single-row batches push a bin over the target. A single row larger than the target is still kept whole. --- mkdocs/docs/api.md | 2 +- pyiceberg/io/pyarrow.py | 79 ++++++++++++++++++---------------------- tests/io/test_pyarrow.py | 23 ++++++++++-- 3 files changed, 56 insertions(+), 48 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index 25a3362d8e..d3bb30365e 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -418,7 +418,7 @@ import polars as pl tbl.append(pl.DataFrame({"city": ["Groningen"], "lat": [53.21917], "long": [6.56667]})) ``` -Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. A streamed batch that is larger than the target file size is split across files, so a dataframe that exports one large batch is not written as one oversized file. +Such an object is streamed into an unpartitioned table, and read into memory as a `pa.Table` for a partitioned one. The stream's schema must match the table's, including nullability. Polars exports every column as optional, so a Polars dataframe cannot be written to a table with required fields. diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index bebded1118..3b1bca7c0d 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3210,17 +3210,6 @@ def bin_pack_arrow_table(tbl: pa.Table, target_file_size: int) -> Iterator[list[ return bin_packed_record_batches -def _rows_fitting(batch: pa.RecordBatch, max_bytes: int) -> int: - lo, hi = 0, batch.num_rows - while lo < hi: - mid = (lo + hi + 1) // 2 - if batch.slice(0, mid).nbytes <= max_bytes: - lo = mid - else: - hi = mid - 1 - return lo - - def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: int) -> Iterator[list[pa.RecordBatch]]: """Microbatch a single-pass stream of RecordBatches into target-sized groups. @@ -3231,13 +3220,20 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: the caller cannot afford to materialise the full dataset. Each yielded list of batches is intended to be written as a single Parquet - data file. Because this is single-pass FIFO accumulation (no lookback), the - last bin may be smaller than ``target_file_size``. A batch that would push - the buffer past ``target_file_size`` is sliced with + data file. Bins are kept at or below ``target_file_size``: a batch that + would push the buffer past the target is sliced with ``RecordBatch.slice`` (zero copy), so a single large batch is split across - bins instead of forcing one oversized file. A batch that cannot be sliced - to fit, such as a single row larger than ``target_file_size``, is kept - whole. + bins instead of forcing one oversized file. The exception is a single row + larger than ``target_file_size``, which is kept whole in its own bin. + Because this is single-pass FIFO accumulation (no lookback), the last bin + may be smaller than ``target_file_size``. + + Rows are sliced by the batch's average row size, as in + :func:`bin_pack_arrow_table`, and bins are accounted in those estimated + bytes. Sizing slices by ``RecordBatch.slice(...).nbytes`` instead would + count fixed per-batch buffers, such as a dictionary, in every slice, which + degenerates to one row per bin when the dictionary alone exceeds the + target. Note: ``target_file_size`` is measured in **uncompressed in-memory** Arrow @@ -3249,46 +3245,43 @@ def bin_pack_record_batches(batches: Iterable[pa.RecordBatch], target_file_size: ``ParquetWriter`` with ``OutputStream.tell()`` (#2998). """ buffer: list[pa.RecordBatch] = [] - buffer_bytes = 0 + buffer_bytes = 0.0 for batch in batches: if batch.num_rows == 0: buffer.append(batch) continue offset = 0 while offset < batch.num_rows: - remaining = batch.slice(offset) + remaining_rows = batch.num_rows - offset space = target_file_size - buffer_bytes - if remaining.nbytes <= space: - buffer.append(remaining) - buffer_bytes += remaining.nbytes + fit = remaining_rows if batch.nbytes == 0 else int(space * batch.num_rows / batch.nbytes) + if fit >= remaining_rows: + buffer.append(batch.slice(offset)) + buffer_bytes += batch.nbytes * remaining_rows / batch.num_rows offset = batch.num_rows if buffer_bytes >= target_file_size: yield buffer buffer = [] - buffer_bytes = 0 + buffer_bytes = 0.0 + elif fit > 0: + buffer.append(batch.slice(offset, fit)) + buffer_bytes += batch.nbytes * fit / batch.num_rows + offset += fit + yield buffer + buffer = [] + buffer_bytes = 0.0 + elif buffer: + yield buffer + buffer = [] + buffer_bytes = 0.0 else: - fit = _rows_fitting(remaining, space) - if fit > 0: - piece = remaining.slice(0, fit) - buffer.append(piece) - buffer_bytes += piece.nbytes - offset += fit - yield buffer - buffer = [] - buffer_bytes = 0 - elif remaining.num_rows == 1 or not buffer: - piece = remaining.slice(0, 1) - buffer.append(piece) - buffer_bytes += piece.nbytes - offset += 1 - if buffer_bytes >= target_file_size: - yield buffer - buffer = [] - buffer_bytes = 0 - else: + buffer.append(batch.slice(offset, 1)) + buffer_bytes += batch.nbytes / batch.num_rows + offset += 1 + if buffer_bytes >= target_file_size: yield buffer buffer = [] - buffer_bytes = 0 + buffer_bytes = 0.0 if buffer: yield buffer diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index b7f8601c16..6c8c518bff 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3162,9 +3162,9 @@ def test_bin_pack_record_batches_microbatched(arrow_table_with_null: pa.Table) - bins = list(bin_pack_record_batches(iter(batches), target_file_size=bin_size)) assert len(bins) > 1 assert sum(b.num_rows for bin_ in bins for b in bin_) == arrow_table_with_null.num_rows * 5 - # All but the last bin should have crossed the size threshold. - for bin_ in bins[:-1]: - assert sum(b.nbytes for b in bin_) >= bin_size + # Bins are kept at or below the target size. + for bin_ in bins: + assert sum(b.nbytes for b in bin_) <= bin_size def test_bin_pack_record_batches_splits_oversized_batch() -> None: @@ -3184,7 +3184,7 @@ def test_bin_pack_record_batches_splits_batch_after_partial_buffer() -> None: bins = list(bin_pack_record_batches(iter([small, table.to_batches()[0]]), target_file_size=table.nbytes // 4)) assert len(bins) > 1 assert sum(b.num_rows for bin_ in bins for b in bin_) == table.num_rows + small.num_rows - for bin_ in bins[:-1]: + for bin_ in bins: assert sum(b.nbytes for b in bin_) <= table.nbytes // 4 @@ -3205,6 +3205,21 @@ def tracking_iter() -> Iterator[pa.RecordBatch]: assert [sum(b.num_rows for b in bin_) for bin_ in bins_iter] == [1] +def test_bin_pack_record_batches_dictionary_column() -> None: + # The dictionary alone is larger than the target: sizing slices by + # slice(...).nbytes would count it in every slice and emit one row per bin. + dictionary = pa.array([f"category-value-{i:06d}" for i in range(10_000)]) + indices = pa.array([i % 10_000 for i in range(20_000)], type=pa.int32()) + batch = pa.record_batch([pa.DictionaryArray.from_arrays(indices, dictionary)], names=["c"]) + assert batch.slice(0, 0).nbytes > 64 * 1024 + + bins = list(bin_pack_record_batches(iter([batch]), target_file_size=64 * 1024)) + + assert len(bins) <= 10 + assert sum(b.num_rows for bin_ in bins for b in bin_) == batch.num_rows + assert pa.Table.from_batches([b for bin_ in bins for b in bin_]).equals(pa.Table.from_batches([batch])) + + def test_bin_pack_record_batches_empty() -> None: assert list(bin_pack_record_batches(iter([]), target_file_size=1024)) == []