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)) == []