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-11462-e466ec1b86a0702840c0a58c38838c0f513290ea in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 120ce28dda04f3c019a9ecba0ed9622af975415f Author: RIchard Baah <[email protected]> AuthorDate: Tue Oct 20 14:40:03 2026 +0000 perf(parquet): skip per-batch key-bounds scan when RLE bit width prov… (#11462) # Which issue does this PR close? - Closes https://github.com/apache/arrow-rs/issues/11414 # Rationale for this change - https://github.com/apache/datafusion/issues/24111 - see https://github.com/apache/arrow-rs/issues/11414 for more context # split out of https://github.com/apache/arrow-rs/pull/11423 , see comment for [context](https://github.com/apache/arrow-rs/pull/11423#pullrequestreview-5459190670) Skip the per-batch key bounds scan when the RLE bit width already proves it's safe. `DictionaryBuffer::Dict` now carries an optional key_upper_bound: Option<u64>, populated from the RLE page's bit_width as 2^bit_width, an exclusive upper bound on anything the decoder can produce. if key_upper_bound <= values.len(), every representable key is already a valid dictionary index, so the min/max fold over keys is skipped entirely. **This removes a per-batch O(n) pass that dominated the profile on low-cardinality shapes.** --- .../arrow/array_reader/byte_array_dictionary.rs | 25 +++- parquet/src/arrow/buffer/dictionary_buffer.rs | 163 +++++++++++++++++---- parquet/src/encodings/rle.rs | 10 +- 3 files changed, 167 insertions(+), 31 deletions(-) diff --git a/parquet/src/arrow/array_reader/byte_array_dictionary.rs b/parquet/src/arrow/array_reader/byte_array_dictionary.rs index 01138abfab..8ffa414eed 100644 --- a/parquet/src/arrow/array_reader/byte_array_dictionary.rs +++ b/parquet/src/arrow/array_reader/byte_array_dictionary.rs @@ -280,6 +280,8 @@ enum MaybeDictionaryDecoder { /// This is a maximum as the null count is not always known, e.g. value data from /// a v1 data page max_remaining_values: usize, + /// Validated bit width of decoded dictionary keys. + bit_width: u8, }, Fallback(ByteArrayDecoder), Fixed(FixedByteArrayDecoder), @@ -401,6 +403,7 @@ where MaybeDictionaryDecoder::Dict { decoder, max_remaining_values: num_values.unwrap_or(num_levels), + bit_width, } } _ if self.flba_column_descr.is_some() => { @@ -433,6 +436,7 @@ where MaybeDictionaryDecoder::Dict { decoder, max_remaining_values, + bit_width, } => { let len = num_values.min(*max_remaining_values); @@ -447,11 +451,9 @@ where return Ok(0); // All data must be NULL } - match out.as_keys(dict) { + match out.as_keys_with_bit_width(dict, Some(*bit_width)) { Some(keys) => { // Happy path - can just copy keys - // Keys will be validated on conversion to arrow - // TODO: Push vec into decoder (#5177) let start = keys.len(); keys.resize(start + len, K::default()); @@ -492,6 +494,7 @@ where MaybeDictionaryDecoder::Dict { decoder, max_remaining_values, + bit_width: _, } => { let num_values = num_values.min(*max_remaining_values); *max_remaining_values -= num_values; @@ -963,4 +966,20 @@ mod tests { "Parquet error: Invalid or corrupted RLE bit width 33. Max allowed is 32" ); } + + #[test] + fn test_dictionary_decoder_rejects_rle_value_exceeding_bit_width() { + let column_desc = utf8_column(); + let mut decoder = DictionaryDecoder::<i32, i32>::new(&column_desc); + + // Bit width 1, run length 1, value 0xff. + let data = Bytes::from_static(&[1, 2, 0xff]); + let err = decoder + .set_data(Encoding::RLE_DICTIONARY, data, 1, Some(1)) + .unwrap_err(); + assert_eq!( + err.to_string(), + "Parquet error: Invalid or corrupted RLE value 255 exceeds bit width 1" + ); + } } diff --git a/parquet/src/arrow/buffer/dictionary_buffer.rs b/parquet/src/arrow/buffer/dictionary_buffer.rs index aef28b045b..25800c52b6 100644 --- a/parquet/src/arrow/buffer/dictionary_buffer.rs +++ b/parquet/src/arrow/buffer/dictionary_buffer.rs @@ -44,8 +44,22 @@ use std::sync::Arc; /// An array of variable length byte arrays that are potentially dictionary encoded /// and can be converted into a corresponding [`ArrayRef`] pub enum DictionaryBuffer<K: ArrowNativeType, V: OffsetSizeTrait> { - Dict { keys: Vec<K>, values: ArrayRef }, - Values { values: OffsetBuffer<V> }, + Dict { + keys: Vec<K>, + values: ArrayRef, + /// Exclusive upper bound for decoded keys. + key_upper_bound: Option<u64>, + }, + Values { + values: OffsetBuffer<V>, + }, +} + +fn widen_key_bound(existing: &mut Option<u64>, incoming: Option<u64>) { + *existing = match (*existing, incoming) { + (Some(current), Some(new)) => Some(current.max(new)), + _ => None, + }; } impl<K: ArrowNativeType + Ord, V: OffsetSizeTrait> DictionaryBuffer<K, V> { @@ -57,27 +71,41 @@ impl<K: ArrowNativeType + Ord, V: OffsetSizeTrait> DictionaryBuffer<K, V> { } } - /// Returns a mutable reference to a keys array + /// Returns the key buffer or `None` if the dictionary must be rebuilt. /// - /// Returns None if the dictionary needs to be recomputed + /// Records an exclusive bound derived from `rle_bit_width`. A missing width + /// discards any previously recorded bound. /// /// # Panics /// - /// Panics if the dictionary is too large for `K` - pub fn as_keys(&mut self, dictionary: &ArrayRef) -> Option<&mut Vec<K>> { + /// Panics if the dictionary is too large for `K`. + pub fn as_keys_with_bit_width( + &mut self, + dictionary: &ArrayRef, + rle_bit_width: Option<u8>, + ) -> Option<&mut Vec<K>> { assert!(K::from_usize(dictionary.len()).is_some()); + // Dictionary RLE bit widths are validated to be at most 32. + let incoming_bound = rle_bit_width.map(|bit_width| 1u64 << bit_width); + match self { - Self::Dict { keys, values } => { + Self::Dict { + keys, + values, + key_upper_bound, + } => { // Need to discard fat pointer for equality check // - https://stackoverflow.com/a/67114787 // - https://github.com/rust-lang/rust/issues/46139 let values_ptr = std::ptr::from_ref(values.as_ref()).cast::<()>(); let dict_ptr = std::ptr::from_ref(dictionary.as_ref()).cast::<()>(); if values_ptr == dict_ptr { + widen_key_bound(key_upper_bound, incoming_bound); Some(keys) } else if keys.is_empty() { *values = Arc::clone(dictionary); + *key_upper_bound = incoming_bound; Some(keys) } else { None @@ -87,6 +115,7 @@ impl<K: ArrowNativeType + Ord, V: OffsetSizeTrait> DictionaryBuffer<K, V> { *self = Self::Dict { keys: Default::default(), values: Arc::clone(dictionary), + key_upper_bound: incoming_bound, }; match self { Self::Dict { keys, .. } => Some(keys), @@ -104,7 +133,7 @@ impl<K: ArrowNativeType + Ord, V: OffsetSizeTrait> DictionaryBuffer<K, V> { pub fn spill_values(&mut self) -> Result<&mut OffsetBuffer<V>> { match self { Self::Values { values } => Ok(values), - Self::Dict { keys, values } => { + Self::Dict { keys, values, .. } => { let mut spilled = OffsetBuffer::with_capacity(0); let data = values.to_data(); let dict_buffers = data.buffers(); @@ -142,21 +171,27 @@ impl<K: ArrowNativeType + Ord, V: OffsetSizeTrait> DictionaryBuffer<K, V> { assert!(matches!(data_type, ArrowType::Dictionary(_, _))); match self { - Self::Dict { keys, values } => { - // Validate keys unless dictionary is empty - if !values.is_empty() { + Self::Dict { + keys, + values, + key_upper_bound, + } => { + let keys_provably_in_range = key_upper_bound + .map(|bound| bound <= values.len() as u64) + .unwrap_or(false); + + if !values.is_empty() && !keys_provably_in_range { let min = K::from_usize(0).unwrap(); let max = K::from_usize(values.len()).unwrap(); - // using copied and fold gets auto-vectorized since rust 1.70 - // all/any would allow early exit on invalid values - // but in the happy case all values have to be checked anyway - if !keys - .as_slice() - .iter() - .copied() - .fold(true, |a, x| a && x >= min && x < max) - { + let (observed_min, observed_max) = keys.as_slice().iter().copied().fold( + (max, min), + |(current_min, current_max), key| { + (current_min.min(key), current_max.max(key)) + }, + ); + + if observed_min < min || observed_max >= max { return Err(general_err!( "dictionary key beyond bounds of dictionary: 0..{}", values.len() @@ -521,7 +556,10 @@ mod tests { // Read some data preserving the dictionary let values = &[1, 0, 3, 2, 4]; - buffer.as_keys(&d1).unwrap().extend_from_slice(values); + buffer + .as_keys_with_bit_width(&d1, None) + .unwrap() + .extend_from_slice(values); let mut valid = vec![false, false, true, true, false, true, true, true]; let valid_buffer = Buffer::from_iter(valid.iter().copied()); @@ -576,7 +614,7 @@ mod tests { assert_eq!(buffer.len(), 0); let d2 = Arc::new(StringArray::from(vec!["bingo", ""])) as ArrayRef; buffer - .as_keys(&d2) + .as_keys_with_bit_width(&d2, None) .unwrap() .extend_from_slice(&[0, 1, 0, 1]); @@ -596,11 +634,14 @@ mod tests { assert!(matches!(&buffer, DictionaryBuffer::Values { .. })); assert_eq!(buffer.len(), 0); let d3 = Arc::new(StringArray::from(vec!["bongo"])) as ArrayRef; - buffer.as_keys(&d3).unwrap().extend_from_slice(&[0, 0]); + buffer + .as_keys_with_bit_width(&d3, None) + .unwrap() + .extend_from_slice(&[0, 0]); // Cannot change dictionary as keys not empty let d4 = Arc::new(StringArray::from(vec!["bananas"])) as ArrayRef; - assert!(buffer.as_keys(&d4).is_none()); + assert!(buffer.as_keys_with_bit_width(&d4, None).is_none()); } #[test] @@ -610,7 +651,10 @@ mod tests { let mut buffer = DictionaryBuffer::<i32, i32>::with_capacity(0); let d = Arc::new(StringArray::from(vec!["", "f"])) as ArrayRef; - buffer.as_keys(&d).unwrap().extend_from_slice(&[0, 2, 0]); + buffer + .as_keys_with_bit_width(&d, None) + .unwrap() + .extend_from_slice(&[0, 2, 0]); let err = buffer .into_array(None, &dict_type, &mut MutableBuffer::new(0)) @@ -624,7 +668,10 @@ mod tests { let mut buffer = DictionaryBuffer::<i32, i32>::with_capacity(0); let d = Arc::new(StringArray::from(vec![""])) as ArrayRef; - buffer.as_keys(&d).unwrap().extend_from_slice(&[0, 1, 0]); + buffer + .as_keys_with_bit_width(&d, None) + .unwrap() + .extend_from_slice(&[0, 1, 0]); let err = buffer.spill_values().unwrap_err().to_string(); assert!( @@ -790,4 +837,68 @@ mod tests { assert_eq!(dict.data_type(), &dict_type); assert_eq!(dict.values().data_type(), &ArrowType::Binary); } + + #[test] + fn test_key_upper_bound_skip_scan_when_bound_fits_otherwise_scan() { + let dict_type = + ArrowType::Dictionary(Box::new(ArrowType::Int32), Box::new(ArrowType::Utf8)); + let dict_5 = Arc::new(StringArray::from(vec!["a", "b", "c", "d", "e"])) as ArrayRef; + + let mut buffer = DictionaryBuffer::<i32, i32>::with_capacity(0); + buffer + .as_keys_with_bit_width(&dict_5, Some(2)) + .unwrap() + .extend_from_slice(&[0, 1, 2, 3]); + assert!(matches!( + buffer, + DictionaryBuffer::Dict { + key_upper_bound: Some(4), + .. + } + )); + let array = buffer + .into_array(None, &dict_type, &mut MutableBuffer::new(0)) + .unwrap(); + assert_eq!(array.len(), 4); + + let mut buffer = DictionaryBuffer::<i32, i32>::with_capacity(0); + buffer + .as_keys_with_bit_width(&dict_5, Some(4)) + .unwrap() + .extend_from_slice(&[0, 10]); + let err = buffer + .into_array(None, &dict_type, &mut MutableBuffer::new(0)) + .unwrap_err() + .to_string(); + assert!(err.contains("dictionary key beyond bounds"), "{err}"); + + let mut buffer = DictionaryBuffer::<i32, i32>::with_capacity(0); + buffer + .as_keys_with_bit_width(&dict_5, None) + .unwrap() + .extend_from_slice(&[0, 7]); + buffer + .into_array(None, &dict_type, &mut MutableBuffer::new(0)) + .unwrap_err(); + + let mut buffer = DictionaryBuffer::<i32, i32>::with_capacity(0); + buffer + .as_keys_with_bit_width(&dict_5, Some(2)) + .unwrap() + .extend_from_slice(&[0, 1]); + buffer + .as_keys_with_bit_width(&dict_5, Some(4)) + .unwrap() + .extend_from_slice(&[10]); + assert!(matches!( + buffer, + DictionaryBuffer::Dict { + key_upper_bound: Some(16), + .. + } + )); + buffer + .into_array(None, &dict_type, &mut MutableBuffer::new(0)) + .unwrap_err(); + } } diff --git a/parquet/src/encodings/rle.rs b/parquet/src/encodings/rle.rs index d45b999fc0..67af778d4b 100644 --- a/parquet/src/encodings/rle.rs +++ b/parquet/src/encodings/rle.rs @@ -742,10 +742,16 @@ impl RleDecoder { } else { self.rle_left = num_values; let value_width = bit_util::ceil(self.bit_width as usize, u8::BITS as usize); - self.current_value = bit_reader.get_aligned::<u64>(value_width); - self.current_value.ok_or_else(|| { + let value = bit_reader.get_aligned::<u64>(value_width).ok_or_else(|| { general_err!("parquet_data_error: not enough data for RLE decoding") })?; + if self.bit_width < u64::BITS as u8 && value >= (1_u64 << self.bit_width) { + return Err(general_err!( + "Invalid or corrupted RLE value {value} exceeds bit width {}", + self.bit_width + )); + } + self.current_value = Some(value); } Ok(true) } else {
