diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index d0d6d08332..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 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. 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..3b1bca7c0d 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -3220,8 +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``. + 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. 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 @@ -3233,14 +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: - 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_rows = batch.num_rows - offset + space = target_file_size - buffer_bytes + 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.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: + 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.0 if buffer: yield buffer diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 92d533651c..6c8c518bff 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3162,9 +3162,62 @@ 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: + 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: + 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_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: