jayzhan211 commented on code in PR #12059:
URL: https://github.com/apache/arrow-rs/pull/12059#discussion_r4731072117


##########
arrow-select/src/interleave.rs:
##########
@@ -312,6 +355,28 @@ fn interleave_dictionaries<K: ArrowDictionaryKeyType>(
     Ok(Arc::new(array))
 }
 
+/// Interleaves dictionary keys without copying their shared values array.
+///
+/// # Safety
+///
+/// Every dictionary's values array must be pointer-equal to `shared_values`.
+unsafe fn interleave_shared_dictionary<K: ArrowDictionaryKeyType>(
+    dictionaries: &[&DictionaryArray<K>],
+    indices: &[(usize, usize)],
+    shared_values: &ArrayRef,
+) -> Result<ArrayRef, ArrowError> {

Review Comment:
   Optional: a `debug_assert!` on the safety precondition would make a future 
caller that passes a mismatched values array fail in debug builds instead of 
building an invalid dictionary. Using `child_values_ptr_eq` keeps it valid if 
the shared check moves to buffer identity:
   
   ```diff
   @@ -5,7 +5,9 @@
   -use crate::dictionary::{merge_dictionary_values, 
should_merge_dictionary_values};
   +use crate::dictionary::{
   +    child_values_ptr_eq, merge_dictionary_values, 
should_merge_dictionary_values,
   +};
   @@ -365,6 +367,11 @@ unsafe fn interleave_shared_dictionary<K: 
ArrowDictionaryKeyType>(
        indices: &[(usize, usize)],
        shared_values: &ArrayRef,
    ) -> Result<ArrayRef, ArrowError> {
   +    debug_assert!(
   +        dictionaries
   +            .iter()
   +            .all(|dictionary| child_values_ptr_eq(dictionary.values(), 
shared_values))
   +    );
        let key_arrays: Vec<&dyn Array> = dictionaries
   ```



##########
arrow-select/src/interleave.rs:
##########
@@ -264,33 +264,76 @@ fn interleave_dictionaries<K: ArrowDictionaryKeyType>(
     let dictionaries: Vec<_> = arrays.iter().map(|x| 
x.as_dictionary::<K>()).collect();
     let (should_merge, has_overflow) =
         should_merge_dictionary_values::<K>(&dictionaries, indices.len());
-    if !should_merge {
-        return if has_overflow {
-            interleave_fallback(arrays, indices)
+    let strategy = if should_merge {
+        DictionaryInterleaveStrategy::MergeDictionaries
+    } else {
+        let first_values = dictionaries[0].values();
+        if dictionaries
+            .iter()
+            .skip(1)
+            .all(|dictionary| Arc::ptr_eq(first_values, dictionary.values()))

Review Comment:
   This only matches values in the same `Arc`, so values that share buffers 
through different `Arc`s still get concatenated. Every dictionary pair that 
arrow's own `zip` passes to `interleave` has that shape, because `zip` rebuilds 
both inputs with `make_array`: zipping two 2,048-row dictionaries that share 
one 10-value array still returns 20 values, as before this PR. `concat` outputs 
behave the same. `should_merge_dictionary_values` already compares the values 
buffers for byte and primitive types, and returning that result covers these 
inputs (1.7–2.8x faster) with no measurable cost on distinct inputs:
   
   ```diff
   --- a/arrow-select/src/dictionary.rs
   +++ b/arrow-select/src/dictionary.rs
   @@ pub(crate) fn should_merge_dictionary_values<K: ArrowDictionaryKeyType>(
   -) -> (bool, bool) {
   +) -> (bool, bool, bool) {
   @@
                if !dt.is_primitive() {
   +                let first_values = dictionaries[0].values();
                    return (
                        false,
                        K::Native::from_usize(dictionaries.iter().map(|d| 
d.values().len()).sum())
                            .is_none(),
   +                    dictionaries
   +                        .iter()
   +                        .skip(1)
   +                        .all(|d| Arc::ptr_eq(first_values, d.values())),
                    );
                }
   @@
            overflow,
   +        single_dictionary,
        )
   --- a/arrow-select/src/interleave.rs
   +++ b/arrow-select/src/interleave.rs
   @@ fn interleave_dictionaries<K: ArrowDictionaryKeyType>(
   -    let (should_merge, has_overflow) =
   +    let (should_merge, has_overflow, shared_values) =
            should_merge_dictionary_values::<K>(&dictionaries, indices.len());
   -    let strategy = if should_merge {
   +    let strategy = if shared_values {
   +        DictionaryInterleaveStrategy::SharedDictionary
   +    } else if should_merge {
            DictionaryInterleaveStrategy::MergeDictionaries
   +    } else if has_overflow {
   +        DictionaryInterleaveStrategy::Fallback
        } else {
   -        let first_values = dictionaries[0].values();
   -        if dictionaries
   -            .iter()
   -            .skip(1)
   -            .all(|dictionary| Arc::ptr_eq(first_values, 
dictionary.values()))
   -        {
   -            DictionaryInterleaveStrategy::SharedDictionary
   -        } else if has_overflow {
   -            DictionaryInterleaveStrategy::Fallback
   -        } else {
   -            DictionaryInterleaveStrategy::FallbackDictionary
   -        }
   +        DictionaryInterleaveStrategy::FallbackDictionary
        };
   ```
   
   <details><summary>Doc comment, SAFETY wording and three tests (byte, 
primitive and view values)</summary>
   
   ```diff
   --- a/arrow-select/src/dictionary.rs
   +++ b/arrow-select/src/dictionary.rs
   -/// Returns `(should_merge, has_overflow)` where:
   +/// Returns `(should_merge, has_overflow, shared_values)` where:
    /// - `should_merge`: whether dictionary values should be merged
    /// - `has_overflow`: whether the combined dictionary values would overflow 
the key type
   +/// - `shared_values`: whether every dictionary's values array has the same 
length and
   +///   buffers as the first one's, compared by buffers for byte and 
primitive values and by
   +///   `Arc` otherwise. Unlike `should_merge` this is exact, because 
`interleave` reuses the
   +///   first values array when it is set
   --- a/arrow-select/src/interleave.rs
   +++ b/arrow-select/src/interleave.rs
            DictionaryInterleaveStrategy::SharedDictionary => {
   -            // SAFETY: the strategy is selected only after verifying that 
every dictionary's
   -            // values array is pointer-equal to `dictionaries[0].values()`.
   +            // SAFETY: `should_merge_dictionary_values` verified that every 
dictionary's
   +            // values array has the same length and buffers as 
`dictionaries[0].values()`.
   @@
   -/// Every dictionary's values array must be pointer-equal to 
`shared_values`.
   +/// Every dictionary's values array must have the same length and buffers as
   +/// `shared_values`.
   @@
   -    // SAFETY: every non-null key came from a dictionary backed by 
`shared_values`.
   +    // SAFETY: every non-null key is in bounds for its own values array, 
which has the
   +    // same length as `shared_values`.
   ```
   
   ```rs
   #[test]
   fn test_interleave_dictionary_reuses_values_with_shared_buffers() {
       let values: ArrayRef = Arc::new(StringArray::from_iter_values(["a", "b", 
"c"]));
       let dictionary = DictionaryArray::<Int32Type>::new(
           Int32Array::from(vec![Some(0), None, Some(2), Some(1)]),
           values,
       );
       // An `ArrayData` round trip wraps the same values buffers in a new 
`Arc`.
       let dict_a = make_array(dictionary.slice(0, 2).to_data());
       let dict_b = make_array(dictionary.slice(2, 2).to_data());
   
       let result = interleave(&[&dict_a, &dict_b], &[(0, 0), (1, 1), (0, 1), 
(1, 0)]).unwrap();
       let result = result.as_dictionary::<Int32Type>();
   
       assert!(Arc::ptr_eq(
           result.values(),
           dict_a.as_dictionary::<Int32Type>().values()
       ));
       assert_eq!(
           result.keys(),
           &Int32Array::from(vec![Some(0), Some(1), None, Some(2)])
       );
   }
   
   #[test]
   fn test_interleave_dictionary_reuses_primitive_values_with_shared_buffers() {
       let dictionary = DictionaryArray::<Int32Type>::new(
           Int32Array::from(vec![0, 2, 1]),
           Arc::new(Int64Array::from(vec![10, 20, 30])),
       );
       let dict_a = make_array(dictionary.to_data());
       let dict_b = make_array(dictionary.to_data());
   
       let result = interleave(&[&dict_a, &dict_b], &[(1, 1), (0, 2)]).unwrap();
       let result = result.as_dictionary::<Int32Type>();
   
       assert!(Arc::ptr_eq(
           result.values(),
           dict_a.as_dictionary::<Int32Type>().values()
       ));
       assert_eq!(result.keys(), &Int32Array::from(vec![2, 1]));
   }
   
   #[test]
   fn test_interleave_dictionary_reuses_shared_view_values() {
       let values: ArrayRef = Arc::new(StringViewArray::from_iter_values(["a", 
"b", "c"]));
       let dictionary =
           DictionaryArray::<Int32Type>::new(Int32Array::from(vec![0, 2, 1]), 
Arc::clone(&values));
   
       let result = interleave(
           &[&dictionary.slice(0, 2), &dictionary.slice(1, 2)],
           &[(1, 1), (0, 0)],
       )
       .unwrap();
       let result = result.as_dictionary::<Int32Type>();
   
       assert!(Arc::ptr_eq(result.values(), &values));
       assert_eq!(result.keys(), &Int32Array::from(vec![1, 0]));
   }
   ```
   
   The first two fail on this PR's head; the view test guards the `Arc` check 
that moves into `should_merge_dictionary_values`.
   </details>
   
   <details><summary>Repro with <code>zip</code></summary>
   
   ```rs
   let values: ArrayRef = Arc::new(StringArray::from_iter_values(
       (0..10).map(|i| format!("value-{i}")),
   ));
   let a = DictionaryArray::<Int32Type>::new(
       Int32Array::from_iter_values((0..2048).map(|i| i % 10)),
       Arc::clone(&values),
   );
   let b = DictionaryArray::<Int32Type>::new(
       Int32Array::from_iter_values((0..2048).map(|i| (i * 3) % 10)),
       Arc::clone(&values),
   );
   // a fragmented mask, so `zip` calls `interleave`
   let mask = BooleanArray::from_iter((0..2048).map(|i| Some(i % 3 == 0)));
   let out = zip(&mask, &a, &b).unwrap();
   // 20 before and with this PR, 10 with the change above
   println!("{}", out.as_dictionary::<Int32Type>().values().len());
   ```
   </details>
   
   <details><summary>Benchmarks: this PR vs the change (ns, medians of 9 
interleaved rounds, Apple M-series)</summary>
   
   | input (2,048 rows unless noted) | this PR | with the change |
   |---|---:|---:|
   | two `concat` outputs, 10 Utf8 values | 1,958 | 1,080 |
   | two `concat` outputs, 1,000 Utf8 values | 2,950 | 1,067 |
   | two `make_array` round trips, 10 Int64 values | 1,950 | 1,144 |
   | two distinct dictionaries, 8 rows: Int64 / Utf8 / Utf8View values | 335 / 
297 / 226 | 341 / 301 / 231 |
   | merge path, 16 distinct dictionaries | 13,813 | 13,805 |
   | `interleave dict*` benches in `interleave_kernels` | | within 2%, except 
`dict(20, 0.0) 100`: 226 → 239 |
   
   On distinct inputs the change does no extra work, and the 100-row case does 
less, so I read the residuals as code layout: a control build of this PR moved 
by up to 3% on the same cases. Calling `child_values_ptr_eq` instead would 
cover the same inputs, but its `to_data()` calls cost +26% and +69% on the 
8-row distinct Int64 and Utf8View cases.
   </details>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to