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

commit 6759872cabb7c581c9daa9d9a7f52492e2cedd70
Author: RIchard Baah <[email protected]>
AuthorDate: Thu Nov 5 14:54:30 2026 +0000

    perf(arrow-row): avoid encoding oversized dictionary values (#12043)
    
    ## Why
    
    Closes #11901.
    
    The benchmark coverage for this change is in the consolidated benchmark
    PR #12054.
    
    `RowConverter` currently encodes every value in a dictionary before
    converting a batch. For an 8,192-row slice backed by a large dictionary,
    the work therefore scales with the retained values array rather than the
    rows being converted.
    
    ```text
    DictionaryArray
      keys:     8,192 rows --------+
                                   +--> RowConverter --> 8,192 encoded rows
      values: 1,000,000 strings ---+
    
    before: encode all 1,000,000 values --> look up 8,192 keys
    after:  gather 8,192 row values      --> encode the row-aligned values
    ```
    
    This is a smaller follow-up to #11904. It avoids the hash map and
    per-row remap used there, and uses the benchmark crossover requested in
    
[review](https://github.com/apache/arrow-rs/pull/11904#discussion_r4393788975)
    to keep small and dense dictionaries on the existing path.
    
    ## What changed
    
    When a dictionary has at least 32K values and its values array is at
    least four times longer than the input, gather one value per row and
    encode that row-aligned array. All other dictionaries keep the existing
    dictionary-key lookup path.
    
    The benchmark sweep put the crossover between 20K and 24.6K values. The
    32K / 4x guard is deliberately conservative.
    
    ## Results
    
    The [hosted exact-ref
    run](https://github.com/apache/arrow-rs/pull/12043#issuecomment-6606029732)
    is flat at 10K, 1.3x faster at 32K, 3.45x at 100K, and about 33x at 1M.
    Row decoding is unchanged, and peak memory drops from 56.8 MiB to 29.5
    MiB.
    
    ## Test coverage
    
    One test checks row equality and round-trip decoding for a sliced
    dictionary with repeated high keys and nulls.
---
 arrow-row/src/lib.rs | 133 ++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 132 insertions(+), 1 deletion(-)

diff --git a/arrow-row/src/lib.rs b/arrow-row/src/lib.rs
index 851ba5ca41..abe1b6320f 100644
--- a/arrow-row/src/lib.rs
+++ b/arrow-row/src/lib.rs
@@ -163,6 +163,7 @@ use arrow_array::cast::*;
 use arrow_array::types::{ArrowDictionaryKeyType, ByteArrayType, ByteViewType};
 use arrow_array::*;
 use arrow_buffer::{ArrowNativeType, Buffer, OffsetBuffer, ScalarBuffer};
+use arrow_data::transform::MutableArrayData;
 use arrow_schema::*;
 use variable::{decode_binary_view, decode_string_view};
 
@@ -176,6 +177,11 @@ mod list;
 mod run;
 mod variable;
 
+// Gathering copies one value per row before encoding, so only use it when the
+// dictionary is large and sparse enough for skipping unused values to pay off.
+const DICTIONARY_GATHER_MIN_VALUES: usize = 32 * 1024;
+const DICTIONARY_GATHER_RATIO: usize = 4;
+
 /// Converts [`ArrayRef`] columns into a [row-oriented](self) format.
 ///
 /// *Note: The encoding of the row format may change from release to release.*
@@ -762,7 +768,24 @@ impl Codec {
         match self {
             Codec::Stateless => Ok(Encoder::Stateless),
             Codec::Dictionary(converter, nulls) => {
-                let values = array.as_any_dictionary().values().clone();
+                let dictionary = array.as_any_dictionary();
+                let values = dictionary.values();
+                if values.len() >= DICTIONARY_GATHER_MIN_VALUES
+                    && values.len() >= 
dictionary.len().saturating_mul(DICTIONARY_GATHER_RATIO)
+                {
+                    let values = downcast_dictionary_array! {
+                        array => gather_dictionary_values(array),
+                        _ => unreachable!(),
+                    };
+                    // Gathering can overflow nested offsets or run ends even 
when
+                    // encoding the original dictionary values would succeed.
+                    if let Ok(values) = values {
+                        let rows = converter.convert_columns(&[values])?;
+                        return Ok(Encoder::DictionaryRows(rows, nulls.row()));
+                    }
+                }
+
+                let values = Arc::clone(values);
                 let rows = converter.convert_columns(&[values])?;
                 Ok(Encoder::Dictionary(rows, nulls.row()))
             }
@@ -898,6 +921,8 @@ enum Encoder<'a> {
     Stateless,
     /// The encoding of the child array and the encoding of a null row
     Dictionary(Rows, Row<'a>),
+    /// The encoding of the flattened dictionary array and a null row
+    DictionaryRows(Rows, Row<'a>),
     /// The row encoding of the child arrays and the encoding of a null row
     ///
     /// It is necessary to encode to a temporary [`Rows`] to avoid serializing
@@ -1880,6 +1905,17 @@ fn row_lengths(cols: &[ArrayRef], encoders: &[Encoder]) 
-> LengthTracker {
                     _ => unreachable!(),
                 }
             }
+            Encoder::DictionaryRows(values, null) => {
+                downcast_dictionary_array! {
+                    array => tracker.push_variable(
+                        array.keys().iter().enumerate().map(|(row, key)| match 
key {
+                            Some(_) => values.row_len(row),
+                            None => null.data.len(),
+                        })
+                    ),
+                    _ => unreachable!(),
+                }
+            }
             Encoder::Struct(rows, null) => {
                 let array = as_struct_array(array);
                 if rows.num_rows() > 0 {
@@ -2108,6 +2144,12 @@ fn encode_column(
                 _ => unreachable!()
             }
         }
+        Encoder::DictionaryRows(values, nulls) => {
+            downcast_dictionary_array! {
+                column => encode_dictionary_rows(data, offsets, column, 
values, nulls),
+                _ => unreachable!()
+            }
+        }
         Encoder::Struct(rows, null) => {
             fn struct_encode_helper<const NO_CHILD_FIELDS: bool>(
                 array: &StructArray,
@@ -2249,6 +2291,36 @@ pub fn encode_dictionary_values<K: 
ArrowDictionaryKeyType>(
     }
 }
 
+fn gather_dictionary_values<K: ArrowDictionaryKeyType>(
+    array: &DictionaryArray<K>,
+) -> Result<ArrayRef, ArrowError> {
+    let data = array.values().to_data();
+    let mut mutable = MutableArrayData::new(vec![&data], false, array.len());
+    for key in array.keys() {
+        let index = key.map(|key| key.as_usize()).unwrap_or_default();
+        mutable.try_extend(0, index, index + 1)?;
+    }
+    Ok(make_array(mutable.freeze()))
+}
+
+fn encode_dictionary_rows<K: ArrowDictionaryKeyType>(
+    data: &mut [u8],
+    offsets: &mut [usize],
+    column: &DictionaryArray<K>,
+    values: &Rows,
+    null: &Row<'_>,
+) {
+    for (row, (offset, key)) in 
offsets.iter_mut().skip(1).zip(column.keys()).enumerate() {
+        let value = match key {
+            Some(_) => values.row(row).data,
+            None => null.data,
+        };
+        let end_offset = *offset + value.len();
+        data[*offset..end_offset].copy_from_slice(value);
+        *offset = end_offset;
+    }
+}
+
 macro_rules! decode_primitive_helper {
     ($t:ty, $rows:ident, $data_type:ident, $options:ident) => {
         Arc::new(decode_primitive::<$t>($rows, $data_type, $options))
@@ -3282,6 +3354,65 @@ mod tests {
         assert!(rows.row(3) < rows.row(0));
     }
 
+    #[test]
+    fn test_sparse_dictionary_values() {
+        let values = StringArray::from_iter_values((0..100_000).map(|i| 
format!("value-{i}")));
+        let keys = Int32Array::from(vec![
+            Some(0),
+            Some(99_999),
+            None,
+            Some(7),
+            Some(99_999),
+            Some(3),
+        ]);
+        let dictionary = DictionaryArray::<Int32Type>::try_new(keys, 
Arc::new(values)).unwrap();
+        let sparse = Arc::new(dictionary.slice(1, 4)) as ArrayRef;
+
+        let expected = Arc::new(DictionaryArray::<Int32Type>::from_iter([
+            Some("value-99999"),
+            None,
+            Some("value-7"),
+            Some("value-99999"),
+        ])) as ArrayRef;
+
+        let converter =
+            
RowConverter::new(vec![SortField::new(sparse.data_type().clone())]).unwrap();
+        let actual_rows = converter.convert_columns(&[sparse]).unwrap();
+        let expected_rows = 
converter.convert_columns(&[Arc::clone(&expected)]).unwrap();
+
+        for (actual, expected) in actual_rows.iter().zip(&expected_rows) {
+            assert_eq!(actual, expected);
+        }
+        let decoded = converter.convert_rows(&actual_rows).unwrap();
+        dictionary_eq(&decoded[0], &expected);
+    }
+
+    #[test]
+    fn test_sparse_dictionary_gather_overflow_falls_back() {
+        let inner = RunArray::<Int16Type>::try_new(
+            &PrimitiveArray::from(vec![1_i16]),
+            &Int32Array::from(vec![1]),
+        )
+        .unwrap();
+        let values = RunArray::<Int64Type>::try_new(
+            &PrimitiveArray::from(vec![
+                (DICTIONARY_GATHER_MIN_VALUES * DICTIONARY_GATHER_RATIO) as 
i64,
+            ]),
+            &inner,
+        )
+        .unwrap();
+        let keys = Int32Array::from(vec![0; DICTIONARY_GATHER_MIN_VALUES]);
+        let dictionary = DictionaryArray::<Int32Type>::try_new(keys, 
Arc::new(values)).unwrap();
+
+        let input = Arc::new(dictionary) as ArrayRef;
+        let converter = 
RowConverter::new(vec![SortField::new(input.data_type().clone())]).unwrap();
+        let rows = converter.convert_columns(&[input]).unwrap();
+
+        assert_eq!(rows.num_rows(), DICTIONARY_GATHER_MIN_VALUES);
+        let first = rows.row(0);
+        assert!(rows.iter().all(|row| row == first));
+    }
+
     #[test]
     fn test_from_binary_shared_buffer() {
         let converter = 
RowConverter::new(vec![SortField::new(DataType::Binary)]).unwrap();

Reply via email to