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-12028-d3b09aafc731a6e7032653ade09911b4115a7933 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit b1614b863108ffd4f7c879bae0fa4ef032648498 Author: xudong.w <[email protected]> AuthorDate: Tue Nov 3 02:18:50 2026 +0000 fix(parquet): copy Decimal/Float16 column chunk statistics instead of aliasing the written values (#12028) # Which issue does this PR close? - Closes #12027. # Rationale for this change Since #10364 the Arrow writer hands `FixedLenByteArray` values to the column writer as `split_to` slices of one `Bytes` buffer per batch. The column writer keeps its running min/max as clones of the written values, which for byte-array types is a refcount bump, and when the column chunk is closed `truncate_statistics` only rebuilt min/max for types that may be truncated. Decimal and Float16 are exempt from truncation, so their chunk statistics went into `ColumnChunkMetaData` still pointing into the batch buffer. Every closed row group of such a column kept one or two batch-sized buffers (128 KiB each with 8192-row batches) alive for as long as the `ParquetMetaData` returned by `close()` lived, while `memory_size()` reported 16 bytes per value. See the issue for the full chain and the production impact (about 1 GiB of RSS per 10 GB written through DataFusion, which retains the metadata of every written file). # What changes are included in this PR? - `truncate_statistics` now always rebuilds `BYTE_ARRAY` / `FIXED_LEN_BYTE_ARRAY` min/max from a copy of their bytes. `can_truncate_value` now only decides the truncation length passed to `truncate_min_value` / `truncate_max_value` (`None` for Decimal and Float16), so those types are copied but never shortened. - The rebuilt statistics keep every other field of the incoming statistics (null, distinct and NaN counts, the deprecated and backwards-compatible flags) through a crate-private `ValueStatistics::with_min_max`; exactness becomes `was exact && !truncated`. Previously the rebuilt statistics were created from scratch with `ValueStatistics::new(.., sort_order().is_signed())`. That was equivalent for the unsigned types that reached this path, but Decimal and Float16 have a signed sort order, and reusing it would have set `is_min_max_deprecated` and dropped `min_value` / `max_value` from the footer. The thrift output is unchanged for all types. - Regression test: writes FLBA decimals sliced out of one `Bytes` buffer and asserts that the column chunk statistics do not point into it and that the deprecated / backwards-compatible flags are unchanged. It fails on `main` and passes with this change. It would be useful to backport this to the 59.x and 60.x patch lines, since the aliasing exists since 59.0.0. # Are these changes tested? Yes. `cargo test -p parquet --lib` passes (1487 tests, including the existing truncation / Decimal / Float16 statistics tests) and `cargo clippy -p parquet --all-targets --all-features -- -D warnings` is clean. The allocator-counting reproducer from #12027, rebuilt against this branch (64 batches x 8192 `Decimal128(38, 8)` rows written through `ArrowWriter`, only the `ParquetMetaData` kept after `close()`): | row groups | `metadata.memory_size()` | live heap after `close()`, parquet 60.1.0 | live heap after `close()`, this PR | |---|---|---|---| | 512 (1024 rows each) | 341 KB | 8.73 MB | 366 KB | | 16 (4 batches each) | 12 KB | 4.21 MB | 12.7 KB | # Are there any user-facing changes? No API changes. Column chunk statistics for Decimal and Float16 columns no longer retain the buffers the values were written from. --- parquet/src/column/writer/mod.rs | 138 ++++++++++++++++++++++++++------------- parquet/src/file/statistics.rs | 5 ++ 2 files changed, 99 insertions(+), 44 deletions(-) diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index 179153894d..9d896dce01 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -1430,60 +1430,57 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { } /// Truncate the min and max values that will be written to a data page - /// header or column chunk Statistics + /// header or column chunk Statistics. + /// + /// Binary statistics are always rebuilt from a copy of their bytes, even when they are not + /// truncated, so the returned [`Statistics`] never alias the buffers the values were written + /// from. Columns whose values must not be truncated (see [`Self::can_truncate_value`]) are + /// copied without being shortened. fn truncate_statistics(&self, statistics: Statistics) -> Statistics { - let backwards_compatible_min_max = self.descr.sort_order().is_signed(); + let truncation_length = self + .can_truncate_value() + .then(|| self.props.statistics_truncate_length()) + .flatten(); match statistics { - 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(), - ); - let (max, did_truncate_max) = self.truncate_max_value( - self.props.statistics_truncate_length(), - stats.max_bytes_opt().unwrap(), - ); - Statistics::ByteArray( - ValueStatistics::new( - Some(min.into()), - Some(max.into()), - stats.distinct_count(), - stats.null_count_opt(), - backwards_compatible_min_max, - ) - .with_max_is_exact(!did_truncate_max) - .with_min_is_exact(!did_truncate_min), - ) + Statistics::ByteArray(stats) if stats._internal_has_min_max_set() => { + Statistics::ByteArray(self.copy_and_truncate_min_max(stats, truncation_length)) } - Statistics::FixedLenByteArray(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(), - ); - let (max, did_truncate_max) = self.truncate_max_value( - self.props.statistics_truncate_length(), - stats.max_bytes_opt().unwrap(), - ); + Statistics::FixedLenByteArray(stats) if stats._internal_has_min_max_set() => { Statistics::FixedLenByteArray( - ValueStatistics::new( - Some(min.into()), - Some(max.into()), - stats.distinct_count(), - stats.null_count_opt(), - backwards_compatible_min_max, - ) - .with_max_is_exact(!did_truncate_max) - .with_min_is_exact(!did_truncate_min), + self.copy_and_truncate_min_max(stats, truncation_length), ) } stats => stats, } } + /// Returns `stats` with min and max copied into their own buffers, truncated to + /// `truncation_length` bytes if one is given. Every other field is kept as is. + /// + /// Values handed to [`Self::write_batch`] may be slices of a larger shared buffer (the Arrow + /// writer slices all `FixedLenByteArray` values of a batch out of one allocation), and the + /// running min/max are clones of those values. Copying here keeps the column chunk + /// statistics, which outlive the write, from pinning those buffers. + fn copy_and_truncate_min_max<T>( + &self, + stats: ValueStatistics<T>, + truncation_length: Option<usize>, + ) -> ValueStatistics<T> + where + T: ParquetValueType + From<Vec<u8>>, + { + let (min, did_truncate_min) = + self.truncate_min_value(truncation_length, stats.min_bytes_opt().unwrap()); + let (max, did_truncate_max) = + self.truncate_max_value(truncation_length, stats.max_bytes_opt().unwrap()); + let min_is_exact = stats.min_is_exact() && !did_truncate_min; + let max_is_exact = stats.max_is_exact() && !did_truncate_max; + stats + .with_min_max(Some(min.into()), Some(max.into())) + .with_min_is_exact(min_is_exact) + .with_max_is_exact(max_is_exact) + } + /// Adds data page. /// Data page is either buffered in case of dictionary encoding or written directly. /// @@ -4757,6 +4754,59 @@ mod tests { } } + #[test] + fn test_decimal_statistics_do_not_alias_written_values() { + // See https://github.com/apache/arrow-rs/issues/12027 + // + // The Arrow writer slices all FixedLenByteArray values of a batch out of one shared + // buffer. Decimal and Float16 statistics are never truncated and used to be stored as + // clones of the written values, so the column chunk statistics kept every such buffer + // alive for as long as the file metadata existed. + let page_writer = get_test_page_writer(); + let mut writer = get_test_decimals_column_writer::<FixedLenByteArrayType>( + page_writer, + 0, + 0, + Default::default(), + ); + + // Four 16-byte big-endian non-negative values in ascending order, in one buffer + let arena = Bytes::from((0..64u8).collect::<Vec<_>>()); + let values: Vec<FixedLenByteArray> = (0..4) + .map(|i| ByteArray::from(arena.slice(i * 16..(i + 1) * 16)).into()) + .collect(); + writer.write_batch(&values, None, None).unwrap(); + let r = writer.close().unwrap(); + drop(values); + + let statistics = r.metadata.statistics().unwrap(); + // Copying must not change how the statistics are written: Decimal has a signed sort + // order, so both min_value/max_value and the deprecated min/max are emitted + assert!(!statistics.is_min_max_deprecated()); + assert!(statistics.is_min_max_backwards_compatible()); + let Statistics::FixedLenByteArray(stats) = statistics else { + panic!("expecting Statistics::FixedLenByteArray"); + }; + let min = stats.min_bytes_opt().unwrap(); + let max = stats.max_bytes_opt().unwrap(); + assert_eq!(min, &arena[..16]); + assert_eq!(max, &arena[48..]); + + // The statistics must own their bytes rather than point into the written buffer + let arena_range = arena.as_ptr_range(); + assert!( + !arena_range.contains(&min.as_ptr()), + "min aliases the written buffer" + ); + assert!( + !arena_range.contains(&max.as_ptr()), + "max aliases the written buffer" + ); + + assert!(stats.min_is_exact()); + assert!(stats.max_is_exact()); + } + #[test] fn test_decimal_byte_array_min_max_no_statistics_truncation() { // See https://github.com/apache/arrow-rs/issues/11073 diff --git a/parquet/src/file/statistics.rs b/parquet/src/file/statistics.rs index b7d2206da5..c94fc92266 100644 --- a/parquet/src/file/statistics.rs +++ b/parquet/src/file/statistics.rs @@ -591,6 +591,11 @@ impl<T> ValueStatistics<T> { } } + /// Returns these statistics with `min` and `max` replaced and every other field kept. + pub(crate) fn with_min_max(self, min: Option<T>, max: Option<T>) -> Self { + Self { min, max, ..self } + } + /// Set whether the stored `min` field represents the exact /// minimum, or just a bound on the minimum value. ///
