Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions arrow-select/src/dictionary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,15 @@ type PtrEq = fn(&dyn Array, &dyn Array) -> bool;
///
/// `len` is the total length of the merged output
///
/// 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
pub(crate) fn should_merge_dictionary_values<K: ArrowDictionaryKeyType>(
dictionaries: &[&DictionaryArray<K>],
len: usize,
) -> (bool, bool) {
) -> (bool, bool, bool) {
use DataType::*;
let first_values = dictionaries[0].values().as_ref();
let ptr_eq: PtrEq = match first_values.data_type() {
Expand All @@ -238,10 +240,15 @@ pub(crate) fn should_merge_dictionary_values<K: ArrowDictionaryKeyType>(
LargeBinary => bytes_ptr_eq::<LargeBinaryType>,
dt => {
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())),
);
}
|a, b| a.to_data().ptr_eq(&b.to_data())
Expand All @@ -264,6 +271,7 @@ pub(crate) fn should_merge_dictionary_values<K: ArrowDictionaryKeyType>(
(
!single_dictionary && (overflow || values_exceed_length),
overflow,
single_dictionary,
Comment thread
Rich-T-kid marked this conversation as resolved.
Resolved
)
}

Expand Down
253 changes: 228 additions & 25 deletions arrow-select/src/interleave.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
//! Interleave elements from multiple arrays

use crate::concat::concat;
use crate::dictionary::{merge_dictionary_values, should_merge_dictionary_values};
use crate::dictionary::{
child_values_ptr_eq, merge_dictionary_values, should_merge_dictionary_values,
};
use arrow_array::ListLikeArray;
use arrow_array::builder::{BooleanBufferBuilder, PrimitiveBuilder};
use arrow_array::cast::AsArray;
Expand Down Expand Up @@ -262,35 +264,71 @@ fn interleave_dictionaries<K: ArrowDictionaryKeyType>(
indices: &[(usize, usize)],
) -> Result<ArrayRef, ArrowError> {
let dictionaries: Vec<_> = arrays.iter().map(|x| x.as_dictionary::<K>()).collect();
let (should_merge, has_overflow) =
let (should_merge, has_overflow, shared_values) =
should_merge_dictionary_values::<K>(&dictionaries, indices.len());
if !should_merge {
return if has_overflow {
interleave_fallback(arrays, indices)
} else {
let strategy = if shared_values {
DictionaryInterleaveStrategy::SharedDictionary
} else if should_merge {
DictionaryInterleaveStrategy::MergeDictionaries
} else if has_overflow {
DictionaryInterleaveStrategy::Fallback
} else {
DictionaryInterleaveStrategy::FallbackDictionary
};

match strategy {
Comment thread
Rich-T-kid marked this conversation as resolved.
Resolved
DictionaryInterleaveStrategy::SharedDictionary => {
// SAFETY: `should_merge_dictionary_values` verified that every dictionary's values
// array has the same length and buffers as `dictionaries[0].values()`.
unsafe {
interleave_shared_dictionary(&dictionaries, indices, dictionaries[0].values())
}
}
DictionaryInterleaveStrategy::MergeDictionaries => {
interleave_merged_dictionaries(&dictionaries, indices)
}
DictionaryInterleaveStrategy::Fallback => interleave_fallback(arrays, indices),
DictionaryInterleaveStrategy::FallbackDictionary => {
interleave_fallback_dictionary::<K>(&dictionaries, indices)
};
}
}
}

enum DictionaryInterleaveStrategy {
SharedDictionary,
MergeDictionaries,
Fallback,
FallbackDictionary,
}

// Keep merge-path code generation independent of shared-mapping detection.
#[inline(never)]
fn interleave_merged_dictionaries<K: ArrowDictionaryKeyType>(
dictionaries: &[&DictionaryArray<K>],
indices: &[(usize, usize)],
) -> Result<ArrayRef, ArrowError> {
let masks_and_lookups: Result<Vec<_>, ArrowError> = dictionaries
.iter()
.enumerate()
.map(|(a_idx, dictionary)| {
.map(|dictionary| {
let buffer = MutableBuffer::try_from_len_zeroed(bit_util::ceil(dictionary.len(), 8))
.map_err(|e| ArrowError::MemoryError(e.to_string()))?;
let mut key_mask = BooleanBufferBuilder::new_from_buffer(buffer, dictionary.len());

let mut lookups = 0;
for (_, key_idx) in indices.iter().filter(|(a, _)| *a == a_idx) {
key_mask.set_bit(*key_idx, true);
lookups += 1;
}
Ok((key_mask.finish(), lookups))
Ok((
BooleanBufferBuilder::new_from_buffer(buffer, dictionary.len()),
0,
))
})
.collect();
let (masks, key_lookups): (Vec<_>, Vec<_>) = masks_and_lookups?.into_iter().unzip();
let mut masks_and_lookups = masks_and_lookups?;
for &(array_idx, key_idx) in indices {
masks_and_lookups[array_idx].0.set_bit(key_idx, true);
masks_and_lookups[array_idx].1 += 1;
}
let (masks, key_lookups): (Vec<_>, Vec<_>) = masks_and_lookups
.into_iter()
.map(|(mut mask, lookups)| (mask.finish(), lookups))
.unzip();

let merged = merge_dictionary_values(&dictionaries, Some(&masks), Some(&key_lookups))?;
let merged = merge_dictionary_values(dictionaries, Some(&masks), Some(&key_lookups))?;

// Recompute keys
let mut keys = PrimitiveBuilder::<K>::with_capacity(indices.len());
Expand All @@ -312,6 +350,34 @@ 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 have the same length and buffers as `shared_values`.
unsafe fn interleave_shared_dictionary<K: ArrowDictionaryKeyType>(
dictionaries: &[&DictionaryArray<K>],
indices: &[(usize, usize)],
shared_values: &ArrayRef,
) -> Result<ArrayRef, ArrowError> {
Comment thread
Rich-T-kid marked this conversation as resolved.
Resolved
debug_assert!(
dictionaries
.iter()
.all(|dictionary| child_values_ptr_eq(dictionary.values(), shared_values))
);
let key_arrays: Vec<&dyn Array> = dictionaries
.iter()
.map(|dictionary| dictionary.keys() as &dyn Array)
.collect();
let keys = interleave_primitive::<K>(&key_arrays, indices, dictionaries[0].keys().data_type())?;
// SAFETY: every non-null key is in bounds for its own values array, which has the same length
// as `shared_values`.
let array = unsafe {
DictionaryArray::new_unchecked(keys.as_primitive::<K>().clone(), Arc::clone(shared_values))
};
Ok(Arc::new(array))
}

fn interleave_views<T: ByteViewType>(
values: &[&dyn Array],
indices: &[(usize, usize)],
Expand Down Expand Up @@ -1198,16 +1264,134 @@ mod tests {
}

#[test]
fn test_interleave_dictionary_overflow_same_values() {
fn test_interleave_dictionary_reuses_shared_values() {
let values: ArrayRef = Arc::new(StringArray::from_iter_values(["a", "b", "c"]));
let dict_a = DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![Some(0), None, Some(2)]),
Arc::clone(&values),
);
let dict_b = DictionaryArray::<Int32Type>::new(
Int32Array::from(vec![Some(1), Some(0)]),
Arc::clone(&values),
);

let result = interleave(
&[&dict_a, &dict_b],
&[(0, 2), (1, 0), (0, 1), (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![Some(2), Some(1), None, Some(0), Some(0)])
);
}

#[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_values_with_different_nulls_are_not_shared() {
let values = StringArray::from_iter_values(["a", "b", "c"]);
// Same offsets and data buffers as `values`, but "b" is null.
let values_with_null: ArrayRef = Arc::new(StringArray::new(
values.offsets().clone(),
values.values().clone(),
Some(NullBuffer::from(&[true, false, true])),
));
let dict_a = DictionaryArray::<Int32Type>::new(Int32Array::from(vec![1]), values_with_null);
let dict_b = DictionaryArray::<Int32Type>::new(Int32Array::from(vec![1]), Arc::new(values));

let result = interleave(&[&dict_a, &dict_b], &[(0, 0), (1, 0)]).unwrap();
let result = result.as_dictionary::<Int32Type>();
let strings: Vec<_> = result
.downcast_dict::<StringArray>()
.unwrap()
.into_iter()
.collect();
assert_eq!(strings, vec![None, Some("b")]);
}

#[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]));
}

#[test]
fn test_interleave_dictionary_empty_values() {
let values: ArrayRef = Arc::new(StringArray::new_null(0));
let dictionary =
DictionaryArray::<Int8Type>::new(Int8Array::new_null(2), Arc::clone(&values));

let result = interleave(&[&dictionary], &[(0, 1), (0, 0)]).unwrap();
let result = result.as_dictionary::<Int8Type>();

assert!(Arc::ptr_eq(result.values(), &values));
assert_eq!(result.keys(), &Int8Array::new_null(2));
}

#[test]
fn test_interleave_dictionary_shared_values_avoid_key_overflow() {
let values: ArrayRef = Arc::new(StringArray::from_iter_values(
(0..50).map(|i| format!("v{i}")),
));

// With 3 dictionaries of 50 values each, relative_offsets = [0, 50, 100]
// Accessing key 49 from dict3 gives 100 + 49 = 149 which overflows Int8
// (max 127).
// This test case falls back to interleave_fallback because the
// dictionaries share the same underlying values slice.
// Concatenating the three mappings would overflow Int8, but the shared
// values mapping lets interleave keep the original keys.
let dict1 = DictionaryArray::<Int8Type>::new(
Int8Array::from_iter_values([0, 1, 2]),
values.clone(),
Expand All @@ -1230,6 +1414,25 @@ mod tests {
.map(|x| x.unwrap())
.collect();
assert_eq!(string_result, vec!["v0", "v0", "v49"]);
Comment thread
Rich-T-kid marked this conversation as resolved.
Resolved
assert!(Arc::ptr_eq(dict_result.values(), &values));
}

#[test]
fn test_interleave_dictionary_distinct_values_overflow_returns_err() {
let values_a: ArrayRef = Arc::new(StringArray::from_iter_values(
(0..200).map(|i| format!("a{i}")),
));
let values_b: ArrayRef = Arc::new(StringArray::from_iter_values(
(0..200).map(|i| format!("b{i}")),
));
let dict_a =
DictionaryArray::<UInt8Type>::new(UInt8Array::from_iter_values(0..200), values_a);
let dict_b =
DictionaryArray::<UInt8Type>::new(UInt8Array::from_iter_values(0..200), values_b);
let indices: Vec<_> = (0..200).flat_map(|i| [(0, i), (1, i)]).collect();

let err = interleave(&[&dict_a, &dict_b], &indices).unwrap_err();
assert!(matches!(err, ArrowError::DictionaryKeyOverflowError));
}

fn test_interleave_lists<O: OffsetSizeTrait>() {
Expand Down
21 changes: 21 additions & 0 deletions arrow/benches/interleave_kernels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,27 @@ fn add_benchmark(c: &mut Criterion) {
&[&dict, &sparse_dict],
);
}

let shared_values: ArrayRef = Arc::new(create_string_array_with_len::<i32>(10, 0.0, 20));
let shared_dictionary = DictionaryArray::<Int32Type>::new(
Int32Array::from_iter_values((0..1024).map(|i| i % 10)),
shared_values,
);
let shared_a = shared_dictionary.slice(0, shared_dictionary.len());
let shared_b = shared_dictionary.slice(0, shared_dictionary.len());
let distinct_values: ArrayRef = Arc::new(create_string_array_with_len::<i32>(10, 0.0, 20));
let distinct_dictionary = DictionaryArray::<Int32Type>::new(
Int32Array::from_iter_values((0..1024).map(|i| i % 10)),
distinct_values,
);
let values: [&dyn Array; 3] = [&shared_a, &shared_b, &distinct_dictionary];
let indices: Vec<_> = (0..2040)
.map(|i| (i % 2, i % 1024))
.chain((0..8).map(|i| (2, i)))
.collect();
c.bench_function("interleave dict_shared_distinct_tail 2048", |b| {
b.iter(|| hint::black_box(interleave(&values, &indices).unwrap()))
});
}

// Alternate sources so parent rows cannot coalesce, while each selected list
Expand Down