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-12122-b8d7b68bfc327e7c10ecf01c6d6476a5bdc36370
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit da51f1468a52e411f3eec31e7bd929ddd2f5ab88
Author: Chinmay Shrivastava <[email protected]>
AuthorDate: Thu Nov 12 18:46:41 2026 +0000

    Use non-null value counts for Parquet dictionary caches (#12122)
    
    # Which issue does this PR close?
    
    Closes #12115.
    
    # Rationale for this change
    
    The Parquet Arrow writer counts all rows when deciding whether to create
    a dictionary cache, even though only selected non-null values are
    encoded. This can allocate a cache for a batch containing mostly or
    entirely null values.
    
    Nulls can come from dictionary keys, dictionary values, or a parent
    array masking a child value.
    
    # What changes are included in this PR?
    
    Pass the complete selection’s non-null value count through the internal
    write_gather interface and use it for the dictionary-cache decision.
    
    The count covers the enclosing write batch, preserving profitable
    caching when the writer splits it into smaller mini-batches. Existing
    caches remain available for reuse across sparse and all-null writes.
    
    # Are these changes tested?
    
    Regression tests cover sliced inputs, null keys, null dictionary values,
    parent-masked values, and partially or entirely null selections. A dense
    control checks that mini-batching does not disable a profitable cache.
    The memory regression fails against the original implementation and
    passes with this change.
    
    Retained `ArrowWriter::memory_size()` bytes after one write to a fresh
    writer:
    
    | Rows | Dictionary values | Input | Before | After |
    |---:|---:|---|---:|---:|
    | 8,192 | 4,096 | Dense | 372,778 | 372,778 |
    | 8,192 | 4,096 | 50% null | 340,010 | 340,010 |
    | 8,192 | 4,096 | Approximately 99% null | 38,890 | 6,122 |
    | 8,192 | 4,096 | All null | 32,768 | 0 |
    | 131,072 | 65,536 | Approximately 99% null | 620,983 | 96,695 |
    | 131,072 | 65,536 | All null | 524,456 | 168 |
    
    The affected cases avoid 32 KiB or 512 KiB of new cache storage, and the
    large 99%-null and all-null writes were about 10% and 52% faster, with
    the dense control about 2% slower.
    
    # Are there any user-facing changes?
    
    No.
    
    AI assistance was used for implementation, regression tests, independent
    review, and validation.
    
    ---------
    
    Co-authored-by: JonSnow1807 <[email protected]>
---
 parquet/src/arrow/arrow_writer/byte_array.rs | 15 +++--
 parquet/src/arrow/arrow_writer/mod.rs        | 92 ++++++++++++++++++++++++++++
 parquet/src/column/writer/encoder.rs         | 21 ++++++-
 parquet/src/column/writer/mod.rs             |  7 ++-
 4 files changed, 124 insertions(+), 11 deletions(-)

diff --git a/parquet/src/arrow/arrow_writer/byte_array.rs 
b/parquet/src/arrow/arrow_writer/byte_array.rs
index b60ac10467..e9656c38f0 100644
--- a/parquet/src/arrow/arrow_writer/byte_array.rs
+++ b/parquet/src/arrow/arrow_writer/byte_array.rs
@@ -805,14 +805,17 @@ impl ColumnValueEncoder for ByteArrayEncoder {
         unreachable!("should call write_gather instead")
     }
 
-    fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> 
Result<()> {
+    fn write_gather(
+        &mut self,
+        values: &Self::Values,
+        indices: &[usize],
+        num_values_in_batch: usize,
+    ) -> Result<()> {
         if let DataType::Dictionary(key, value) = values.data_type() {
             let dictionary = values.as_any_dictionary().values();
-            if self
-                .dict_encoder
-                .as_ref()
-                .is_some_and(|encoder| 
encoder.use_dictionary_cache(dictionary, values.len()))
-            {
+            if self.dict_encoder.as_ref().is_some_and(|encoder| {
+                encoder.use_dictionary_cache(dictionary, num_values_in_batch)
+            }) {
                 return downcast_dict_values_op!(
                     key,
                     value,
diff --git a/parquet/src/arrow/arrow_writer/mod.rs 
b/parquet/src/arrow/arrow_writer/mod.rs
index c6318fdfaa..928a6fad41 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -2731,6 +2731,98 @@ mod tests {
         assert_eq!(write_string_dictionaries(&arrays), 5);
     }
 
+    fn dictionary_writer_memory_size(array: ArrayRef, batch_size: usize) -> 
usize {
+        let schema = Arc::new(Schema::new(vec![Field::new(
+            "col",
+            array.data_type().clone(),
+            true,
+        )]));
+        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
+        let props = WriterProperties::builder()
+            .set_write_batch_size(batch_size)
+            .build();
+        let mut writer = ArrowWriter::try_new(Vec::new(), schema, 
Some(props)).unwrap();
+        writer.write(&batch).unwrap();
+        writer.memory_size()
+    }
+
+    #[test]
+    fn arrow_writer_dictionary_cache_ignores_null_rows() {
+        let values: ArrayRef = Arc::new(StringArray::from(vec![
+            Some("value"),
+            None,
+            Some("unused"),
+            Some("also unused"),
+        ]));
+
+        for non_null in [0, 2] {
+            let valid = |i| (3..3 + non_null).contains(&i);
+            let keys = Int32Array::from_iter((0..10).map(|i| 
valid(i).then_some(0)));
+            let null_keys: ArrayRef =
+                Arc::new(DictionaryArray::new(keys, values.clone()).slice(1, 
8));
+            let keys = Int32Array::from_iter_values((0..10).map(|i| 
i32::from(!valid(i))));
+            let null_values: ArrayRef =
+                Arc::new(DictionaryArray::new(keys, values.clone()).slice(1, 
8));
+            let child: ArrayRef = Arc::new(DictionaryArray::new(
+                Int32Array::from(vec![0; 10]),
+                values.clone(),
+            ));
+            let parent: ArrayRef = Arc::new(
+                StructArray::new(
+                    vec![Arc::new(Field::new(
+                        "item",
+                        child.data_type().clone(),
+                        true,
+                    ))]
+                    .into(),
+                    vec![child],
+                    Some(NullBuffer::from_iter((0..10).map(valid))),
+                )
+                .slice(1, 8),
+            );
+
+            for array in [null_keys, null_values, parent] {
+                let plain_type = match array.data_type() {
+                    DataType::Struct(_) => DataType::Struct(
+                        vec![Arc::new(Field::new("item", DataType::Utf8, 
true))].into(),
+                    ),
+                    _ => DataType::Utf8,
+                };
+                let plain = cast(&array, &plain_type).unwrap();
+                // Neither input should retain a cache for only zero or two 
encoded values.
+                assert_eq!(
+                    dictionary_writer_memory_size(array, 2),
+                    dictionary_writer_memory_size(plain, 2)
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn arrow_writer_dictionary_cache_counts_rows_across_mini_batches() {
+        let values: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c", 
"d"]));
+        let array: ArrayRef = Arc::new(DictionaryArray::new(
+            Int32Array::from(vec![
+                Some(0),
+                Some(1),
+                None,
+                Some(2),
+                Some(3),
+                Some(0),
+                Some(1),
+                Some(2),
+                Some(3),
+            ]),
+            values,
+        ));
+        let plain = cast(&array, &DataType::Utf8).unwrap();
+        // Eight rows justify a four-slot cache, even with only two rows per 
mini-batch.
+        assert_eq!(
+            dictionary_writer_memory_size(array, 2),
+            dictionary_writer_memory_size(plain, 2) + 4 * 
std::mem::size_of::<u64>()
+        );
+    }
+
     #[test]
     fn roundtrip_bytes() {
         // define schema
diff --git a/parquet/src/column/writer/encoder.rs 
b/parquet/src/column/writer/encoder.rs
index 110c5a498b..8582d12a98 100644
--- a/parquet/src/column/writer/encoder.rs
+++ b/parquet/src/column/writer/encoder.rs
@@ -84,7 +84,19 @@ pub trait ColumnValueEncoder {
     fn write(&mut self, values: &Self::Values, offset: usize, len: usize) -> 
Result<()>;
 
     /// Write the values at the indexes in `indices` to this 
[`ColumnValueEncoder`]
-    fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> 
Result<()>;
+    ///
+    /// `num_values_in_batch` is the number of non-null values in the whole 
write. The
+    /// column writer may split one write into several calls of this method 
(for
+    /// example by `write_batch_size` or the page size limit), so it can be 
larger than
+    /// `indices.len()`. It is the length of the write's full index list, 
which has one
+    /// entry per non-null value. The byte array encoder uses it to decide 
whether a
+    /// dictionary cache pays off.
+    fn write_gather(
+        &mut self,
+        values: &Self::Values,
+        indices: &[usize],
+        num_values_in_batch: usize,
+    ) -> Result<()>;
 
     /// Returns the largest `k` such that the first `k` values in
     /// `values[offset..offset + len]` encode to at most `byte_budget`
@@ -310,7 +322,12 @@ impl<T: DataType> ColumnValueEncoder for 
ColumnValueEncoderImpl<T> {
         self.write_slice(slice)
     }
 
-    fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> 
Result<()> {
+    fn write_gather(
+        &mut self,
+        values: &Self::Values,
+        indices: &[usize],
+        _num_values_in_batch: usize,
+    ) -> Result<()> {
         self.num_values += indices.len();
         let slice: Vec<_> = indices.iter().map(|idx| 
values[*idx].clone()).collect();
         self.write_slice(&slice)
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index 3c5e52a7f2..cbc10d2827 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -1125,9 +1125,10 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, 
E> {
         }
 
         match value_indices {
-            Some(indices) => {
-                let indices = &indices[values_offset..values_offset + 
values_to_write];
-                self.encoder.write_gather(values, indices)?;
+            Some(all_indices) => {
+                let indices = &all_indices[values_offset..values_offset + 
values_to_write];
+                self.encoder
+                    .write_gather(values, indices, all_indices.len())?;
             }
             None => self.encoder.write(values, values_offset, 
values_to_write)?,
         }

Reply via email to