Fokko commented on code in PR #4505:
URL: https://github.com/apache/iceberg-python/pull/4505#discussion_r4735138008
##########
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:
Review Comment:
**Blocking:** `RecordBatch.slice(...).nbytes` counts the whole dictionary in
every slice, including a 0-row slice. When the dictionary alone is bigger than
the space left, this returns 0. With an empty buffer, the caller then takes the
`not buffer` branch and moves forward one row at a time, so every row becomes
its own bin.
This affects the streamed path the PR targets: Polars exports `Categorical`
as `dictionary<string_view>`, and `_ConvertViewTypes` only casts the dictionary
values, not the dictionary itself.
```python
import polars as pl
import pyarrow as pa
from pyiceberg.io.pyarrow import bin_pack_record_batches
cats = [f"category-value-{i:06d}" for i in range(100_000)]
df = pl.DataFrame({"c": pl.Series([cats[i % len(cats)] for i in
range(200_000)], dtype=pl.Categorical)})
batch = pa.RecordBatchReader.from_stream(df).read_next_batch()
print(batch.nbytes, batch.slice(0, 0).nbytes) # 4500000 3700000
bins = list(bin_pack_record_batches(pa.RecordBatchReader.from_stream(df),
1024 * 1024))
print(len(bins)) # 200000
```
End to end, `tbl.append(df)` on an unpartitioned table with a 1 MB target
commits 200,000 data files. Before this change it wrote 1 file, and
`pa.table(df)` produces 3 bins. Even when the dictionary fits within the
target, each bin pays for it again, so files shrink as the dictionary size
approaches the target.
Possible fixes:
- Count the fixed per-batch cost (`batch.slice(0, 0).nbytes`) only once per
batch, both here and in `buffer_bytes`.
- Or slice by average row size, like `bin_pack_arrow_table` does. That would
also remove the need for the binary search, and the result is only an
approximation anyway, since `nbytes` is uncompressed (#2998).
Either way, please add a regression test with a dictionary column.
##########
pyiceberg/io/pyarrow.py:
##########
@@ -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:
Review Comment:
Because of `remaining.num_rows == 1`, a single row that doesn't fit is added
to a non-empty buffer, so the bin goes over the target. For example, two
104-byte single-row batches with a 154-byte target become one 208-byte bin,
while the same two rows in one 2-row batch become two bins. Multi-row batches
give bins at or below the target, which the new tests check. The existing
`test_bin_pack_record_batches_microbatched` still asserts `>= bin_size` for all
bins except the last, and it only passes because of this condition.
Please pick one rule and state it in the docstring:
- Bins at or below the target: drop `remaining.num_rows == 1 or`.
- Bins at or above the target: split at the first row that reaches the
target. This is how the streaming code behaved before this change, and it
matches Java. `RollingFileWriter` checks `length() >= targetFileSizeInBytes`
every 1000 rows, so Java files reach or slightly exceed the target, except the
last file of each task.
##########
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:
Review Comment:
This test also passes on the code before this PR, because the old loop
already yielded once the buffer reached the target. It's still a useful guard,
but it doesn't test a regression.
##########
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.
Review Comment:
Nit: as suggested in #4499, this sentence could simply be removed rather
than reworded.
##########
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]:
Review Comment:
Nit: the size check isn't consistent between the new tests.
`test_bin_pack_record_batches_splits_oversized_batch` checks every bin, while
this test skips the last one.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]