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-12161-4c03e90286b2b176dd37cf08187a61c09b09acb7 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 2a007e8ef61106711ded9148d7eb95ddf3aebd33 Author: RIchard Baah <[email protected]> AuthorDate: Fri Nov 13 01:32:48 2026 +0000 fix(parquet): honor requested dictionary value type (#12161) # Which issue does this PR close? - Closes #11748. # Rationale for this change A Parquet `BYTE_ARRAY` column without a UTF8 annotation is physically decoded as `Binary`. When a caller supplies a schema requesting `Dictionary(Int32, Utf8)`, the dictionary reader previously still returned `Dictionary(Int32, Binary)`, requiring the scan consumer to cast every emitted batch. For a dictionary page containing potentially thousands of unique values: ```text values = [ b"mobile", b"desktop", b"tablet", b"bot", b"tv", b"console", b"wearable", b"other", ... ] keys = [0, 0, 1, 2, 0, 3, 1, 4, 5, 0, 6, 7, ...] ``` Before this PR, batches from the same dictionary page repeatedly converted and allocated the entire dictionary values array: ```text Parquet dictionary page Binary dictionary values (potentially thousands) [mobile, desktop, tablet, bot, tv, console, wearable, other, ...] | decode batches with shared Binary dictionary values | +-------------------+-------------------+ | | | batch 1 batch 2 batch N keys [..] keys [..] keys [..] | | | | cast ALL | cast ALL | cast ALL | dictionary | dictionary | dictionary | values again | values again | values again v v v allocate Utf8 allocate Utf8 allocate Utf8 [mobile, ...] [mobile, ...] [mobile, ...] | | | v v v Dict<Int32, Utf8> Dict<Int32, Utf8> Dict<Int32, Utf8> same validation, conversion, and allocation repeated per batch ``` After this PR, the reader converts the unique values once per dictionary page and shares the result with every batch: ```text Parquet dictionary page Binary dictionary values (potentially thousands) [mobile, desktop, tablet, bot, tv, console, wearable, other, ...] | validate + convert ALL values ONCE | v cached Utf8 values [mobile, desktop, tablet, bot, tv, console, wearable, other, ...] | +----------+----------+ | | | batch 1 batch 2 batch N keys [..] keys [..] keys [..] | | | +---- share cached ---+ Utf8 values | | | v v v Dict<Int32, Utf8> ... Dict<Int32, Utf8> one validation, conversion, and allocation per dictionary page ``` The potentially millions of keys are preserved; only the unique dictionary values are converted. Invalid UTF-8 still returns an error. Plain-encoded fallback pages retain the existing dictionary-building path. # Are these changes tested? Coverage includes binary dictionary pages requested as `Utf8`, `LargeUtf8`, and `Utf8View`, reuse across batches, nulls, invalid UTF-8 rejection, and plain-encoded fallback pages. End-to-end hosted benchmark evidence is recorded in [apache/datafusion#27312](https://github.com/apache/datafusion/pull/27312#issuecomment-6776074482). With RLE dictionary reads enabled on both the exact parent and dependency head, total time across TPC-H, TPC-DS, and partitioned ClickBench improved by 22.40% (49.147s to 38.140s); partitioned ClickBench improved by 27.60%. All suites completed without query failures. # Are there any significant user-facing changes? No. --- .../arrow/array_reader/byte_array_dictionary.rs | 111 ++++++---- parquet/src/arrow/arrow_reader/tests/schema.rs | 230 +++++++++++++++++++++ 2 files changed, 305 insertions(+), 36 deletions(-) diff --git a/parquet/src/arrow/array_reader/byte_array_dictionary.rs b/parquet/src/arrow/array_reader/byte_array_dictionary.rs index 337ca8741d..0db34d07ff 100644 --- a/parquet/src/arrow/array_reader/byte_array_dictionary.rs +++ b/parquet/src/arrow/array_reader/byte_array_dictionary.rs @@ -8,7 +8,8 @@ use std::sync::Arc; use arrow_array::cast::AsArray; use arrow_array::{ - Array, ArrayRef, BinaryViewArray, OffsetSizeTrait, StringViewArray, new_empty_array, + Array, ArrayRef, BinaryViewArray, LargeStringArray, OffsetSizeTrait, StringArray, + StringViewArray, new_empty_array, }; use arrow_buffer::{ArrowNativeType, MutableBuffer}; use arrow_schema::DataType as ArrowType; @@ -38,12 +39,13 @@ macro_rules! make_reader { match ($k, $v) { $( ($key_arrow, $value_arrow) => { + let buffer_value_type = byte_array_value_type::<$value_type>(&$column_desc); let mut reader = GenericRecordReader::new($column_desc, $batch_size); if let Some(threshold) = $padding_threshold { reader.set_padding_threshold(threshold); } Ok(Box::new(ByteArrayDictionaryReader::<$key_type, $value_type>::try_new( - $pages, $data_type, reader, + $pages, $data_type, buffer_value_type, reader, )?)) } )+ @@ -111,32 +113,46 @@ pub fn make_byte_array_dictionary_reader( } } -/// Convert a dictionary-typed array with string or binary typed values -/// to one with string or binary view typed values. -fn convert_values_to_view(array: ArrayRef, to_type: &ArrowType) -> Result<ArrayRef> { - let ArrowType::Dictionary(_, to_value_type) = to_type else { - return Err(general_err!( - "Cannot convert {} dictionary values to non-dictionary type {}", - array.data_type(), - to_type - )); - }; - - let array = array.as_any_dictionary(); - let values = array.values(); +/// Returns the string or binary type produced when decoding a byte array column. +fn byte_array_value_type<V: OffsetSizeTrait>(column_desc: &ColumnDescPtr) -> ArrowType { + match ( + V::IS_LARGE, + column_desc.converted_type() == ConvertedType::UTF8, + ) { + (true, true) => ArrowType::LargeUtf8, + (true, false) => ArrowType::LargeBinary, + (false, true) => ArrowType::Utf8, + (false, false) => ArrowType::Binary, + } +} - let new_values: ArrayRef = match to_value_type.as_ref() { - ArrowType::Utf8View => Arc::new(StringViewArray::from(values.as_string::<i32>())), - ArrowType::BinaryView => Arc::new(BinaryViewArray::from(values.as_binary::<i32>())), - other => { +/// Convert dictionary values without expanding the dictionary keys. +fn convert_dictionary_values(values: &ArrayRef, to_type: &ArrowType) -> Result<ArrayRef> { + let new_values: ArrayRef = match (values.data_type(), to_type) { + (ArrowType::Binary, ArrowType::Utf8) => Arc::new(StringArray::try_from_binary( + values.as_binary::<i32>().clone(), + )?), + (ArrowType::LargeBinary, ArrowType::LargeUtf8) => Arc::new( + LargeStringArray::try_from_binary(values.as_binary::<i64>().clone())?, + ), + (ArrowType::Utf8, ArrowType::Utf8View) => { + Arc::new(StringViewArray::from(values.as_string::<i32>())) + } + (ArrowType::Binary, ArrowType::Utf8View) => { + let values = StringArray::try_from_binary(values.as_binary::<i32>().clone())?; + Arc::new(StringViewArray::from(&values)) + } + (ArrowType::Binary, ArrowType::BinaryView) => { + Arc::new(BinaryViewArray::from(values.as_binary::<i32>())) + } + (from, to) => { return Err(general_err!( - "Cannot convert dictionary values to {}", - other + "Cannot convert dictionary values from {from} to {to}" )); } }; - Ok(array.with_values(new_values)) + Ok(new_values) } /// An [`ArrayReader`] for dictionary encoded byte arrays @@ -152,6 +168,11 @@ struct ByteArrayDictionaryReader<K: ArrowNativeType, V: OffsetSizeTrait> { record_reader: GenericRecordReader<DictionaryBuffer<K, V>, DictionaryDecoder<K, V>>, /// Reusable scratch space for hashing byte slices when building dictionaries from plain-encoded values. hash_scratch: MutableBuffer, + /// Cached `(source_values, converted_values)` for the current dictionary page. + /// + /// `source_values` is retained for pointer-identity checks, while + /// `converted_values` is reused across batches backed by the same dictionary page. + converted_values_cache: Option<(ArrayRef, ArrayRef)>, } impl<K, V> ByteArrayDictionaryReader<K, V> @@ -162,6 +183,7 @@ where fn try_new( pages: Box<dyn PageIterator>, data_type: ArrowType, + buffer_value_type: ArrowType, record_reader: GenericRecordReader<DictionaryBuffer<K, V>, DictionaryDecoder<K, V>>, ) -> Result<Self> { let ArrowType::Dictionary(key_type, value_type) = &data_type else { @@ -172,13 +194,10 @@ where }; let buffer_type = match value_type.as_ref() { - ArrowType::Utf8View => Some(ArrowType::Dictionary( + ArrowType::FixedSizeBinary(_) => None, + _ if value_type.as_ref() != &buffer_value_type => Some(ArrowType::Dictionary( key_type.clone(), - Box::new(ArrowType::Utf8), - )), - ArrowType::BinaryView => Some(ArrowType::Dictionary( - key_type.clone(), - Box::new(ArrowType::Binary), + Box::new(buffer_value_type), )), _ => None, }; @@ -191,6 +210,7 @@ where rep_levels_buffer: None, record_reader, hash_scratch: MutableBuffer::new(0), + converted_values_cache: None, }) } } @@ -227,13 +247,37 @@ where let buffer = self.record_reader.consume_record_data(); let null_buffer = self.record_reader.consume_compact_bitmap(); + let ArrowType::Dictionary(_, output_value_type) = &self.data_type else { + unreachable!() + }; + let cache_converted_values = matches!(&buffer, DictionaryBuffer::Dict { .. }); + + // Plain-encoded pages also decode into `buffer_type` and convert, so that + // `convert_dictionary_values` validates UTF-8 for unannotated BINARY columns. let array = match &self.buffer_type { - None => buffer.into_array(null_buffer, &self.data_type, &mut self.hash_scratch)?, Some(buffer_type) => { let buffer_array = buffer.into_array(null_buffer, buffer_type, &mut self.hash_scratch)?; - convert_values_to_view(buffer_array, &self.data_type)? + let array = buffer_array.as_any_dictionary(); + let values = array.values(); + let converted = match (cache_converted_values, &self.converted_values_cache) { + // Reuse the conversion for another batch from the same dictionary page. + (true, Some((source, converted))) if Arc::ptr_eq(source, values) => { + Arc::clone(converted) + } + // Convert and cache values from the first batch of a dictionary page. + (true, _) => { + let converted = convert_dictionary_values(values, output_value_type)?; + self.converted_values_cache = + Some((Arc::clone(values), Arc::clone(&converted))); + converted + } + // Convert batch-local plain-page values without caching them. + (false, _) => convert_dictionary_values(values, output_value_type)?, + }; + array.with_values(converted) } + None => buffer.into_array(null_buffer, &self.data_type, &mut self.hash_scratch)?, }; self.record_reader.reset(); @@ -303,12 +347,7 @@ where fn new(col: &ColumnDescPtr) -> Self { let validate_utf8 = col.converted_type() == ConvertedType::UTF8; - let value_type = match (V::IS_LARGE, col.converted_type() == ConvertedType::UTF8) { - (true, true) => ArrowType::LargeUtf8, - (true, false) => ArrowType::LargeBinary, - (false, true) => ArrowType::Utf8, - (false, false) => ArrowType::Binary, - }; + let value_type = byte_array_value_type::<V>(col); Self { dict: None, diff --git a/parquet/src/arrow/arrow_reader/tests/schema.rs b/parquet/src/arrow/arrow_reader/tests/schema.rs index 6a93395113..1a8d2ed8c1 100644 --- a/parquet/src/arrow/arrow_reader/tests/schema.rs +++ b/parquet/src/arrow/arrow_reader/tests/schema.rs @@ -622,6 +622,236 @@ fn test_read_binary_as_utf8() { ); } +fn dictionary_type(value_type: ArrowDataType) -> ArrowDataType { + ArrowDataType::Dictionary(Box::new(ArrowDataType::Int32), Box::new(value_type)) +} + +#[test] +fn test_binary_column_as_utf8_dictionary() { + let file = write_parquet_from_iter(vec![( + "binary", + Arc::new(BinaryArray::from(vec![ + b"one".as_ref(), + b"two".as_ref(), + b"one".as_ref(), + ])) as ArrayRef, + )]); + let data_type = dictionary_type(ArrowDataType::Utf8); + let schema = Arc::new(Schema::new(vec![Field::new( + "binary", + data_type.clone(), + false, + )])); + let options = ArrowReaderOptions::new().with_schema(schema); + let mut reader = ParquetRecordBatchReaderBuilder::try_new_with_options(file, options) + .unwrap() + .build() + .unwrap(); + + let batch = reader.next().unwrap().unwrap(); + assert_eq!(batch.column(0).data_type(), &data_type); + let dictionary = batch + .column(0) + .as_dictionary::<arrow::datatypes::Int32Type>(); + assert_eq!(dictionary.keys().values().as_ref(), &[0, 1, 0]); + assert_eq!( + dictionary.values().as_string::<i32>(), + &StringArray::from(vec!["one", "two"]) + ); +} + +#[test] +fn test_dictionary_requested_value_type_variants() { + let values = vec![b"one".as_ref(), b"two".as_ref(), b"one".as_ref()]; + let file = write_parquet_from_iter(vec![ + ( + "large_utf8", + Arc::new(LargeBinaryArray::from(values.clone())) as ArrayRef, + ), + ("utf8_view", Arc::new(BinaryArray::from(values)) as ArrayRef), + ]); + let schema = Arc::new(Schema::new(vec![ + Field::new( + "large_utf8", + dictionary_type(ArrowDataType::LargeUtf8), + false, + ), + Field::new("utf8_view", dictionary_type(ArrowDataType::Utf8View), false), + ])); + + let options = ArrowReaderOptions::new().with_schema(Arc::clone(&schema)); + let mut reader = ParquetRecordBatchReaderBuilder::try_new_with_options(file, options) + .unwrap() + .build() + .unwrap(); + + let batch = reader.next().unwrap().unwrap(); + assert_eq!(batch.schema().as_ref(), schema.as_ref()); + let expected = StringArray::from(vec!["one", "two", "one"]); + for column in batch.columns() { + let actual = arrow::compute::cast(column, &ArrowDataType::Utf8).unwrap(); + assert_eq!(actual.as_string::<i32>(), &expected); + } +} + +#[test] +fn test_dictionary_value_cache_across_row_groups() { + let values = Arc::new(BinaryArray::from(vec![ + b"one".as_ref(), + b"two".as_ref(), + b"one".as_ref(), + b"two".as_ref(), + b"three".as_ref(), + b"four".as_ref(), + b"three".as_ref(), + b"four".as_ref(), + ])) as ArrayRef; + let batch = RecordBatch::try_from_iter(vec![("binary", values)]).unwrap(); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(4)) + .build(); + let mut parquet_data = vec![]; + let mut writer = ArrowWriter::try_new(&mut parquet_data, batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + + let schema = Arc::new(Schema::new(vec![Field::new( + "binary", + dictionary_type(ArrowDataType::Utf8), + false, + )])); + let options = ArrowReaderOptions::new().with_schema(Arc::clone(&schema)); + let reader = + ParquetRecordBatchReaderBuilder::try_new_with_options(Bytes::from(parquet_data), options) + .unwrap() + .with_batch_size(2) + .build() + .unwrap(); + + let batches = reader.collect::<std::result::Result<Vec<_>, _>>().unwrap(); + assert_eq!(batches.len(), 4); + let dictionary_values = batches + .iter() + .map(|batch| { + Arc::clone( + batch + .column(0) + .as_dictionary::<arrow::datatypes::Int32Type>() + .values(), + ) + }) + .collect::<Vec<_>>(); + assert!(Arc::ptr_eq(&dictionary_values[0], &dictionary_values[1])); + assert!(!Arc::ptr_eq(&dictionary_values[1], &dictionary_values[2])); + assert!(Arc::ptr_eq(&dictionary_values[2], &dictionary_values[3])); + assert_eq!( + dictionary_values[0].as_string::<i32>(), + &StringArray::from(vec!["one", "two"]) + ); + assert_eq!( + dictionary_values[2].as_string::<i32>(), + &StringArray::from(vec!["three", "four"]) + ); +} + +#[test] +fn test_binary_dictionary_rejects_invalid_utf8() { + let file = write_parquet_from_iter(vec![( + "binary", + Arc::new(BinaryArray::from(vec![ + b"valid".as_ref(), + b"\xDE\x00\xFF".as_ref(), + b"valid".as_ref(), + ])) as ArrayRef, + )]); + let schema = Arc::new(Schema::new(vec![Field::new( + "binary", + dictionary_type(ArrowDataType::Utf8), + false, + )])); + let options = ArrowReaderOptions::new().with_schema(schema); + let mut reader = ParquetRecordBatchReaderBuilder::try_new_with_options(file, options) + .unwrap() + .build() + .unwrap(); + + let error = reader.next().unwrap().unwrap_err(); + assert!(error.to_string().contains("non UTF-8 data"), "{error}"); +} + +#[test] +fn test_plain_binary_as_utf8_view_dictionary() { + let values = Arc::new(BinaryArray::from(vec![ + b"one".as_ref(), + b"two".as_ref(), + b"one".as_ref(), + ])) as ArrayRef; + let batch = RecordBatch::try_from_iter(vec![("binary", values)]).unwrap(); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .build(); + let mut parquet_data = vec![]; + let mut writer = ArrowWriter::try_new(&mut parquet_data, batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + + let data_type = dictionary_type(ArrowDataType::Utf8View); + let schema = Arc::new(Schema::new(vec![Field::new( + "binary", + data_type.clone(), + false, + )])); + let options = ArrowReaderOptions::new().with_schema(schema); + let mut reader = + ParquetRecordBatchReaderBuilder::try_new_with_options(Bytes::from(parquet_data), options) + .unwrap() + .build() + .unwrap(); + + let batch = reader.next().unwrap().unwrap(); + assert_eq!(batch.column(0).data_type(), &data_type); + let dictionary = batch + .column(0) + .as_dictionary::<arrow::datatypes::Int32Type>(); + assert_eq!(dictionary.keys().values().as_ref(), &[0, 1, 0]); + assert_eq!( + dictionary.values().as_string_view(), + &StringViewArray::from(vec!["one", "two"]) + ); +} + +#[test] +fn test_plain_binary_dictionary_rejects_invalid_utf8() { + let values = Arc::new(BinaryArray::from(vec![ + b"valid".as_ref(), + b"\xDE\x00\xFF".as_ref(), + b"valid".as_ref(), + ])) as ArrayRef; + let batch = RecordBatch::try_from_iter(vec![("binary", values)]).unwrap(); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .build(); + let mut parquet_data = vec![]; + let mut writer = ArrowWriter::try_new(&mut parquet_data, batch.schema(), Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + + let schema = Arc::new(Schema::new(vec![Field::new( + "binary", + dictionary_type(ArrowDataType::Utf8), + false, + )])); + let options = ArrowReaderOptions::new().with_schema(schema); + let mut reader = + ParquetRecordBatchReaderBuilder::try_new_with_options(Bytes::from(parquet_data), options) + .unwrap() + .build() + .unwrap(); + + let error = reader.next().unwrap().unwrap_err(); + assert!(error.to_string().contains("non UTF-8 data"), "{error}"); +} + #[test] #[should_panic(expected = "Invalid UTF8 sequence at")] fn test_read_non_utf8_binary_as_utf8() {
