Skip to main content

parquet/column/writer/
byte_budget_chunker.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! See [`ByteBudgetChunker`] for byte-budget-aware mini-batch sizing.
6
7use crate::basic::Type;
8use crate::column::writer::LevelDataRef;
9use crate::column::writer::encoder::ColumnValueEncoder;
10use crate::file::properties::ResolvedColumnProperties;
11use crate::schema::types::ColumnDescriptor;
12
13/// How [`write_granular_chunk`] should cut mini-batch windows in one chunk.
14///
15/// Cutting on exact value counts is the precise option and the expensive one:
16/// it roughly doubles the number of mini-batches on a nullable column, because
17/// the level:value ratio no longer rounds a window up to cover a second value.
18/// It is used only where that precision buys something.
19///
20/// [`write_granular_chunk`]: super::GenericColumnWriter::write_granular_chunk
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub(crate) enum SubBatchStrategy {
23    /// Cut after exactly this many values, walking definition levels to find
24    /// the boundary.
25    ///
26    /// Used against the data page budget for encodings that compress a value
27    /// against its predecessor, where the round-up below costs whole values of
28    /// output: 16 MiB rather than 2 MiB for 128 values at one null in 16. See
29    /// [#10538] for the measurements.
30    ///
31    /// [#10538]: https://github.com/apache/arrow-rs/issues/10538
32    Values(usize),
33    /// Cut after this many levels: the value budget scaled by the chunk's
34    /// level:value ratio, rounded up.
35    ///
36    /// Used everywhere else, because everywhere else the round-up changes no
37    /// bytes — the *dictionary page* budget shrinks toward zero as the
38    /// dictionary fills, so a one-value budget is routine there for ordinary
39    /// values, and `PLAIN` and `DELTA_LENGTH_BYTE_ARRAY` values cost the same
40    /// wherever they land — while value-exact windows cost throughput
41    /// ([#10554]).
42    ///
43    /// The round-up must stay bounded for that price to be acceptable. The
44    /// level count alone does not bound it: the ratio is a chunk *average*,
45    /// so a window over a run of clustered values can hold far more than the
46    /// budget (28 values of 76 MiB followed by 996 nulls all land in a
47    /// 37-level window, [#11994]). Each window is therefore also capped at
48    /// `max_values` values, twice the value budget, so the page bound [#9972]
49    /// added holds whatever the null layout: two values per page rather than
50    /// one. The cap walks the window's definition levels, but adds no
51    /// mini-batches where nulls are evenly spread.
52    ///
53    /// [#9972]: https://github.com/apache/arrow-rs/pull/9972
54    /// [#10554]: https://github.com/apache/arrow-rs/pull/10554
55    /// [#11994]: https://github.com/apache/arrow-rs/issues/11994
56    Levels { levels: usize, max_values: usize },
57}
58
59/// Picks byte-budget-aware mini-batch sizes for one column.
60///
61/// The parquet column writer checks the data page byte limit only *after*
62/// each mini-batch finishes writing. Mini-batches are sized in rows
63/// (`write_batch_size`, default 1024), so for BYTE_ARRAY columns whose
64/// values are large (e.g. multi-MiB blobs) a single mini-batch can buffer
65/// GiB into one page before the limit is consulted.
66///
67/// This isolates the per-chunk decision that prevents that: given a chunk's
68/// level data and the input values, pick the largest `sub_batch_size` such
69/// that one mini-batch fits in one page byte budget. For the overwhelmingly
70/// common case (small or fixed-width values) the answer is just `chunk_size`
71/// and the decision is O(1) on the column type — only when the input might
72/// overflow does the chunker consult the encoder's byte estimate.
73pub(crate) struct ByteBudgetChunker {
74    /// Configured data page byte limit for the column.
75    page_byte_limit: usize,
76    /// Max definition level of the column; a level equal to this marks a
77    /// present (non-null) leaf value. Used to count values per chunk.
78    max_def_level: i16,
79    /// `true` when no chunk of `base_batch_size` values can ever overflow
80    /// `page_byte_limit` regardless of input. Set once at column open from
81    /// the physical type's known per-value byte size; lets the per-chunk
82    /// decision short-circuit with no work for every numeric, bool, or
83    /// narrow `FIXED_LEN_BYTE_ARRAY` column.
84    static_always_fits: bool,
85    /// Configured dictionary page byte limit for the column.
86    dict_page_byte_limit: usize,
87    /// As [`Self::static_always_fits`] but for the dictionary page: `true`
88    /// when one `base_batch_size` mini-batch of this fixed-width type cannot
89    /// overshoot `dict_page_byte_limit` by more than one mini-batch's worth.
90    static_dict_always_fits: bool,
91    /// Upper bound on the page bytes of any one value of this write call,
92    /// from [`ColumnValueEncoder::max_value_bytes`]. `None` if the encoder
93    /// has no bound, or if the call does not gather values by index.
94    max_value_bytes: Option<usize>,
95}
96
97impl ByteBudgetChunker {
98    #[inline]
99    pub(crate) fn new(
100        descr: &ColumnDescriptor,
101        column_props: &ResolvedColumnProperties,
102        base_batch_size: usize,
103        max_value_bytes: Option<usize>,
104    ) -> Self {
105        let page_byte_limit = column_props.data_page_size_limit;
106        let dict_page_byte_limit = column_props.dictionary_page_size_limit;
107        let static_bytes_per_value = match descr.physical_type() {
108            Type::BOOLEAN => Some(1),
109            Type::INT32 | Type::FLOAT => Some(std::mem::size_of::<i32>()),
110            Type::INT64 | Type::DOUBLE => Some(std::mem::size_of::<i64>()),
111            Type::INT96 => Some(12),
112            Type::FIXED_LEN_BYTE_ARRAY => Some(descr.type_length().max(0) as usize),
113            Type::BYTE_ARRAY => None,
114        };
115        let static_fits = |limit: usize| {
116            static_bytes_per_value
117                .map(|b| b.saturating_mul(base_batch_size) <= limit)
118                .unwrap_or(false)
119        };
120        Self {
121            page_byte_limit,
122            max_def_level: descr.max_def_level(),
123            static_always_fits: static_fits(page_byte_limit),
124            dict_page_byte_limit,
125            static_dict_always_fits: static_fits(dict_page_byte_limit),
126            max_value_bytes,
127        }
128    }
129
130    /// Decide how many *values* at the start of a chunk belong in one
131    /// mini-batch, so the mini-batch cannot overflow whichever page is
132    /// currently accumulating value bytes: the data page when plain-encoding,
133    /// or the *dictionary* page while dictionary-encoding.
134    ///
135    /// `None` means the whole chunk fits in a single mini-batch — the common
136    /// case. `Some(_)` triggers granular sub-batching in
137    /// `write_batch_internal`; see [`SubBatchStrategy`] for why the data page and
138    /// dictionary page budgets get different windowing.
139    ///
140    /// While dictionary-encoding, the data page holds only small RLE indices,
141    /// but the dictionary page accumulates the distinct values themselves —
142    /// so it is the dictionary page's remaining budget that must bound the
143    /// mini-batch. The per-mini-batch dictionary spill check would otherwise
144    /// let one mini-batch of large values balloon the dictionary page.
145    ///
146    /// Returns `None` immediately (no value inspection) when the chunk is
147    /// empty, or when the column is a fixed-width type whose mini-batches
148    /// statically cannot overshoot the relevant page.
149    ///
150    /// `#[inline]`: this is a tiny per-chunk dispatcher; the actual byte
151    /// inspection lives in the out-of-line `byte_budget_sub_batch`.
152    #[inline]
153    pub(crate) fn pick_sub_batch<E: ColumnValueEncoder>(
154        &self,
155        encoder: &E,
156        values: &E::Values,
157        value_indices: Option<&[usize]>,
158        chunk_def: LevelDataRef<'_>,
159        values_offset: usize,
160        chunk_size: usize,
161    ) -> Option<SubBatchStrategy> {
162        if chunk_size == 0 {
163            return None;
164        }
165        // The second element selects the windowing; see [`SubBatchStrategy`]. Only a
166        // constant data page budget under an encoding that compresses against
167        // the previous value is worth cutting exactly.
168        let (budget, value_exact) = if encoder.has_dictionary() {
169            if self.static_dict_always_fits {
170                return None;
171            }
172            // Bound the mini-batch by the dictionary page's *remaining*
173            // budget (it accumulates across mini-batches until it spills).
174            // An encoder that cannot size its dictionary page (`?`) leaves
175            // the chunk unsplit.
176            let used = encoder.estimated_dict_page_size()?;
177            (self.dict_page_byte_limit.saturating_sub(used), false)
178        } else {
179            if self.static_always_fits {
180                return None;
181            }
182            (
183                self.page_byte_limit,
184                encoder.compresses_against_previous_value(),
185            )
186        };
187        self.byte_budget_sub_batch::<E>(
188            values,
189            value_indices,
190            chunk_def,
191            values_offset,
192            chunk_size,
193            budget,
194            value_exact,
195        )
196    }
197
198    /// Inspect value sizes to decide how many of the chunk's values fit in
199    /// `budget` bytes (the data page or dictionary page remaining budget).
200    ///
201    /// `#[inline(never)]` keeps this slow path out of the hot
202    /// `write_batch_internal` loop; numeric and bool columns never reach it.
203    #[inline(never)]
204    #[expect(clippy::too_many_arguments)]
205    fn byte_budget_sub_batch<E: ColumnValueEncoder>(
206        &self,
207        values: &E::Values,
208        value_indices: Option<&[usize]>,
209        chunk_def: LevelDataRef<'_>,
210        values_offset: usize,
211        chunk_size: usize,
212        budget: usize,
213        value_exact: bool,
214    ) -> Option<SubBatchStrategy> {
215        // Ask the encoder how many of the chunk's values fit in one page byte
216        // budget. Dispatch on whether the caller supplied gather indices.
217        // This mirrors how `write_mini_batch` picks `write_gather` or
218        // `write`.
219        let (fit, vals_in_chunk) = match value_indices {
220            Some(idx) => {
221                // Counting the chunk's values scans its def levels on a
222                // nullable column, and most chunks fit outright. So first
223                // try to prove the fit without the count. The next
224                // `chunk_size` values contain the chunk's values, so if
225                // that window fits, the chunk fits too.
226                //
227                // The window overlaps the windows of the following chunks,
228                // almost entirely so on a sparse column. The proof must
229                // therefore not read the window, or a sparse column pays
230                // for `chunk_size` values on every chunk of a few values.
231                // It uses the length of the window and a bound on one value.
232                //
233                // Only gather indices allow this lookahead, because each one
234                // names a real value of a later chunk. A contiguous `values`
235                // slice may hold placeholders past the values its levels
236                // reference. Raw `ColumnWriter` callers pad them, and they
237                // cannot be sized.
238                let end = values_offset.saturating_add(chunk_size).min(idx.len());
239                let start = values_offset.min(end);
240                let window = &idx[start..end];
241                let window_fits =
242                    |max_value_bytes: usize| window.len().saturating_mul(max_value_bytes) <= budget;
243                if window.is_empty() || self.max_value_bytes.is_some_and(window_fits) {
244                    return None;
245                }
246                let vals_in_chunk = chunk_def.value_count(chunk_size, self.max_def_level);
247                let chunk_idx = &window[..vals_in_chunk.min(window.len())];
248                if chunk_idx.is_empty() {
249                    return None;
250                }
251                let fit = E::count_values_within_byte_budget_gather(values, chunk_idx, budget)?;
252                (fit, vals_in_chunk)
253            }
254            None => {
255                // For a non-nullable, unrepeated column `value_count` is O(1)
256                // (`Absent` or `Uniform` def levels). Nullable or nested
257                // columns pay the def-level scan.
258                let vals_in_chunk = chunk_def.value_count(chunk_size, self.max_def_level);
259                if vals_in_chunk == 0 {
260                    return None;
261                }
262                let fit = E::count_values_within_byte_budget(
263                    values,
264                    values_offset,
265                    vals_in_chunk,
266                    budget,
267                )?;
268                (fit, vals_in_chunk)
269            }
270        };
271        if fit >= vals_in_chunk {
272            return None;
273        }
274        // `count_values_within_byte_budget` never reports zero, but a
275        // zero-wide window would not advance `write_granular_chunk`.
276        let values_per_subbatch = fit.max(1);
277        Some(if value_exact {
278            SubBatchStrategy::Values(values_per_subbatch)
279        } else {
280            // Scale to a level count. Inexact on nullable chunks, and
281            // deliberately so — see `SubBatchStrategy::Levels`.
282            let levels_per_subbatch = if vals_in_chunk == chunk_size {
283                values_per_subbatch
284            } else {
285                (values_per_subbatch * chunk_size)
286                    .div_ceil(vals_in_chunk)
287                    .max(1)
288            };
289            SubBatchStrategy::Levels {
290                levels: chunk_size.min(levels_per_subbatch),
291                max_values: values_per_subbatch.saturating_mul(2),
292            }
293        })
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use crate::basic::Repetition;
301    use crate::column::writer::encoder::ColumnValueEncoderImpl;
302    use crate::data_type::{ByteArray, ByteArrayType};
303    use crate::file::properties::WriterProperties;
304    use crate::schema::types::{ColumnPath, Type as SchemaType};
305    use std::sync::Arc;
306
307    const BUDGET: usize = 100;
308
309    /// Runs `pick_sub_batch` for one nullable, plain-encoded BYTE_ARRAY
310    /// chunk whose data page budget is [`BUDGET`] bytes, over both the
311    /// contiguous and the gather entry points, and checks they agree.
312    fn pick(lens: &[usize], def: &[i16]) -> Option<SubBatchStrategy> {
313        let values: Vec<_> = lens
314            .iter()
315            .map(|&n| ByteArray::from(vec![b'x'; n]))
316            .collect();
317        let indices: Vec<usize> = (0..values.len()).collect();
318        let contiguous = pick_values(&values, None, def);
319        assert_eq!(contiguous, pick_values(&values, Some(&indices), def));
320        contiguous
321    }
322
323    fn pick_values(
324        values: &[ByteArray],
325        value_indices: Option<&[usize]>,
326        def: &[i16],
327    ) -> Option<SubBatchStrategy> {
328        let descr = Arc::new(ColumnDescriptor::new(
329            Arc::new(
330                SchemaType::primitive_type_builder("col", Type::BYTE_ARRAY)
331                    .with_repetition(Repetition::OPTIONAL)
332                    .build()
333                    .unwrap(),
334            ),
335            1,
336            0,
337            ColumnPath::from("col"),
338        ));
339        let props = WriterProperties::builder()
340            .set_dictionary_enabled(false)
341            .set_data_page_size_limit(BUDGET)
342            .build();
343        let column_props = props.resolve_column_properties(descr.path());
344        let encoder =
345            ColumnValueEncoderImpl::<ByteArrayType>::try_new(&descr, &props, &column_props)
346                .unwrap();
347        let max_value_bytes = value_indices.and_then(|_| {
348            <ColumnValueEncoderImpl<ByteArrayType> as ColumnValueEncoder>::max_value_bytes(values)
349        });
350        let chunker = ByteBudgetChunker::new(&descr, &column_props, def.len(), max_value_bytes);
351        let chunk_def = LevelDataRef::Materialized(def);
352        chunker.pick_sub_batch(&encoder, values, value_indices, chunk_def, 0, def.len())
353    }
354
355    #[test]
356    fn small_chunk_is_not_split() {
357        assert_eq!(pick(&[10, 10], &[1, 0, 1, 0]), None);
358    }
359
360    #[test]
361    fn overflow_past_the_chunk_does_not_split_it() {
362        // The chunk holds two small values. The next `chunk_size` values
363        // reach an oversized value that belongs to a later chunk. That
364        // overflow must not split this chunk.
365        assert_eq!(pick(&[10, 10, 1000, 10], &[1, 0, 1, 0]), None);
366    }
367
368    #[test]
369    fn overflow_inside_the_chunk_splits_it() {
370        // Three values in four levels; the first already overflows the
371        // budget, so one value per window, scaled to ceil(1 * 4 / 3) levels.
372        assert_eq!(
373            pick(&[1000, 10, 10], &[1, 1, 0, 1]),
374            Some(SubBatchStrategy::Levels {
375                levels: 2,
376                max_values: 2
377            })
378        );
379    }
380
381    #[test]
382    fn contiguous_values_past_the_chunk_are_not_read() {
383        // Raw `ColumnWriter` callers may pad `values` past the values their
384        // levels reference with placeholders that hold no data, which cannot
385        // be sized; the contiguous path must not look ahead at them.
386        let values = [ByteArray::from(vec![b'x'; 10]), ByteArray::new()];
387        assert_eq!(pick_values(&values, None, &[1, 0]), None);
388    }
389
390    #[test]
391    fn all_null_chunk_is_not_split() {
392        assert_eq!(pick(&[1000], &[0, 0, 0, 0]), None);
393    }
394}