This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11997-435038ec58a2904cb1c3f74c406ef2ee89b31202 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 8befa3cd899afea17b1969f0f4fd4491e3f81439 Author: Adrian Garcia Badaracco <[email protected]> AuthorDate: Wed Nov 25 05:48:19 2026 +0000 perf(parquet): count fitting values before scanning def levels (#11997) # Which issue does this PR close? - Related to #11994 / #11996: this is a follow-up perf tweak, not the fix itself. # Rationale for this change `ByteBudgetChunker::byte_budget_sub_batch` calls `chunk_def.value_count(...)` before it asks the encoder whether the chunk's values fit the page budget. For nullable columns (`Materialized` def levels) that call is an O(chunk_size) scan, and it runs on every chunk of every nullable byte-array column, even chunks far below the page limit. # What changes are included in this PR? The chunker now asks the encoder first, about the next `chunk_size` values. That window always contains the chunk's values as a prefix, because a chunk holds at most `chunk_size` values. `count_values_within_byte_budget[_gather]` counts how many *leading* values fit, so its answer for the window also answers for the chunk: - **The whole window fits:** the chunk fits too. Return `None` without scanning def levels. This is the common case, and it uses the existing stage-1 bounds. Those cost O(1) for view arrays and one ordered pass over the indices for offset arrays. - **The count stops at `k`, the first value that overflows:** only now run `value_count`. If `k >= vals_in_chunk` the overflow is past this chunk, so the chunk fits. Otherwise `k` is the same answer the current code computes. The lookahead is used only on the gather path (`value_indices`), which the arrow writer always uses, because every gather index names a real value. A contiguous `values` slice from a raw `ColumnWriter` caller may be padded with placeholder `ByteArray`s past the values its levels reference, and those can't be sized. That path keeps counting the chunk's values first, as on `main`. There are no new trait methods. An earlier revision of this PR added a byte-array-only `values_fit_within_byte_budget_gather` hook to `ColumnValueEncoder`. This version reuses the existing count instead, and benchmarked the same. # Are these changes tested? New unit tests in `byte_budget_chunker` call `pick_sub_batch` directly, through both the contiguous and the gather entry points: - a small chunk is not split; - an overflow past the chunk, inside the lookahead window, does not split it; - an overflow inside the chunk splits it, with the same `Levels` window as on `main`; - an all-null chunk is not split; - a contiguous slice padded with placeholder values past the chunk is never read (`test_write_statistics_not_arrow` in `tests/geospatial.rs` caught this in CI). They pass on `main` as well, so they pin the behaviour to `main`'s. The second test fails if the `k >= vals_in_chunk` check is removed. The existing writer and page-size tests also pass. Benchmarks: `arrow_writer`, `/default` props, on a quiet GCE c3-standard-8. Each variant ran twice, interleaved, and the numbers below are the two runs: | case | main | this PR | | --- | --- | --- | | byte_array_sparse_99pct_null | 10.6 / 10.7 ms | 9.3 / 9.3 ms (**−13%**) | | string_and_binary_view | 52.9 / 52.6 ms | 51.7 / 51.5 ms | | string | 150.9 / 152.9 ms | 149.6 / 149.5 ms | | string_dictionary | 74.4 / 74.4 ms | 73.8 / 73.6 ms | | string_ree_95pct_null | 31.3 / 31.2 ms | 31.1 / 30.9 ms | | string_non_null | 176.4 / 179.7 ms | 175.7 / 176.0 ms | | large_string_non_null | 58.1 / 58.0 ms | 58.1 / 57.9 ms | | list_string_ree | 137.7 / 137.6 ms | 138.9 / 138.9 ms | Every case except the sparse one is within noise. `perf` on `byte_array_sparse_99pct_null`: `byte_budget_sub_batch` (with the inlined def-level scan) drops from 10.2% to 0.6% of samples, and `count_values_within_byte_budget_gather` rises from 0.9% to 1.6%. # Are there any user-facing changes? No. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]> --- parquet/src/arrow/arrow_writer/byte_array.rs | 50 ++-- parquet/src/arrow/arrow_writer/mod.rs | 307 +++++++++++++++++++++++ parquet/src/column/writer/byte_budget_chunker.rs | 218 ++++++++++++---- parquet/src/column/writer/encoder.rs | 26 +- parquet/src/column/writer/mod.rs | 10 +- 5 files changed, 548 insertions(+), 63 deletions(-) diff --git a/parquet/src/arrow/arrow_writer/byte_array.rs b/parquet/src/arrow/arrow_writer/byte_array.rs index e9656c38f0..e0004c9673 100644 --- a/parquet/src/arrow/arrow_writer/byte_array.rs +++ b/parquet/src/arrow/arrow_writer/byte_array.rs @@ -831,6 +831,24 @@ impl ColumnValueEncoder for ByteArrayEncoder { downcast_op!(values.data_type(), values, encode, indices, self) } + fn max_value_bytes(values: &Self::Values) -> Option<usize> { + // An offset array has no bound tighter than its whole payload unless + // the code reads every offset. + let buffers = match values.data_type() { + DataType::Utf8View => { + let array = values.as_any().downcast_ref::<StringViewArray>().unwrap(); + array.data_buffers() + } + DataType::BinaryView => { + let array = values.as_any().downcast_ref::<BinaryViewArray>().unwrap(); + array.data_buffers() + } + _ => return None, + }; + // Each plain-encoded value carries a 4-byte length prefix. + Some(max_view_value_len(buffers) + std::mem::size_of::<u32>()) + } + fn count_values_within_byte_budget_gather( values: &Self::Values, indices: &[usize], @@ -840,10 +858,11 @@ impl ColumnValueEncoder for ByteArrayEncoder { // is the relevant method. // // Two-stage walk for the simple offset-buffer byte array types: - // 1. If indices are contiguous, compute the total payload in - // O(1) via a single subtraction on the offsets buffer. - // When the total fits the budget — the overwhelmingly - // common "small values" case — return immediately. + // 1. If indices are strictly increasing, bound the total + // payload by a single subtraction on the offsets buffer. + // The order check is one sequential pass over `indices`. + // When the bound fits the budget (the common small-value + // case), return immediately. // 2. Otherwise, walk per-value byte sizes from the offsets // buffer (still cheap, no slice/UTF-8 construction) and // exit at the first value that pushes the cumulative sum @@ -1141,8 +1160,9 @@ fn count_within_budget_views( /// `byte_budget` (boundary value included), for offset-buffer byte arrays /// (`Utf8`/`LargeUtf8`/`Binary`/`LargeBinary`). /// -/// `indices` are assumed sorted ascending — they always are here, since -/// they come from `non_null_indices`, which is built in array order. +/// `indices` come from `non_null_indices`. They are strictly increasing for +/// most arrays, but a `ListView` can reference its child values in any +/// order and more than once. fn count_within_budget_offsets<T: ByteArrayType>( values: &GenericByteArray<T>, indices: &[usize], @@ -1158,14 +1178,16 @@ fn count_within_budget_offsets<T: ByteArrayType>( // Each plain-encoded value carries a 4-byte length prefix on the page. let prefix_overhead = std::mem::size_of::<u32>(); - // Stage 1: O(1) span upper bound. The span `offsets[last+1] - - // offsets[first]` covers every array position in `[first, last]`, a - // superset of `indices` — and the skipped positions in a nullable - // column are nulls with zero offset delta, so the span still equals the - // exact payload. If it fits the budget, every value fits. Covers the - // common small-value case for both non-null and (sparse) nullable - // columns. - if last >= first { + // Stage 1: span upper bound. The span `offsets[last+1] - offsets[first]` + // covers every array position in `[first, last]`. If it fits the budget, + // every value fits. Covers the common small-value case for both non-null + // and (sparse) nullable columns. + // + // The span bounds the payload only when `indices` are strictly + // increasing. A `ListView` gather can repeat an index or jump backwards, + // so the span can miss values between the jumps. The order check is one + // sequential compare per index. Stage 2 reads two offsets per index. + if indices.windows(2).all(|w| w[0] < w[1]) { let payload = (offsets[last + 1] - offsets[first]).as_usize(); if payload + n * prefix_overhead <= byte_budget { return n; diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs index 928a6fad41..5be76f6220 100644 --- a/parquet/src/arrow/arrow_writer/mod.rs +++ b/parquet/src/arrow/arrow_writer/mod.rs @@ -5605,6 +5605,313 @@ mod tests { ); } + /// Writes singleton `ListView<Utf8>` rows that reference the child values + /// at `offsets` (`None` for a null row), and returns the largest data + /// page body. Child 0 is one byte. Children 1 to 8 are + /// [`LIST_VIEW_LARGE`] bytes, against a page limit of the same size. + fn max_list_view_page_bytes(offsets: &[Option<i32>], write_batch_size: usize) -> usize { + let mut strings = vec!["s".to_owned()]; + strings.extend((1..=8).map(|i| char::from(b'a' + i).to_string().repeat(LIST_VIEW_LARGE))); + let children = Arc::new(StringArray::from(strings)); + let child_field = Arc::new(Field::new_list_field(ArrowDataType::Utf8, false)); + let num_rows = offsets.len(); + let lists = ListViewArray::new( + child_field.clone(), + offsets.iter().map(|o| o.unwrap_or(0)).collect(), + offsets.iter().map(|o| i32::from(o.is_some())).collect(), + children, + Some(offsets.iter().map(Option::is_some).collect()), + ); + let schema = Arc::new(Schema::new(vec![Field::new( + "col", + ArrowDataType::ListView(child_field), + true, + )])); + let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(lists)]).unwrap(); + + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_encoding(Encoding::PLAIN) + .set_compression(crate::basic::Compression::UNCOMPRESSED) + .set_data_page_size_limit(LIST_VIEW_LARGE) + .set_write_batch_size(write_batch_size) + .build(); + let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap(); + writer.write(&batch).unwrap(); + let data = Bytes::from(writer.into_inner().unwrap()); + + let mut metadata = ParquetMetaDataReader::new(); + metadata.try_parse(&data).unwrap(); + let metadata = metadata.finish().unwrap(); + let col_meta = metadata.row_group(0).column(0); + let mut reader = + SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap(); + let mut max_page_bytes = 0; + while let Some(page) = reader.get_next_page().unwrap() { + assert!(page.is_data_page()); + max_page_bytes = max_page_bytes.max(page.buffer().len()); + } + max_page_bytes + } + + const LIST_VIEW_LARGE: usize = 4096; + + /// The byte-budget chunker sizes each mini-batch to the values up to and + /// including the first that overflows the budget: the small value and + /// one large value. On a nullable column a mini-batch may hold twice + /// that (`SubBatchStrategy::Levels::max_values`). So a page holds at + /// most four values, plus levels. Without the bound, all eight large + /// values land in one page. + const LIST_VIEW_MAX_PAGE: usize = 4 * (LIST_VIEW_LARGE + 4) + 64; + + #[test] + fn test_arrow_writer_list_view_backward_gather_splits_pages() { + // The gather `[0, 1, ..., 8, 0]` jumps back to the small value 0. The + // offsets span from the first index to the last covers only value 0, + // but the eight large values in between must still split into pages. + let offsets: Vec<_> = (0..=8).chain([0]).map(Some).collect(); + let max = max_list_view_page_bytes(&offsets, 1024); + assert!(max <= LIST_VIEW_MAX_PAGE, "page of {max} bytes"); + } + + #[test] + fn test_arrow_writer_list_view_backward_gather_after_chunk_splits_pages() { + // The first 16-row chunk references children 0 to 8 in order, then + // holds nulls. The next chunk references child 0 again. A gather + // that reaches past the first chunk jumps back to value 0. + let offsets: Vec<_> = (0..=8) + .map(Some) + .chain([None; 7]) + .chain([Some(0); 16]) + .collect(); + let max = max_list_view_page_bytes(&offsets, 16); + assert!(max <= LIST_VIEW_MAX_PAGE, "page of {max} bytes"); + } + + /// Size and placement of the values of a nullable string column, for + /// [`assert_byte_array_page_layout`]. + struct SparseStrings { + num_rows: usize, + /// Returns the length of the value at a row, or `None` for a null. + value_len: fn(usize) -> Option<usize>, + } + + impl SparseStrings { + fn values(&self) -> Vec<Option<String>> { + (0..self.num_rows) + .map(|row| { + let len = (self.value_len)(row)?; + // Distinct values, so a dictionary does not shrink them. + Some(format!("{row:08}").repeat(len.div_ceil(8))[..len].to_owned()) + }) + .collect() + } + } + + /// Returns `true` for about one row in `one_in`, without a regular + /// stride. + fn scattered(row: usize, one_in: usize) -> bool { + (row.wrapping_mul(2654435761) >> 7).is_multiple_of(one_in) + } + + /// `(num_values, body bytes)` of each page of the only column of `array` + /// written with `props`, dictionary pages included. Checks that the + /// file reads back as `array`. + fn page_layout(array: ArrayRef, props: WriterProperties) -> Vec<(u32, usize)> { + let batch = RecordBatch::try_from_iter([("col", array)]).unwrap(); + let mut writer = ArrowWriter::try_new(Vec::new(), batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + let data = Bytes::from(writer.into_inner().unwrap()); + + let reader = ParquetRecordBatchReader::try_new(data.clone(), batch.num_rows()).unwrap(); + let read = reader.collect::<ArrowResult<Vec<_>>>().unwrap(); + assert_eq!(read, std::slice::from_ref(&batch)); + + let mut metadata = ParquetMetaDataReader::new(); + metadata.try_parse(&data).unwrap(); + let metadata = metadata.finish().unwrap(); + let col_meta = metadata.row_group(0).column(0); + let mut pages = + SerializedPageReader::new(Arc::new(data.clone()), col_meta, batch.num_rows(), None) + .unwrap(); + let mut layout = vec![]; + while let Some(page) = pages.get_next_page().unwrap() { + layout.push((page.num_values(), page.buffer().len())); + } + layout + } + + const LAYOUT_PAGE_LIMIT: usize = 4096; + + /// Writes `strings` in every string representation and checks what the + /// byte-budget chunker must guarantee, whatever way it sizes the values + /// of each representation: + /// + /// * No page body exceeds `max_page_bytes`. + /// * The page layout does not depend on the representation. A sizing + /// shortcut that exists for one representation may skip work, but it + /// must reach the decision that the exact sizes give. + fn assert_byte_array_page_layout(strings: &SparseStrings, max_page_bytes: usize) { + let values = strings.values(); + let data_bytes: usize = values.iter().flatten().map(String::len).sum(); + let max_len = values.iter().flatten().map(String::len).max().unwrap(); + let view_blocks = |block_size: usize| -> ArrayRef { + let mut builder = + StringViewBuilder::new().with_fixed_block_size(block_size.try_into().unwrap()); + values + .iter() + .for_each(|v| builder.append_option(v.as_deref())); + Arc::new(builder.finish()) + }; + let arrays: [(&str, ArrayRef); 5] = [ + ("Utf8", Arc::new(StringArray::from(values.clone()))), + ( + "LargeUtf8", + Arc::new(LargeStringArray::from(values.clone())), + ), + // One data buffer holds every long value, so its length says + // little about the length of one value. + ("Utf8View, one buffer", view_blocks(data_bytes.max(1))), + ("Utf8View, small buffers", view_blocks(2048)), + // No data buffer is longer than the longest value, so the buffer + // lengths bound one value closely. + ("Utf8View, tight buffers", view_blocks(max_len)), + ]; + + for write_batch_size in [64, 1024] { + for dictionary in [false, true] { + let props = || { + WriterProperties::builder() + .set_dictionary_enabled(dictionary) + .set_compression(crate::basic::Compression::UNCOMPRESSED) + .set_data_page_size_limit(LAYOUT_PAGE_LIMIT) + .set_dictionary_page_size_limit(LAYOUT_PAGE_LIMIT) + .set_write_batch_size(write_batch_size) + .build() + }; + let case = format!("write_batch_size={write_batch_size} dictionary={dictionary}"); + let expected = page_layout(arrays[0].1.clone(), props()); + let max = expected.iter().map(|(_, bytes)| *bytes).max().unwrap(); + assert!(max <= max_page_bytes, "{case}: page of {max} bytes"); + for (name, array) in &arrays[1..] { + let layout = page_layout(array.clone(), props()); + assert_eq!(layout, expected, "{case}: {name} differs from Utf8"); + } + } + } + } + + /// A mini-batch may run up to twice the values that fit the page limit + /// (`SubBatchStrategy::Levels::max_values`), and the page that it joins + /// may already be almost full. Without the byte budget, a mini-batch of + /// 1024 levels holds over 100 KiB of the 1 KiB values below. + const LAYOUT_MAX_PAGE: usize = 4 * LAYOUT_PAGE_LIMIT; + + #[test] + fn test_arrow_writer_sparse_small_values_page_layout() { + // About ten values per mini-batch of 1024 levels. Nothing here + // comes near the page byte limit. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 64 * 1024, + value_len: |row| scattered(row, 100).then_some(8), + }, + LAYOUT_PAGE_LIMIT + 1024, + ); + } + + #[test] + fn test_arrow_writer_sparse_large_values_page_layout() { + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 8 * 1024, + value_len: |row| scattered(row, 8).then_some(1024), + }, + LAYOUT_MAX_PAGE, + ); + } + + #[test] + fn test_arrow_writer_sparse_mixed_values_page_layout() { + // Mostly small values. A mini-batch stays in budget until it + // reaches one of the large values, which are far apart. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 16 * 1024, + value_len: |row| { + scattered(row, 8).then_some(if scattered(row, 8 * 64) { 1024 } else { 8 }) + }, + }, + LAYOUT_MAX_PAGE, + ); + } + + #[test] + fn test_arrow_writer_clustered_large_values_page_layout() { + // Runs of 200 large values between long runs of nulls. The level to + // value ratio of a chunk says nothing about where its values are. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 8 * 1024, + value_len: |row| (row % 2000 >= 1800).then_some(1024), + }, + LAYOUT_MAX_PAGE, + ); + } + + #[test] + fn test_arrow_writer_large_values_after_small_chunks_page_layout() { + // Small values for the first chunks, then only large ones. The + // large values lie within `write_batch_size` values of the small + // chunks, although they belong to later chunks. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 8 * 1024, + value_len: |row| scattered(row, 16).then_some(if row < 2048 { 8 } else { 1024 }), + }, + LAYOUT_MAX_PAGE, + ); + } + + #[test] + fn test_arrow_writer_dense_values_near_page_limit_page_layout() { + // The payload of a mini-batch of 64 values fits the page limit. With + // the 4-byte length prefixes, 63 values already exceed it. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 4 * 1024, + value_len: |_| Some(62), + }, + LAYOUT_MAX_PAGE, + ); + } + + #[test] + fn test_arrow_writer_dense_values_over_page_limit_page_layout() { + // A mini-batch of 64 values holds between one and two page limits. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 4 * 1024, + value_len: |_| Some(100), + }, + LAYOUT_MAX_PAGE, + ); + } + + #[test] + fn test_arrow_writer_dense_mixed_values_page_layout() { + // Short and long values alternate. With tight buffers, a view array + // holds each short value in a data buffer of its own, so the buffers + // differ in length. + assert_byte_array_page_layout( + &SparseStrings { + num_rows: 4 * 1024, + value_len: |row| Some(if row % 2 == 1 { 200 } else { 20 }), + }, + LAYOUT_MAX_PAGE, + ); + } + struct WriteBatchesShape { num_batches: usize, rows_per_batch: usize, diff --git a/parquet/src/column/writer/byte_budget_chunker.rs b/parquet/src/column/writer/byte_budget_chunker.rs index b8a3317ce9..a0f1579964 100644 --- a/parquet/src/column/writer/byte_budget_chunker.rs +++ b/parquet/src/column/writer/byte_budget_chunker.rs @@ -88,6 +88,10 @@ pub(crate) struct ByteBudgetChunker { /// when one `base_batch_size` mini-batch of this fixed-width type cannot /// overshoot `dict_page_byte_limit` by more than one mini-batch's worth. static_dict_always_fits: bool, + /// Upper bound on the page bytes of any one value of this write call, + /// from [`ColumnValueEncoder::max_value_bytes`]. `None` if the encoder + /// has no bound, or if the call does not gather values by index. + max_value_bytes: Option<usize>, } impl ByteBudgetChunker { @@ -96,6 +100,7 @@ impl ByteBudgetChunker { descr: &ColumnDescriptor, column_props: &ResolvedColumnProperties, base_batch_size: usize, + max_value_bytes: Option<usize>, ) -> Self { let page_byte_limit = column_props.data_page_size_limit; let dict_page_byte_limit = column_props.dictionary_page_size_limit; @@ -118,6 +123,7 @@ impl ByteBudgetChunker { static_always_fits: static_fits(page_byte_limit), dict_page_byte_limit, static_dict_always_fits: static_fits(dict_page_byte_limit), + max_value_bytes, } } @@ -206,55 +212,183 @@ impl ByteBudgetChunker { budget: usize, value_exact: bool, ) -> Option<SubBatchStrategy> { - // How many of this chunk's levels carry an actual value. For a - // non-nullable, unrepeated column every level is a value, so - // `value_count` is O(1) (`Absent`/`Uniform` def levels); only - // nullable or nested columns pay the O(chunk_size) def-level scan. - let vals_in_chunk = chunk_def.value_count(chunk_size, self.max_def_level); - if vals_in_chunk == 0 { - return None; - } - // Ask the encoder how many of the next values fit in one page byte - // budget. Dispatch on whether the caller supplied gather indices; - // this mirrors how `write_mini_batch` picks `write_gather` vs + // Ask the encoder how many of the chunk's values fit in one page byte + // budget. Dispatch on whether the caller supplied gather indices. + // This mirrors how `write_mini_batch` picks `write_gather` or // `write`. - let fit = match value_indices { + let (fit, vals_in_chunk) = match value_indices { Some(idx) => { - let end = (values_offset + vals_in_chunk).min(idx.len()); + // Counting the chunk's values scans its def levels on a + // nullable column, and most chunks fit outright. So first + // try to prove the fit without the count. The next + // `chunk_size` values contain the chunk's values, so if + // that window fits, the chunk fits too. + // + // The window overlaps the windows of the following chunks, + // almost entirely so on a sparse column. The proof must + // therefore not read the window, or a sparse column pays + // for `chunk_size` values on every chunk of a few values. + // It uses the length of the window and a bound on one value. + // + // Only gather indices allow this lookahead, because each one + // names a real value of a later chunk. A contiguous `values` + // slice may hold placeholders past the values its levels + // reference. Raw `ColumnWriter` callers pad them, and they + // cannot be sized. + let end = values_offset.saturating_add(chunk_size).min(idx.len()); let start = values_offset.min(end); - E::count_values_within_byte_budget_gather(values, &idx[start..end], budget) + let window = &idx[start..end]; + let window_fits = + |max_value_bytes: usize| window.len().saturating_mul(max_value_bytes) <= budget; + if window.is_empty() || self.max_value_bytes.is_some_and(window_fits) { + return None; + } + let vals_in_chunk = chunk_def.value_count(chunk_size, self.max_def_level); + let chunk_idx = &window[..vals_in_chunk.min(window.len())]; + if chunk_idx.is_empty() { + return None; + } + let fit = E::count_values_within_byte_budget_gather(values, chunk_idx, budget)?; + (fit, vals_in_chunk) } None => { - E::count_values_within_byte_budget(values, values_offset, vals_in_chunk, budget) + // For a non-nullable, unrepeated column `value_count` is O(1) + // (`Absent` or `Uniform` def levels). Nullable or nested + // columns pay the def-level scan. + let vals_in_chunk = chunk_def.value_count(chunk_size, self.max_def_level); + if vals_in_chunk == 0 { + return None; + } + let fit = E::count_values_within_byte_budget( + values, + values_offset, + vals_in_chunk, + budget, + )?; + (fit, vals_in_chunk) } }; - match fit { - // The encoder cannot size these values; write the chunk whole. - None => None, - // All of the chunk's values fit in the budget — no sub-batching. - Some(values_per_subbatch) if values_per_subbatch >= vals_in_chunk => None, - Some(values_per_subbatch) => { - // `count_values_within_byte_budget` never reports zero, but a - // zero-wide window would not advance `write_granular_chunk`. - let values_per_subbatch = values_per_subbatch.max(1); - Some(if value_exact { - SubBatchStrategy::Values(values_per_subbatch) - } else { - // Scale to a level count. Inexact on nullable chunks, and - // deliberately so — see `SubBatchStrategy::Levels`. - let levels_per_subbatch = if vals_in_chunk == chunk_size { - values_per_subbatch - } else { - (values_per_subbatch * chunk_size) - .div_ceil(vals_in_chunk) - .max(1) - }; - SubBatchStrategy::Levels { - levels: chunk_size.min(levels_per_subbatch), - max_values: values_per_subbatch.saturating_mul(2), - } - }) - } + if fit >= vals_in_chunk { + return None; } + // `count_values_within_byte_budget` never reports zero, but a + // zero-wide window would not advance `write_granular_chunk`. + let values_per_subbatch = fit.max(1); + Some(if value_exact { + SubBatchStrategy::Values(values_per_subbatch) + } else { + // Scale to a level count. Inexact on nullable chunks, and + // deliberately so — see `SubBatchStrategy::Levels`. + let levels_per_subbatch = if vals_in_chunk == chunk_size { + values_per_subbatch + } else { + (values_per_subbatch * chunk_size) + .div_ceil(vals_in_chunk) + .max(1) + }; + SubBatchStrategy::Levels { + levels: chunk_size.min(levels_per_subbatch), + max_values: values_per_subbatch.saturating_mul(2), + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::basic::Repetition; + use crate::column::writer::encoder::ColumnValueEncoderImpl; + use crate::data_type::{ByteArray, ByteArrayType}; + use crate::file::properties::WriterProperties; + use crate::schema::types::{ColumnPath, Type as SchemaType}; + use std::sync::Arc; + + const BUDGET: usize = 100; + + /// Runs `pick_sub_batch` for one nullable, plain-encoded BYTE_ARRAY + /// chunk whose data page budget is [`BUDGET`] bytes, over both the + /// contiguous and the gather entry points, and checks they agree. + fn pick(lens: &[usize], def: &[i16]) -> Option<SubBatchStrategy> { + let values: Vec<_> = lens + .iter() + .map(|&n| ByteArray::from(vec![b'x'; n])) + .collect(); + let indices: Vec<usize> = (0..values.len()).collect(); + let contiguous = pick_values(&values, None, def); + assert_eq!(contiguous, pick_values(&values, Some(&indices), def)); + contiguous + } + + fn pick_values( + values: &[ByteArray], + value_indices: Option<&[usize]>, + def: &[i16], + ) -> Option<SubBatchStrategy> { + let descr = Arc::new(ColumnDescriptor::new( + Arc::new( + SchemaType::primitive_type_builder("col", Type::BYTE_ARRAY) + .with_repetition(Repetition::OPTIONAL) + .build() + .unwrap(), + ), + 1, + 0, + ColumnPath::from("col"), + )); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_data_page_size_limit(BUDGET) + .build(); + let column_props = props.resolve_column_properties(descr.path()); + let encoder = + ColumnValueEncoderImpl::<ByteArrayType>::try_new(&descr, &props, &column_props) + .unwrap(); + let max_value_bytes = value_indices.and_then(|_| { + <ColumnValueEncoderImpl<ByteArrayType> as ColumnValueEncoder>::max_value_bytes(values) + }); + let chunker = ByteBudgetChunker::new(&descr, &column_props, def.len(), max_value_bytes); + let chunk_def = LevelDataRef::Materialized(def); + chunker.pick_sub_batch(&encoder, values, value_indices, chunk_def, 0, def.len()) + } + + #[test] + fn small_chunk_is_not_split() { + assert_eq!(pick(&[10, 10], &[1, 0, 1, 0]), None); + } + + #[test] + fn overflow_past_the_chunk_does_not_split_it() { + // The chunk holds two small values. The next `chunk_size` values + // reach an oversized value that belongs to a later chunk. That + // overflow must not split this chunk. + assert_eq!(pick(&[10, 10, 1000, 10], &[1, 0, 1, 0]), None); + } + + #[test] + fn overflow_inside_the_chunk_splits_it() { + // Three values in four levels; the first already overflows the + // budget, so one value per window, scaled to ceil(1 * 4 / 3) levels. + assert_eq!( + pick(&[1000, 10, 10], &[1, 1, 0, 1]), + Some(SubBatchStrategy::Levels { + levels: 2, + max_values: 2 + }) + ); + } + + #[test] + fn contiguous_values_past_the_chunk_are_not_read() { + // Raw `ColumnWriter` callers may pad `values` past the values their + // levels reference with placeholders that hold no data, which cannot + // be sized; the contiguous path must not look ahead at them. + let values = [ByteArray::from(vec![b'x'; 10]), ByteArray::new()]; + assert_eq!(pick_values(&values, None, &[1, 0]), None); + } + + #[test] + fn all_null_chunk_is_not_split() { + assert_eq!(pick(&[1000], &[0, 0, 0, 0]), None); } } diff --git a/parquet/src/column/writer/encoder.rs b/parquet/src/column/writer/encoder.rs index 8582d12a98..6a66529fa2 100644 --- a/parquet/src/column/writer/encoder.rs +++ b/parquet/src/column/writer/encoder.rs @@ -98,13 +98,16 @@ pub trait ColumnValueEncoder { num_values_in_batch: usize, ) -> Result<()>; - /// Returns the largest `k` such that the first `k` values in - /// `values[offset..offset + len]` encode to at most `byte_budget` - /// bytes — i.e. how many values fit in a single page byte budget. + /// Counts how many leading values in `values[offset..offset + len]` + /// belong in one page of `byte_budget` bytes. /// - /// Returns `len` if every value fits. Returns at least 1 if a single - /// value alone exceeds the budget, matching parquet's "at least one - /// value per data page" rule. + /// Returns `len` if every value fits. Otherwise the result counts the + /// values that fit, and may also count the first value that overflows. + /// The variable-width implementations count that boundary value, so the + /// page-flush check trips on the mini-batch that crosses the budget. + /// The result is at least 1 when a single value alone exceeds the + /// budget. This matches the parquet rule of at least one value per data + /// page. /// /// `None` means "no cheap estimate available"; the caller stays on /// the batched fast path and lets the post-write @@ -134,6 +137,17 @@ pub trait ColumnValueEncoder { None } + /// Returns an upper bound on the bytes that any one value of `values` + /// adds to a plain-encoded page, if the encoder knows one without + /// reading the values. + /// + /// The byte-budget chunker asks once per write call. The bound lets it + /// prove that a run of values fits a page from the length of the run + /// alone. + fn max_value_bytes(_values: &Self::Values) -> Option<usize> { + None + } + /// Returns the number of buffered values fn num_values(&self) -> usize; diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index cbc10d2827..2c99ab9c7b 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -626,7 +626,15 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { }; debug_assert!(base_batch_size > 0); - let chunker = ByteBudgetChunker::new(&self.descr, &self.column_props, base_batch_size); + // The chunker looks ahead only at gathered values. See + // `ByteBudgetChunker::byte_budget_sub_batch`. + let max_value_bytes = value_indices.and_then(|_| E::max_value_bytes(values)); + let chunker = ByteBudgetChunker::new( + &self.descr, + &self.column_props, + base_batch_size, + max_value_bytes, + ); while levels_offset < num_levels { let mut end_offset = num_levels.min(levels_offset + base_batch_size);
