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-11092-6f3d92253941ac2d72572c44ab174656b5f5bc13 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit d58a0fce35b67836ac9b2e20a7efe47a584e0a86 Author: DeviousCardi <[email protected]> AuthorDate: Tue Oct 20 06:03:08 2026 +0000 Fix incorrect Decimal statistics for BYTE_ARRAY columns written via ArrowColumnWriter (#11092) ## Summary Fixes #11073. Writing a Decimal-logical-type column backed by an Arrow `BinaryArray`/`ByteArray` through `ArrowColumnWriter` produced wrong min/max column statistics, because the statistics computation used plain unsigned lexicographic `Ord` comparison on the raw two's-complement-encoded bytes. The direct `parquet::file::writer` column-writer path (and the `FixedSizeBinaryArray` path) already handled this correctly via a signed, decimal-aware comparator. ## Changes - `parquet/src/column/writer/mod.rs`: widened `compare_greater_byte_array_decimals` to `pub(crate)`; added a shared `is_decimal_descr()` helper (used by both this file's `compare_greater` and the Arrow writer) to avoid duplicating the decimal-type-detection check. - `parquet/src/arrow/arrow_writer/byte_array.rs`: `ByteArrayEncoder` now detects decimal columns at construction and uses the signed comparator for both the running min/max computation and the cross-batch min/max merge. - `truncate_statistics`/`can_truncate_value` (`column/writer/mod.rs`): `BYTE_ARRAY` decimal columns are now excluded from statistics truncation, matching the existing guard already in place for `FIXED_LEN_BYTE_ARRAY` decimals — truncating a decimal's two's-complement bytes with unsigned `increment()` could otherwise reintroduce a corrupted bound for long decimals. - Two regression tests added, based on the issue's repro and a truncation-specific case. ## Test plan - [x] `cargo test -p parquet --lib arrow_writer` — 166 passed - [x] `cargo test -p parquet --lib column::writer` — 112 passed - [x] `cargo clippy -p parquet --lib --all-targets` — clean - [x] `cargo build -p parquet` — clean 🤖 Generated with [Claude Code](https://claude.com/claude-code) Written by Codex. --------- Co-authored-by: Claude Sonnet 5 <[email protected]> Co-authored-by: Ed Seidl <[email protected]> --- parquet/src/arrow/arrow_writer/byte_array.rs | 40 +++++++++-- parquet/src/arrow/arrow_writer/mod.rs | 102 +++++++++++++++++++++++++++ parquet/src/column/writer/mod.rs | 79 +++++++++++++++++---- 3 files changed, 202 insertions(+), 19 deletions(-) diff --git a/parquet/src/arrow/arrow_writer/byte_array.rs b/parquet/src/arrow/arrow_writer/byte_array.rs index 3a5a561218..70687874b8 100644 --- a/parquet/src/arrow/arrow_writer/byte_array.rs +++ b/parquet/src/arrow/arrow_writer/byte_array.rs @@ -20,6 +20,7 @@ use crate::bloom_filter::Sbbf; use crate::column::writer::encoder::{ ColumnValueEncoder, DataPageValues, DictionaryPage, create_bloom_filter, }; +use crate::column::writer::{compare_greater_byte_array_decimals, is_decimal_descr}; use crate::data_type::{AsBytes, ByteArray, Int32Type}; use crate::encodings::encoding::{DeltaBitPackEncoder, Encoder}; use crate::encodings::rle::RleEncoder; @@ -430,6 +431,7 @@ pub struct ByteArrayEncoder { bloom_filter: Option<Sbbf>, bloom_filter_target_fpp: f64, geo_stats_accumulator: Option<Box<dyn GeoStatsAccumulator>>, + is_decimal: bool, } impl ColumnValueEncoder for ByteArrayEncoder { @@ -459,6 +461,8 @@ impl ColumnValueEncoder for ByteArrayEncoder { let geo_stats_accumulator = try_new_geo_stats_accumulator(descr); + let is_decimal = is_decimal_descr(descr.get_basic_info()); + Ok(Self { fallback, statistics_enabled, @@ -468,6 +472,7 @@ impl ColumnValueEncoder for ByteArrayEncoder { min_value: None, max_value: None, geo_stats_accumulator, + is_decimal, }) } @@ -667,18 +672,28 @@ where if encoder.statistics_enabled != EnabledStatistics::None { if let Some(accumulator) = encoder.geo_stats_accumulator.as_mut() { update_geo_stats_accumulator(accumulator.as_mut(), values, indices.clone()); - } else if let Some((min, max)) = compute_min_max(values, indices.clone()) { + } else if let Some((min, max)) = + compute_min_max(values, indices.clone(), encoder.is_decimal) + { // Compare before copying: `write_gather` runs once per // mini-batch, and a byte-budgeted mini-batch of large values can // hold a single value, so an unconditional copy here would // duplicate every value once for `min` and once for `max`. let min = min.as_ref(); - if encoder.min_value.as_ref().is_none_or(|m| m.data() > min) { + if encoder + .min_value + .as_ref() + .is_none_or(|m| is_greater(encoder.is_decimal, m.data(), min)) + { encoder.min_value = Some(min.to_vec().into()); } let max = max.as_ref(); - if encoder.max_value.as_ref().is_none_or(|m| m.data() < max) { + if encoder + .max_value + .as_ref() + .is_none_or(|m| is_greater(encoder.is_decimal, max, m.data())) + { encoder.max_value = Some(max.to_vec().into()); } } @@ -798,12 +813,23 @@ fn count_within_budget_offsets<T: ByteArrayType>( n } +/// Returns `true` if `a > b`. +#[inline] +fn is_greater(is_decimal: bool, a: &[u8], b: &[u8]) -> bool { + if is_decimal { + compare_greater_byte_array_decimals(a, b) + } else { + a > b + } +} + /// Computes the min and max for the provided array and indices /// /// This is a free function so it can be used with `downcast_op!` fn compute_min_max<T>( array: T, mut valid: impl Iterator<Item = usize>, + is_decimal: bool, ) -> Option<(T::Item, T::Item)> where T: ArrayAccessor, @@ -816,8 +842,12 @@ where let mut max = first_val; for idx in valid { let val = array.value(idx); - min = min.min(val); - max = max.max(val); + if is_greater(is_decimal, min.as_ref(), val.as_ref()) { + min = val; + } + if is_greater(is_decimal, val.as_ref(), max.as_ref()) { + max = val; + } } Some((min, max)) } diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs index 09b092b35f..d4df999393 100644 --- a/parquet/src/arrow/arrow_writer/mod.rs +++ b/parquet/src/arrow/arrow_writer/mod.rs @@ -4623,4 +4623,106 @@ mod tests { ); assert_eq!(parquet_schema.column(1).path().string(), "row.b"); } + + /// Regression test for https://github.com/apache/arrow-rs/issues/11073 + /// + /// This checks that the `ArrowColumnWriter` path produces the same min/max + /// statistics as writing the column directly with the low-level + /// `SerializedFileWriter` API, for both `BinaryArray` (the buggy case) + /// and `FixedSizeBinaryArray` (which already worked correctly). + #[test] + fn test_decimal_byte_array_statistics_signed_comparison() { + use crate::basic::{LogicalType, Repetition, Type as PhysicalType}; + use crate::data_type::{ByteArray, ByteArrayType}; + use crate::schema::types::Type as SchemaType; + + // 1-byte two's-complement decimal values: -1, 0, 1 + const VALUES: [&[u8]; 3] = [&[0xffu8], &[0x00], &[0x01]]; + + fn new_file(physical: PhysicalType) -> SerializedFileWriter<Vec<u8>> { + let mut field = SchemaType::primitive_type_builder("value", physical) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::decimal(0, 2))) + .with_precision(2) + .with_scale(0); + if physical == PhysicalType::FIXED_LEN_BYTE_ARRAY { + field = field.with_length(1); + } + let root = SchemaType::group_type_builder("root") + .with_fields(vec![Arc::new(field.build().unwrap())]) + .build() + .unwrap(); + SerializedFileWriter::new(Vec::new(), Arc::new(root), Default::default()).unwrap() + } + + fn read_minmax(file: Vec<u8>) -> (i8, i8) { + let reader = SerializedFileReader::new(Bytes::from(file)).unwrap(); + let metadata = reader.metadata(); + assert_eq!(metadata.file_metadata().num_rows(), 3); + let stats = metadata + .row_group(0) + .column(0) + .statistics() + .expect("missing statistics"); + ( + stats.min_bytes_opt().unwrap()[0] as i8, + stats.max_bytes_opt().unwrap()[0] as i8, + ) + } + + fn direct_parquet() -> Vec<u8> { + let mut file = new_file(PhysicalType::BYTE_ARRAY); + let mut group = file.next_row_group().unwrap(); + let mut column = group.next_column().unwrap().unwrap(); + let values = VALUES + .iter() + .map(|v| ByteArray::from(v.to_vec())) + .collect::<Vec<_>>(); + column + .typed::<ByteArrayType>() + .write_batch(&values, None, None) + .unwrap(); + column.close().unwrap(); + group.close().unwrap(); + file.into_inner().unwrap() + } + + fn arrow_bounds(mut file: SerializedFileWriter<Vec<u8>>, array: ArrayRef) -> Vec<u8> { + let field = Field::new("value", array.data_type().clone(), false); + let schema = Arc::new(Schema::new(vec![field.clone()])); + let factory = ArrowRowGroupWriterFactory::new(&file, schema); + let mut writer: ArrowColumnWriter = factory.create_column_writers(0).unwrap().remove(0); + let leaf = compute_leaves(&field, &array).unwrap().remove(0); + writer.write(&leaf).unwrap(); + let mut group = file.next_row_group().unwrap(); + writer + .close() + .unwrap() + .append_to_row_group(&mut group) + .unwrap(); + group.close().unwrap(); + file.into_inner().unwrap() + } + + fn arrow_binary() -> Vec<u8> { + let file = new_file(PhysicalType::BYTE_ARRAY); + let array: ArrayRef = Arc::new(BinaryArray::from_vec(VALUES.to_vec())); + arrow_bounds(file, array) + } + + fn arrow_fixed_size_binary() -> Vec<u8> { + let file = new_file(PhysicalType::FIXED_LEN_BYTE_ARRAY); + let array: ArrayRef = + Arc::new(FixedSizeBinaryArray::try_from_iter(VALUES.into_iter()).unwrap()); + arrow_bounds(file, array) + } + + let direct = read_minmax(direct_parquet()); + let fixed = read_minmax(arrow_fixed_size_binary()); + let binary = read_minmax(arrow_binary()); + + assert_eq!(direct, (-1, 1), "incorrect direct Parquet stats"); + assert_eq!(fixed, (-1, 1), "incorrect Arrow FixedSizeBinaryArray stats"); + assert_eq!(binary, (-1, 1), "incorrect Arrow BinaryArray stats"); + } } diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index e5a66e913f..923f0a4599 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -1352,14 +1352,13 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { // from that of FIXED_LEN_BYTE_ARRAY sort order. // So truncation of those types could lead to inaccurate min/max statistics Type::FIXED_LEN_BYTE_ARRAY - if !matches!( - self.descr.logical_type_ref(), - Some(&LogicalType::Decimal { .. } | &LogicalType::Float16) - ) => + if !is_decimal_descr(self.descr.get_basic_info()) + && !matches!(self.descr.logical_type_ref(), Some(&LogicalType::Float16)) => { true } - Type::BYTE_ARRAY => true, + // As with FIXED_LEN_BYTE_ARRAY, do not truncate Decimal values + Type::BYTE_ARRAY if !is_decimal_descr(self.descr.get_basic_info()) => true, // Truncation only applies for fba/binary physical types _ => false, } @@ -1435,7 +1434,9 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { fn truncate_statistics(&self, statistics: Statistics) -> Statistics { let backwards_compatible_min_max = self.descr.sort_order().is_signed(); match statistics { - Statistics::ByteArray(stats) if stats._internal_has_min_max_set() => { + Statistics::ByteArray(stats) + if (stats._internal_has_min_max_set() && self.can_truncate_value()) => + { let (min, did_truncate_min) = self.truncate_min_value( self.props.statistics_truncate_length(), stats.min_bytes_opt().unwrap(), @@ -1949,13 +1950,7 @@ fn compare_greater<T: ParquetValueType>(basic_type_info: &BasicTypeInfo, a: &T, { return compare_greater_f16(a.as_bytes(), b.as_bytes()); } - Type::FIXED_LEN_BYTE_ARRAY | Type::BYTE_ARRAY - if matches!(basic_type_info.converted_type(), ConvertedType::DECIMAL) - || matches!( - basic_type_info.logical_type_ref(), - Some(LogicalType::Decimal(_)) - ) => - { + Type::FIXED_LEN_BYTE_ARRAY | Type::BYTE_ARRAY if is_decimal_descr(basic_type_info) => { return compare_greater_byte_array_decimals(a.as_bytes(), b.as_bytes()); } @@ -2005,8 +2000,18 @@ fn compare_greater_f16(a: &[u8], b: &[u8]) -> bool { a.total_cmp(&b) == Ordering::Greater } +/// Returns `true` if the column described by `basic_type_info` is a Decimal column +#[inline] +pub(crate) fn is_decimal_descr(basic_type_info: &BasicTypeInfo) -> bool { + basic_type_info.converted_type() == ConvertedType::DECIMAL + || matches!( + basic_type_info.logical_type_ref(), + Some(LogicalType::Decimal(_)) + ) +} + /// Signed comparison of bytes arrays -fn compare_greater_byte_array_decimals(a: &[u8], b: &[u8]) -> bool { +pub(crate) fn compare_greater_byte_array_decimals(a: &[u8], b: &[u8]) -> bool { let a_length = a.len(); let b_length = b.len(); @@ -4614,6 +4619,52 @@ mod tests { } } + #[test] + fn test_decimal_byte_array_min_max_no_statistics_truncation() { + // See https://github.com/apache/arrow-rs/issues/11073 + let page_writer = get_test_page_writer(); + + // Truncate at 1 byte -- far shorter than either encoded value below. + let builder = WriterProperties::builder().set_statistics_truncate_length(Some(1)); + let props = Arc::new(builder.build()); + let mut writer = get_test_decimals_column_writer::<ByteArrayType>(page_writer, 0, 0, props); + + // Two's-complement, big-endian encodings of 200 and -200 (2 bytes each). + // Naive unsigned byte-wise truncation to 1 byte followed by an unsigned + // increment of the max value would corrupt these: + // max: truncate([0x00, 0xC8], 1) -> [0x00], increment -> [0x01], + // which decodes to 1 -- far less than the true max of 200. + let positive_200 = vec![0x00u8, 0xC8u8]; + let negative_200 = vec![0xFFu8, 0x38u8]; + + let data = vec![ + ByteArray::from(positive_200.clone()), + ByteArray::from(negative_200.clone()), + ]; + writer.write_batch(&data, None, None).unwrap(); + writer.flush_data_pages().unwrap(); + + let r = writer.close().unwrap(); + assert_eq!(2, r.rows_written); + + let stats = r.metadata.statistics().expect("statistics"); + if let Statistics::ByteArray(stats) = stats { + // Decimal columns must never be truncated, regardless of + // `statistics_truncate_length`. + assert!(stats.min_is_exact()); + assert!(stats.max_is_exact()); + + let min_value = stats.min_bytes_opt().unwrap(); + let max_value = stats.max_bytes_opt().unwrap(); + + // Correct signed (two's-complement) ordering: -200 < 200. + assert_eq!(negative_200, min_value); + assert_eq!(positive_200, max_value); + } else { + panic!("expecting Statistics::ByteArray"); + } + } + #[test] fn test_statistics_truncating_byte_array_default() { let page_writer = get_test_page_writer();
