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

commit 9a82c0e2b347b72828a388ada95da43614446e47
Author: Emily Matheys <[email protected]>
AuthorDate: Sat Nov 7 15:58:17 2026 +0000

    perf: Add a dictionary cache for parquet dict types (#11982)
    
    # Rationale for this change
    
    <!--
    Why are you proposing this change? If this is already explained clearly
    in the
    issue then this section is not needed. Explaining clearly why changes
    are proposed
    helps reviewers understand your changes and offer better suggestions for
    fixes.
    
    Please try to explain the problem you are trying to solve in terms of
    the user-visible
    behavior, rather than the implementation.
    -->
    
    Since we already get a dictionary type, we can just calculate hash once
    per entry, until the dictionary provider changes.
    
    # What changes are included in this PR?
    
    <!--
    There is no need to duplicate the description in the issue here but it
    is
    sometimes worth providing a summary of the individual changes in this
    PR.
    -->
    
    Use a Weak ref (so we don't hold the dict alive), and encode each entry
    only once, the moment the dict changes, clear the current hashes, should
    be a huge improvement to perf.
    Made some private functions use slices directly.
    
    # Are these changes tested?
    
    <!--
    We typically require tests for all PRs in order to:
    1. Prevent the code from being accidentally broken by subsequent changes
    2. Serve as another way to document the expected behavior of the code
    
    If tests are not included in your PR, please explain why (for example,
    are they
    covered by existing tests, if so identify these tests)?
    
    If this PR claims a performance improvement, please include evidence
    such as
    benchmark results.
    
    DO NOT simply paste a list of commands ran to verify the code; this is
    what our
    CI is for and it pollutes the PR. ONLY explain if testing was included
    with this
    PR, or why it wasn't.
    -->
    
    Yes.
    Local benchmark results:
      | Benchmark | main (ms) | branch (ms) | Change |
      |---|---:|---:|---:|
      | `string/default` | 87.09 | 86.32 | -0.9% |
      | `string/parquet_2` | 106.94 | 103.09 | -3.6% |
      | `string_dictionary/default` | 45.38 | 45.55 | +0.4% |
      | `string_dictionary/parquet_2` | 55.00 | 54.40 | -1.1% |
    | `string_dictionary_low_cardinality_100/default` | 18.57 | 8.97 |
    -51.7% |
    | `string_dictionary_low_cardinality_100/parquet_2` | 18.46 | 8.96 |
    -51.5% |
      | `string_non_null/default` | 92.34 | 91.97 | -0.4% |
      | `string_non_null/parquet_2` | 117.59 | 115.82 | -1.5% |
      | `string_ree_of_dict/default` | 45.84 | 37.10 | -19.1% |
      | `string_ree_of_dict/parquet_2` | 45.86 | 37.13 | -19.0% |
    
    # Are there any significant user-facing changes?
    
    <!--
    Significant user-facing changes include:
    - Breaking public API change
    - Significant change to existing functionality (e.g. function returns
    something different)
    
    These need to be explicitly called out to ensure we have proper
    documentation if
    required and to ensure we follow proper semantic versioning.
    
    DO NOT restate the changes of this PR; if a bug was fixed and already
    explained
    above, we don't need this to be restated as a user-facing change.
    -->
    
    No
---
 parquet/src/arrow/arrow_writer/byte_array.rs | 337 ++++++++++++++++++++-------
 parquet/src/arrow/arrow_writer/mod.rs        |  88 ++++++-
 2 files changed, 345 insertions(+), 80 deletions(-)

diff --git a/parquet/src/arrow/arrow_writer/byte_array.rs 
b/parquet/src/arrow/arrow_writer/byte_array.rs
index bef9255c52..b60ac10467 100644
--- a/parquet/src/arrow/arrow_writer/byte_array.rs
+++ b/parquet/src/arrow/arrow_writer/byte_array.rs
@@ -20,13 +20,16 @@ use crate::geospatial::statistics::GeospatialStatistics;
 use crate::schema::types::ColumnDescPtr;
 use crate::util::bit_util::num_required_bits;
 use crate::util::prefix::common_prefix_length;
-use arrow_array::types::ByteArrayType;
+use arrow_array::cast::AsArray;
+use arrow_array::types::{ArrowDictionaryKeyType, ByteArrayType};
 use arrow_array::{
-    Array, ArrayAccessor, BinaryArray, BinaryViewArray, DictionaryArray, 
FixedSizeBinaryArray,
-    GenericByteArray, LargeBinaryArray, LargeStringArray, StringArray, 
StringViewArray,
+    Array, ArrayAccessor, ArrayRef, BinaryArray, BinaryViewArray, 
DictionaryArray,
+    FixedSizeBinaryArray, GenericByteArray, LargeBinaryArray, 
LargeStringArray, StringArray,
+    StringViewArray, TypedDictionaryArray,
 };
 use arrow_buffer::{ArrowNativeType, Buffer};
 use arrow_schema::DataType;
+use std::sync::{Arc, Weak};
 
 macro_rules! downcast_dict_impl {
     ($array:ident, $key:ident, $val:ident, $op:expr $(, $arg:expr)*) => {{
@@ -55,6 +58,31 @@ macro_rules! downcast_dict_op {
     };
 }
 
+macro_rules! downcast_dict_values_op {
+    ($key_type:expr, $value_type:expr, $array:ident, $op:expr $(, $arg:expr)*) 
=> {
+        match $value_type.as_ref() {
+            DataType::Utf8 => downcast_dict_op!($key_type, StringArray, 
$array, $op$(, $arg)*),
+            DataType::LargeUtf8 => {
+                downcast_dict_op!($key_type, LargeStringArray, $array, $op$(, 
$arg)*)
+            }
+            DataType::Utf8View => {
+                downcast_dict_op!($key_type, StringViewArray, $array, $op$(, 
$arg)*)
+            }
+            DataType::Binary => downcast_dict_op!($key_type, BinaryArray, 
$array, $op$(, $arg)*),
+            DataType::LargeBinary => {
+                downcast_dict_op!($key_type, LargeBinaryArray, $array, $op$(, 
$arg)*)
+            }
+            DataType::BinaryView => {
+                downcast_dict_op!($key_type, BinaryViewArray, $array, $op$(, 
$arg)*)
+            }
+            DataType::FixedSizeBinary(_) => {
+                downcast_dict_op!($key_type, FixedSizeBinaryArray, $array, 
$op$(, $arg)*)
+            }
+            d => unreachable!("cannot downcast {} dictionary value to byte 
array", d),
+        }
+    };
+}
+
 macro_rules! downcast_op {
     ($data_type:expr, $array:ident, $op:expr $(, $arg:expr)*) => {
         match $data_type {
@@ -72,26 +100,9 @@ macro_rules! downcast_op {
             DataType::BinaryView => {
                 
$op($array.as_any().downcast_ref::<BinaryViewArray>().unwrap()$(, $arg)*)
             }
-            DataType::Dictionary(key, value) => match value.as_ref() {
-                DataType::Utf8 => downcast_dict_op!(key, StringArray, $array, 
$op$(, $arg)*),
-                DataType::LargeUtf8 => {
-                    downcast_dict_op!(key, LargeStringArray, $array, $op$(, 
$arg)*)
-                }
-                DataType::Utf8View => {
-                    downcast_dict_op!(key, StringViewArray, $array, $op$(, 
$arg)*)
-                }
-                DataType::Binary => downcast_dict_op!(key, BinaryArray, 
$array, $op$(, $arg)*),
-                DataType::LargeBinary => {
-                    downcast_dict_op!(key, LargeBinaryArray, $array, $op$(, 
$arg)*)
-                }
-                DataType::BinaryView => {
-                    downcast_dict_op!(key, BinaryViewArray, $array, $op$(, 
$arg)*)
-                }
-                DataType::FixedSizeBinary(_) => {
-                    downcast_dict_op!(key, FixedSizeBinaryArray, $array, 
$op$(, $arg)*)
-                }
-                d => unreachable!("cannot downcast {} dictionary value to byte 
array", d),
-            },
+            DataType::Dictionary(key, value) => {
+                downcast_dict_values_op!(key, value, $array, $op$(, $arg)*)
+            }
             d => unreachable!("cannot downcast {} to byte array", d),
         }
     };
@@ -163,7 +174,7 @@ impl FallbackEncoder {
     }
 
     /// Encode `values` to the in-progress page
-    fn encode<T>(&mut self, values: T, indices: impl ExactSizeIterator<Item = 
usize>)
+    fn encode<T>(&mut self, values: T, indices: &[usize])
     where
         T: ArrayAccessor + Copy,
         T::Item: AsRef<[u8]>,
@@ -171,7 +182,7 @@ impl FallbackEncoder {
         self.num_values += indices.len();
         match &mut self.encoder {
             FallbackEncoderImpl::Plain { buffer } => {
-                for idx in indices {
+                for &idx in indices {
                     let value = values.value(idx);
                     let value = value.as_ref();
                     buffer.extend_from_slice((value.len() as u32).as_bytes());
@@ -180,7 +191,7 @@ impl FallbackEncoder {
                 }
             }
             FallbackEncoderImpl::DeltaLength { buffer, lengths } => {
-                for idx in indices {
+                for &idx in indices {
                     let value = values.value(idx);
                     let value = value.as_ref();
                     lengths.put(&[value.len() as i32]).unwrap();
@@ -194,7 +205,7 @@ impl FallbackEncoder {
                 prefix_lengths,
                 suffix_lengths,
             } => {
-                for idx in indices {
+                for &idx in indices {
                     let value = values.value(idx);
                     let value = value.as_ref();
 
@@ -289,7 +300,7 @@ impl FallbackEncoder {
 }
 
 /// Maximum size of a value that can be inlined in the hash table
-const SHORT_VALUE_LEN: usize = size_of::<u64>() - 1;
+const SHORT_VALUE_LEN: usize = std::mem::size_of::<u64>() - 1;
 
 /// Entry in the hash table
 #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
@@ -315,7 +326,7 @@ struct Entry {
 ///   | 1 bit unset  | offset in dict {63 bits}                   |
 ///   +--------------+--------------------------------------------+
 ///
-/// the inline view contain it's length to avoid having another field for 
length in the entry
+/// the inline view contain its length to avoid having another field for 
length in the entry
 /// since if the hashes are the same, most probably the length will be the 
same, so we can do the indirection check
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 struct OffsetOrInlineView(u64);
@@ -564,18 +575,40 @@ struct DictEncoder {
     interner: ByteArrayInterner,
     indices: Vec<u64>,
     variable_length_bytes: i64,
+    /// The interned index of each value of the last arrow dictionary encoded
+    dictionary_cache: Option<DictionaryCache>,
+}
+
+/// The interned index of each value of an arrow dictionary, so each value is 
hashed once
+/// rather than once per row that references it
+#[derive(Debug)]
+struct DictionaryCache {
+    /// The dictionary's values, to identify the dictionary in later batches. 
A weak reference,
+    /// so the values aren't kept alive, while their allocation can't be 
reused by another
+    /// dictionary
+    values: Weak<dyn Array>,
+    /// The interned index of each value, or [`DictionaryCache::NOT_INTERNED`]
+    interned: Vec<u64>,
+}
+
+impl DictionaryCache {
+    const NOT_INTERNED: u64 = u64::MAX;
+
+    fn is_for(&self, dictionary: &ArrayRef) -> bool {
+        std::ptr::addr_eq(self.values.as_ptr(), Arc::as_ptr(dictionary))
+    }
 }
 
 impl DictEncoder {
     /// Encode `values` to the in-progress page
-    fn encode<T>(&mut self, values: T, indices: impl ExactSizeIterator<Item = 
usize>) -> Result<()>
+    fn encode<T>(&mut self, values: T, indices: &[usize]) -> Result<()>
     where
         T: ArrayAccessor + Copy,
         T::Item: AsRef<[u8]>,
     {
         self.indices.reserve(indices.len());
 
-        for idx in indices {
+        for &idx in indices {
             let value = values.value(idx);
             let interned = self.interner.intern(value.as_ref())?;
             self.indices.push(interned);
@@ -585,13 +618,74 @@ impl DictEncoder {
         Ok(())
     }
 
+    /// Whether to encode the rows of an arrow dictionary with `dictionary` as 
its values and
+    /// `num_rows` rows with [`Self::encode_dictionary`]
+    fn use_dictionary_cache(&self, dictionary: &ArrayRef, num_rows: usize) -> 
bool {
+        // A new cache has a slot per dictionary value, which only pays off if 
the values are
+        // referenced by enough rows
+        dictionary.len() <= num_rows
+            || self
+                .dictionary_cache
+                .as_ref()
+                .is_some_and(|cache| cache.is_for(dictionary))
+    }
+
+    /// Encode the rows of an arrow dictionary at `indices` to the in-progress 
page
+    fn encode_dictionary<'a, K, V>(
+        &mut self,
+        values: TypedDictionaryArray<'a, K, V>,
+        indices: &[usize],
+        dictionary: &ArrayRef,
+    ) -> Result<()>
+    where
+        K: ArrowDictionaryKeyType,
+        &'a V: ArrayAccessor,
+        <&'a V as ArrayAccessor>::Item: AsRef<[u8]>,
+    {
+        let cache = match &mut self.dictionary_cache {
+            Some(cache) if cache.is_for(dictionary) => cache,
+            cache => cache.insert(DictionaryCache {
+                values: Arc::downgrade(dictionary),
+                interned: vec![DictionaryCache::NOT_INTERNED; 
dictionary.len()],
+            }),
+        };
+
+        let keys = values.keys().values();
+        let dictionary_values = values.values();
+        self.indices.reserve(indices.len());
+        for &idx in indices {
+            let key = keys[idx].as_usize();
+
+            // Shadowed for lifetime reasons
+            let value = dictionary_values.value(key);
+            let value = value.as_ref();
+
+            let mut interned = cache.interned[key];
+            if interned == DictionaryCache::NOT_INTERNED {
+                interned = self.interner.intern(value)?;
+                cache.interned[key] = interned;
+            }
+            self.indices.push(interned);
+            self.variable_length_bytes += value.len() as i64;
+        }
+
+        Ok(())
+    }
+
     fn bit_width(&self) -> u8 {
         let length = self.interner.num_unique_values();
         num_required_bits(length.saturating_sub(1) as u64)
     }
 
     fn estimated_memory_size(&self) -> usize {
-        self.interner.estimated_memory_size() + self.indices.capacity() * 
std::mem::size_of::<u64>()
+        let dictionary_cache_size = self
+            .dictionary_cache
+            .as_ref()
+            .map(|cache| cache.interned.capacity() * 
std::mem::size_of::<u64>())
+            .unwrap_or_default();
+        self.interner.estimated_memory_size()
+            + self.indices.capacity() * std::mem::size_of::<u64>()
+            + dictionary_cache_size
     }
 
     fn estimated_data_page_size(&self) -> usize {
@@ -712,13 +806,26 @@ impl ColumnValueEncoder for ByteArrayEncoder {
     }
 
     fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> 
Result<()> {
-        downcast_op!(
-            values.data_type(),
-            values,
-            encode,
-            indices.iter().copied(),
-            self
-        )
+        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()))
+            {
+                return downcast_dict_values_op!(
+                    key,
+                    value,
+                    values,
+                    encode_with_dictionary_cache,
+                    indices,
+                    dictionary,
+                    self
+                );
+            }
+        }
+
+        downcast_op!(values.data_type(), values, encode, indices, self)
     }
 
     fn count_values_within_byte_budget_gather(
@@ -892,18 +999,64 @@ impl ColumnValueEncoder for ByteArrayEncoder {
 /// Encodes the provided `values` and `indices` to `encoder`
 ///
 /// This is a free function so it can be used with `downcast_op!`
-fn encode<T, I>(values: T, indices: I, encoder: &mut ByteArrayEncoder) -> 
Result<()>
+fn encode<T>(values: T, indices: &[usize], encoder: &mut ByteArrayEncoder) -> 
Result<()>
+where
+    T: ArrayAccessor + Copy,
+    T::Item: Copy + Ord + AsRef<[u8]>,
+{
+    update_statistics(values, indices, encoder);
+
+    // While a dictionary is in use the filter is populated from its distinct 
values in
+    // `flush_dict_page`, so each value is hashed once rather than once per 
row.
+    match &mut encoder.dict_encoder {
+        Some(dict_encoder) => dict_encoder.encode(values, indices),
+        None => {
+            if let Some(bloom_filter) = &mut encoder.bloom_filter {
+                for &idx in indices {
+                    bloom_filter.insert(values.value(idx).as_ref());
+                }
+            }
+            encoder.fallback.encode(values, indices);
+
+            Ok(())
+        }
+    }
+}
+
+/// Encodes the rows of an arrow dictionary at `indices` to `encoder`, which 
must have a
+/// dictionary encoder
+///
+/// This is a free function so it can be used with `downcast_dict_values_op!`
+fn encode_with_dictionary_cache<'a, K, V>(
+    values: TypedDictionaryArray<'a, K, V>,
+    indices: &[usize],
+    dictionary: &ArrayRef,
+    encoder: &mut ByteArrayEncoder,
+) -> Result<()>
+where
+    K: ArrowDictionaryKeyType,
+    V: Sync + Send,
+    &'a V: ArrayAccessor,
+    <&'a V as ArrayAccessor>::Item: Copy + Ord + Default + AsRef<[u8]>,
+{
+    update_statistics(values, indices, encoder);
+    encoder
+        .dict_encoder
+        .as_mut()
+        .expect("dictionary encoder")
+        .encode_dictionary(values, indices, dictionary)
+}
+
+/// Updates the statistics of `encoder` with the values at `indices`
+fn update_statistics<T>(values: T, indices: &[usize], encoder: &mut 
ByteArrayEncoder)
 where
     T: ArrayAccessor + Copy,
     T::Item: Copy + Ord + AsRef<[u8]>,
-    I: ExactSizeIterator<Item = usize> + Clone,
 {
     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(), encoder.is_decimal)
-        {
+            update_geo_stats_accumulator(accumulator.as_mut(), values, 
indices);
+        } else if let Some((min, max)) = compute_min_max(values, indices, 
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
@@ -927,22 +1080,6 @@ where
             }
         }
     }
-
-    // While a dictionary is in use the filter is populated from its distinct 
values in
-    // `flush_dict_page`, so each value is hashed once rather than once per 
row.
-    match &mut encoder.dict_encoder {
-        Some(dict_encoder) => dict_encoder.encode(values, indices),
-        None => {
-            if let Some(bloom_filter) = &mut encoder.bloom_filter {
-                for idx in indices.clone() {
-                    bloom_filter.insert(values.value(idx).as_ref());
-                }
-            }
-            encoder.fallback.encode(values, indices);
-
-            Ok(())
-        }
-    }
 }
 
 /// Upper bound on any single value's byte length in a view array.
@@ -971,7 +1108,7 @@ fn count_within_budget_views(
     max_value_len: usize,
 ) -> usize {
     // Each plain-encoded BYTE_ARRAY value carries a 4-byte length prefix, so
-    // the budget is compared against `value_len + size_of::<u32>()` — the
+    // the budget is compared against `value_len + std::mem::size_of::<u32>()` 
— the
     // bytes actually written to the page, not just the payload.
     //
     // Stage 1: O(1) conservative bound. View arrays have no prefix-sum
@@ -1057,21 +1194,17 @@ fn is_greater(is_decimal: bool, a: &[u8], b: &[u8]) -> 
bool {
 /// 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)>
+fn compute_min_max<T>(array: T, valid: &[usize], is_decimal: bool) -> 
Option<(T::Item, T::Item)>
 where
     T: ArrayAccessor,
     T::Item: Copy + Ord + AsRef<[u8]>,
 {
-    let first_idx = valid.next()?;
+    let (&first_idx, valid) = valid.split_first()?;
 
     let first_val = array.value(first_idx);
     let mut min = first_val;
     let mut max = first_val;
-    for idx in valid {
+    for &idx in valid {
         let val = array.value(idx);
         if is_greater(is_decimal, min.as_ref(), val.as_ref()) {
             min = val;
@@ -1084,18 +1217,64 @@ where
 }
 
 /// Updates geospatial statistics for the provided array and indices
-fn update_geo_stats_accumulator<T>(
-    bounder: &mut dyn GeoStatsAccumulator,
-    array: T,
-    valid: impl Iterator<Item = usize>,
-) where
+fn update_geo_stats_accumulator<T>(bounder: &mut dyn GeoStatsAccumulator, 
array: T, valid: &[usize])
+where
     T: ArrayAccessor,
     T::Item: Copy + Ord + AsRef<[u8]>,
 {
-    if bounder.is_valid() {
-        for idx in valid {
-            let val = array.value(idx);
-            bounder.update_wkb(val.as_ref());
-        }
+    if !bounder.is_valid() {
+        return;
+    }
+
+    for &idx in valid {
+        let val = array.value(idx);
+        bounder.update_wkb(val.as_ref());
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use arrow_array::{DictionaryArray, Int32Array, StringArray};
+
+    fn string_values(n: usize) -> ArrayRef {
+        Arc::new(StringArray::from_iter_values(
+            (0..n).map(|i| format!("v{i}")),
+        ))
+    }
+
+    #[test]
+    fn use_dictionary_cache_new_dictionary() {
+        let encoder = DictEncoder::default();
+        let dictionary = string_values(3);
+
+        // A new cache only pays off with at least one row per dictionary value
+        assert!(encoder.use_dictionary_cache(&dictionary, 4));
+        assert!(encoder.use_dictionary_cache(&dictionary, 3));
+        assert!(!encoder.use_dictionary_cache(&dictionary, 2));
+        assert!(!encoder.use_dictionary_cache(&dictionary, 0));
+    }
+
+    #[test]
+    fn use_dictionary_cache_cached_dictionary() {
+        let mut encoder = DictEncoder::default();
+        let dictionary = string_values(3);
+        let array = DictionaryArray::new(Int32Array::from(vec![0, 1, 2]), 
dictionary.clone());
+        encoder
+            .encode_dictionary(
+                array.downcast_dict::<StringArray>().unwrap(),
+                &[0, 1, 2],
+                &dictionary,
+            )
+            .unwrap();
+
+        // An existing cache is reused however few rows reference it
+        assert!(encoder.use_dictionary_cache(&dictionary, 1));
+        assert!(encoder.use_dictionary_cache(&dictionary, 0));
+
+        // Equal values in a different allocation do not use the existing cache
+        let other = string_values(3);
+        assert!(!encoder.use_dictionary_cache(&other, 2));
+        assert!(encoder.use_dictionary_cache(&other, 3));
     }
 }
diff --git a/parquet/src/arrow/arrow_writer/mod.rs 
b/parquet/src/arrow/arrow_writer/mod.rs
index c734d70b79..026387acf6 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -2323,7 +2323,7 @@ mod tests {
     use arrow::error::Result as ArrowResult;
     use arrow::util::data_gen::create_random_array;
     use arrow::util::pretty::pretty_format_batches;
-    use arrow::{array::*, buffer::Buffer};
+    use arrow::{array::*, buffer::Buffer, compute::cast};
     use arrow_buffer::{IntervalMonthDayNano, NullBuffer, OffsetBuffer};
     use arrow_schema::Fields;
     use arrow_select::concat::concat;
@@ -2622,6 +2622,92 @@ mod tests {
         writer.into_inner().unwrap()
     }
 
+    /// Writes each of `arrays` as a batch, in several mini-batches, checks 
they round trip,
+    /// and returns the number of values in the column's dictionary page
+    fn write_string_dictionaries(arrays: &[ArrayRef]) -> usize {
+        let schema = Arc::new(Schema::new(vec![Field::new(
+            "col",
+            arrays[0].data_type().clone(),
+            true,
+        )]));
+        let props = 
WriterProperties::builder().set_write_batch_size(2).build();
+        let mut file = vec![];
+        let mut writer = ArrowWriter::try_new(&mut file, schema.clone(), 
Some(props)).unwrap();
+        for array in arrays {
+            let batch = RecordBatch::try_new(schema.clone(), 
vec![array.clone()]).unwrap();
+            writer.write(&batch).unwrap();
+        }
+        writer.close().unwrap();
+
+        let reader = 
SerializedFileReader::new(Bytes::from(file.clone())).unwrap();
+        let mut pages = reader
+            .get_row_group(0)
+            .unwrap()
+            .get_column_page_reader(0)
+            .unwrap();
+        let dictionary_page = pages.get_next_page().unwrap().unwrap();
+        assert!(matches!(dictionary_page, Page::DictionaryPage { .. }));
+
+        let expected: Vec<&dyn Array> = arrays.iter().map(|a| 
a.as_ref()).collect();
+        let expected = concat(&expected).unwrap();
+        let actual = read_column(file);
+        assert_eq!(
+            cast(&actual, &DataType::Utf8).unwrap().as_ref(),
+            cast(&expected, &DataType::Utf8).unwrap().as_ref()
+        );
+
+        dictionary_page.num_values() as usize
+    }
+
+    #[test]
+    fn arrow_writer_string_dictionary_cache_reused_for_same_values() {
+        // "dup" is in the dictionary twice, and values are both short enough 
to be inlined and not
+        let shared: ArrayRef = Arc::new(StringArray::from(vec![
+            "a",
+            "bb",
+            "longer than eight bytes",
+            "dup",
+            "dup",
+        ]));
+        let keys = Int32Array::from(vec![
+            Some(0),
+            Some(1),
+            None,
+            Some(2),
+            Some(3),
+            Some(4),
+            Some(0),
+        ]);
+        let first = DictionaryArray::new(keys, shared.clone());
+        // Same values `Arc` as `first`, so encoded with the cache built for 
`first`. Sliced,
+        // with fewer rows than values, so the cache is only used because it 
is reused
+        let keys = Int32Array::from(vec![Some(4), Some(4), Some(1), None, 
Some(2), Some(0)]);
+        let second = DictionaryArray::new(keys, shared).slice(1, 4);
+
+        let arrays: Vec<ArrayRef> = vec![Arc::new(first), Arc::new(second)];
+        // a, bb, longer than eight bytes, dup
+        assert_eq!(write_string_dictionaries(&arrays), 4);
+    }
+
+    #[test]
+    fn arrow_writer_string_dictionary_cache_replaced_for_new_values() {
+        let first_values: ArrayRef = Arc::new(StringArray::from(vec!["a", 
"bb", "ccc"]));
+        let first = DictionaryArray::new(Int32Array::from(vec![0, 1, 2, 0]), 
first_values.clone());
+        // A different values `Arc`, sharing some values with `first` at other 
keys, so a
+        // stale cache would map keys to the wrong values
+        let second_values: ArrayRef = Arc::new(StringArray::from(vec!["zz", 
"a", "new value!!"]));
+        let second = DictionaryArray::new(
+            Int32Array::from(vec![Some(2), Some(1), None, Some(0), Some(1)]),
+            second_values,
+        );
+        // Back to `first`'s values, whose cache has since been replaced
+        let third = DictionaryArray::new(Int32Array::from(vec![2, 1, 0]), 
first_values);
+
+        let arrays: Vec<ArrayRef> = vec![Arc::new(first), Arc::new(second), 
Arc::new(third)];
+        // a, bb, ccc, zz, new value!!
+        assert_eq!(write_string_dictionaries(&arrays), 5);
+    }
+
     #[test]
     fn roundtrip_bytes() {
         // define schema

Reply via email to