Rich-T-kid commented on code in PR #23187: URL: https://github.com/apache/datafusion/pull/23187#discussion_r3508939506
########## datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs: ########## @@ -0,0 +1,397 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::aggregates::group_values::multi_group_by::GroupColumn; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, DictionaryArray, PrimitiveArray, +}; +use arrow::compute::concat; +use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field}; +use datafusion_common::Result; +use std::marker::PhantomData; +use std::sync::Arc; + +pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + Sync> { + inner: Box<dyn GroupColumn>, + null_array: ArrayRef, + cached_values: Option<ArrayRef>, + cached_combined: Option<ArrayRef>, + _phantom: PhantomData<K>, +} + +impl<K: ArrowDictionaryKeyType + Send + Sync> DictionaryGroupValuesColumn<K> { + pub fn new(inner: Box<dyn GroupColumn>, field: &Field) -> Self { + let null_array = arrow::array::new_null_array(field.data_type(), 1); + Self { + inner, + null_array, + cached_values: None, + cached_combined: None, + _phantom: PhantomData, + } + } + + #[inline] + fn get_combined(&mut self, values: &ArrayRef) -> Result<ArrayRef> { + let is_cached = self + .cached_values + .as_ref() + .is_some_and(|cached| Arc::ptr_eq(cached, values)); + if !is_cached { + self.cached_combined = + Some(concat(&[values.as_ref(), self.null_array.as_ref()])?); + self.cached_values = Some(Arc::clone(values)); + } + Ok(Arc::clone(self.cached_combined.as_ref().unwrap())) + } + + #[inline] + fn into_dict(values: ArrayRef) -> ArrayRef { + // at some point in the future we may want to support bumping the key types + // https://github.com/apache/datafusion/issues/23127 + let keys: PrimitiveArray<K> = (0..values.len()) Review Comment: It may be useful to add bounds checking here ```rust fn valid_bounds<K: ArrowDictionaryKeyType>(n: usize) -> bool { let max: usize = match K::DATA_TYPE { DataType::Int8 => i8::MAX as usize, DataType::Int16 => i16::MAX as usize, DataType::Int32 => i32::MAX as usize, DataType::Int64 => i64::MAX as usize, DataType::UInt8 => u8::MAX as usize, DataType::UInt16 => u16::MAX as usize, DataType::UInt32 => u32::MAX as usize, DataType::UInt64 => usize::MAX, _ => return false, }; n == 0 || n - 1 <= max } ``` ########## datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs: ########## @@ -1934,6 +2004,221 @@ mod tests { ); } + fn dict_col(vals: &[Option<&str>]) -> ArrayRef { + let mut b = StringDictionaryBuilder::<Int32Type>::new(); + for v in vals { + match v { + Some(s) => b.append_value(s), + None => b.append_null(), + } + } + Arc::new(b.finish()) + } + + fn assert_dict_str(arr: &ArrayRef, expected: &[Option<&str>]) { + let casted = cast(arr.as_ref(), &DataType::Utf8).unwrap(); + let s = casted.as_any().downcast_ref::<StringArray>().unwrap(); + assert_eq!(s.len(), expected.len()); + for (i, exp) in expected.iter().enumerate() { + match exp { + Some(v) => { + assert!(!s.is_null(i), "row {i}"); + assert_eq!(s.value(i), *v, "row {i}"); + } + None => assert!(s.is_null(i), "row {i}"), + } + } + } + + fn assert_is_dict_utf8(arr: &ArrayRef, label: &str) { + assert!( + matches!(arr.data_type(), + DataType::Dictionary(k, v) + if k.as_ref() == &DataType::Int32 && v.as_ref() == &DataType::Utf8), + "{label}: expected Dictionary(Int32, Utf8), got {:?}", + arr.data_type() + ); + } + + fn dict_utf8() -> DataType { + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)) + } + + // Mixed key types (Int8/Int32) and value types (Utf8/LargeUtf8) in the same schema. + #[test] + fn test_group_dict_repeated_keys_mixed_types_non_streaming() { + let schema = Arc::new(Schema::new(vec![ + Field::new( + "a", + DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)), + true, + ), + Field::new( + "b", + DataType::Dictionary( + Box::new(DataType::Int32), + Box::new(DataType::LargeUtf8), + ), + true, + ), + ])); + let mut gv = GroupValuesColumn::<false>::try_new(Arc::clone(&schema)).unwrap(); + + let i8_utf8 = |vals: &[Option<&str>]| -> ArrayRef { + let mut b = StringDictionaryBuilder::<Int8Type>::new(); + for v in vals { + match v { + Some(s) => b.append_value(s), + None => b.append_null(), + } + } + Arc::new(b.finish()) + }; + let i32_large = |keys: Vec<Option<i32>>, vals: &[&str]| -> ArrayRef { + Arc::new(DictionaryArray::<Int32Type>::new( + Int32Array::from(keys), + Arc::new(LargeStringArray::from(vals.to_vec())), + )) + }; + + let mut groups = vec![]; + gv.intern( + &[ + i8_utf8(&[Some("a"), Some("b"), Some("a")]), + i32_large(vec![Some(0), Some(1), Some(0)], &["x", "y"]), + ], + &mut groups, + ) + .unwrap(); + assert_eq!(groups, vec![0, 1, 0]); + + gv.intern( + &[ + i8_utf8(&[Some("b"), Some("c"), Some("c"), Some("a")]), + i32_large(vec![Some(1), Some(2), Some(2), Some(0)], &["x", "y", "z"]), + ], + &mut groups, + ) + .unwrap(); + assert_eq!(groups, vec![1, 2, 2, 0]); + + let out = gv.emit(EmitTo::All).unwrap(); + assert_dict_str(&out[0], &[Some("a"), Some("b"), Some("c")]); + let s = cast(out[1].as_ref(), &DataType::LargeUtf8).unwrap(); + let s = s.as_any().downcast_ref::<LargeStringArray>().unwrap(); + let got: Vec<_> = (0..s.len()) + .map(|i| s.is_valid(i).then(|| s.value(i))) + .collect(); + assert_eq!(got, vec![Some("x"), Some("y"), Some("z")]); + } + + // Dict cols mixed with a primitive col; both non-streaming and streaming paths. + #[test] + fn test_group_dict_with_primitive_non_streaming() { + let dt = dict_utf8(); + let schema = Arc::new(Schema::new(vec![ + Field::new("a", dt.clone(), true), + Field::new("b", dt.clone(), true), + Field::new("c", DataType::Int64, true), + ])); + + let run = |mut gv: Box<dyn GroupValues>| { + let mut groups = vec![]; + gv.intern( + &[ + dict_col(&[Some("a"), Some("b"), Some("a")]), + dict_col(&[Some("x"), Some("y"), Some("x")]), + Arc::new(Int64Array::from(vec![1i64, 2, 1])), + ], + &mut groups, + ) + .unwrap(); + assert_eq!(groups, vec![0, 1, 0]); + gv.intern( + &[ + dict_col(&[Some("a"), Some("c")]), + dict_col(&[Some("x"), Some("z")]), + Arc::new(Int64Array::from(vec![1i64, 3])), + ], + &mut groups, + ) + .unwrap(); + assert_eq!(groups, vec![0, 2]); + let out = gv.emit(EmitTo::All).unwrap(); + assert_dict_str(&out[0], &[Some("a"), Some("b"), Some("c")]); + assert_dict_str(&out[1], &[Some("x"), Some("y"), Some("z")]); + let c = out[2].as_any().downcast_ref::<Int64Array>().unwrap(); + assert_eq!(c.values(), &[1, 2, 3]); + }; + + run(Box::new( + GroupValuesColumn::<false>::try_new(Arc::clone(&schema)).unwrap(), + )); + run(Box::new( + GroupValuesColumn::<true>::try_new(Arc::clone(&schema)).unwrap(), + )); + } + + // Nulls in different columns must form distinct groups. + #[test] + fn test_group_three_dict_cols_with_nulls_non_streaming() { + let dt = dict_utf8(); + let schema = Arc::new(Schema::new(vec![ + Field::new("a", dt.clone(), true), + Field::new("b", dt.clone(), true), + Field::new("c", dt.clone(), true), + ])); + let mut gv = GroupValuesColumn::<false>::try_new(Arc::clone(&schema)).unwrap(); + let mut groups = vec![]; + + gv.intern( + &[ + dict_col(&[None, Some("a"), None, Some("a")]), + dict_col(&[Some("x"), None, Some("x"), None]), + dict_col(&[Some("p"), Some("p"), Some("p"), Some("q")]), + ], + &mut groups, + ) + .unwrap(); + assert_eq!(groups, vec![0, 1, 0, 2]); + + let out = gv.emit(EmitTo::All).unwrap(); + assert_dict_str(&out[0], &[None, Some("a"), Some("a")]); + assert_dict_str(&out[1], &[Some("x"), None, None]); + assert_dict_str(&out[2], &[Some("p"), Some("p"), Some("q")]); + } + + // Emitted columns must carry the exact schema DataType via both build and take_n paths. + #[test] + fn test_emit_dict_output_exact_type() { + let dt = dict_utf8(); + let schema = Arc::new(Schema::new(vec![Field::new("a", dt.clone(), true)])); + + // non-streaming: build path + let mut gv = GroupValuesColumn::<false>::try_new(Arc::clone(&schema)).unwrap(); + let mut groups = vec![]; + gv.intern(&[dict_col(&[Some("x"), None, Some("y")])], &mut groups) + .unwrap(); + assert_eq!(groups, vec![0, 1, 2]); + let out = gv.emit(EmitTo::All).unwrap(); + assert_is_dict_utf8(&out[0], "build"); + assert_dict_str(&out[0], &[Some("x"), None, Some("y")]); + + // streaming: take_n then build + let mut gv2 = GroupValuesColumn::<true>::try_new(Arc::clone(&schema)).unwrap(); + gv2.intern( + &[dict_col(&[Some("alpha"), Some("beta"), None])], + &mut groups, + ) + .unwrap(); + let taken = gv2.emit(EmitTo::First(2)).unwrap(); + assert_is_dict_utf8(&taken[0], "take_n"); + assert_dict_str(&taken[0], &[Some("alpha"), Some("beta")]); + let remaining = gv2.emit(EmitTo::All).unwrap(); + assert_is_dict_utf8(&remaining[0], "build after take_n"); + assert_dict_str(&remaining[0], &[None]); + } + Review Comment: I think the test in this file are fine ########## datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs: ########## @@ -1067,6 +1067,42 @@ fn make_group_column(field: &Field) -> Result<Box<dyn GroupColumn>> { v.push(Box::new(BooleanGroupValueBuilder::<false>::new())); } } + DataType::Dictionary(key_dt, value_dt) => { + let new_field = Field::new("", *value_dt.clone(), true); + let inner = make_group_column(&new_field)?; + let col: Box<dyn GroupColumn> = match key_dt.as_ref() { + DataType::Int8 => Box::new(dictionary::DictionaryGroupValuesColumn::< + Int8Type, + >::new(inner, &new_field)), + DataType::Int16 => Box::new(dictionary::DictionaryGroupValuesColumn::< + Int16Type, + >::new(inner, &new_field)), + DataType::Int32 => Box::new(dictionary::DictionaryGroupValuesColumn::< + Int32Type, + >::new(inner, &new_field)), + DataType::Int64 => Box::new(dictionary::DictionaryGroupValuesColumn::< + Int64Type, + >::new(inner, &new_field)), + DataType::UInt8 => Box::new(dictionary::DictionaryGroupValuesColumn::< + UInt8Type, + >::new(inner, &new_field)), + DataType::UInt16 => Box::new(dictionary::DictionaryGroupValuesColumn::< + UInt16Type, + >::new(inner, &new_field)), + DataType::UInt32 => Box::new(dictionary::DictionaryGroupValuesColumn::< + UInt32Type, + >::new(inner, &new_field)), + DataType::UInt64 => Box::new(dictionary::DictionaryGroupValuesColumn::< + UInt64Type, + >::new(inner, &new_field)), + _ => { + return not_impl_err!( + "Dictionary key type {key_dt} not supported in GroupValuesColumn" + ); + } Review Comment: replace this with the downcast! macro ########## datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs: ########## @@ -0,0 +1,397 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::aggregates::group_values::multi_group_by::GroupColumn; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanBufferBuilder, DictionaryArray, PrimitiveArray, +}; +use arrow::compute::concat; +use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field}; +use datafusion_common::Result; +use std::marker::PhantomData; +use std::sync::Arc; + +pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + Sync> { + inner: Box<dyn GroupColumn>, + null_array: ArrayRef, + cached_values: Option<ArrayRef>, + cached_combined: Option<ArrayRef>, + _phantom: PhantomData<K>, +} + +impl<K: ArrowDictionaryKeyType + Send + Sync> DictionaryGroupValuesColumn<K> { + pub fn new(inner: Box<dyn GroupColumn>, field: &Field) -> Self { + let null_array = arrow::array::new_null_array(field.data_type(), 1); + Self { + inner, + null_array, + cached_values: None, + cached_combined: None, + _phantom: PhantomData, + } + } + + #[inline] + fn get_combined(&mut self, values: &ArrayRef) -> Result<ArrayRef> { + let is_cached = self + .cached_values + .as_ref() + .is_some_and(|cached| Arc::ptr_eq(cached, values)); + if !is_cached { + self.cached_combined = + Some(concat(&[values.as_ref(), self.null_array.as_ref()])?); + self.cached_values = Some(Arc::clone(values)); + } + Ok(Arc::clone(self.cached_combined.as_ref().unwrap())) + } + + #[inline] + fn into_dict(values: ArrayRef) -> ArrayRef { + // at some point in the future we may want to support bumping the key types + // https://github.com/apache/datafusion/issues/23127 + let keys: PrimitiveArray<K> = (0..values.len()) + .map(|i| { + if values.is_null(i) { + None + } else { + Some(K::Native::usize_as(i)) + } + }) + .collect(); + Arc::new(DictionaryArray::<K>::new(keys, values)) + } +} + +impl<K: ArrowDictionaryKeyType + Send + Sync> GroupColumn + for DictionaryGroupValuesColumn<K> +{ + fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool { + let dict = array.as_dictionary::<K>(); + match dict.key(rhs_row) { + None => self.inner.equal_to(lhs_row, &self.null_array, 0), + Some(key) => self.inner.equal_to(lhs_row, dict.values(), key), + } + } + + fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> { + let dict = array.as_dictionary::<K>(); + match dict.key(row) { + None => self.inner.append_val(&self.null_array, 0), + Some(key) => self.inner.append_val(dict.values(), key), + } + } + + fn vectorized_equal_to( + &self, + lhs_rows: &[usize], + array: &ArrayRef, + rhs_rows: &[usize], + equal_to_results: &mut BooleanBufferBuilder, + ) { + let dict = array.as_dictionary::<K>(); + let keys = dict.keys(); + let values = dict.values(); + + if keys.null_count() == 0 { + let key_indices: Vec<usize> = + rhs_rows.iter().map(|&r| keys.value(r).as_usize()).collect(); + self.inner.vectorized_equal_to( + lhs_rows, + values, + &key_indices, + equal_to_results, + ); + } else { + for (i, (lhs_row, rhs_row)) in lhs_rows.iter().zip(rhs_rows).enumerate() { + if equal_to_results.get_bit(i) { + let result = match dict.key(*rhs_row) { + None => self.inner.equal_to(*lhs_row, &self.null_array, 0), + Some(key) => self.inner.equal_to(*lhs_row, values, key), + }; + equal_to_results.set_bit(i, result); + } + } + } + } + + fn vectorized_append(&mut self, array: &ArrayRef, rows: &[usize]) -> Result<()> { + let dict = array.as_dictionary::<K>(); + let keys = dict.keys(); + + if keys.null_count() == 0 { + let key_indices: Vec<usize> = + rows.iter().map(|&r| keys.value(r).as_usize()).collect(); + self.inner.vectorized_append(dict.values(), &key_indices) + } else { + let combined = self.get_combined(dict.values())?; + // last element of combined is always the null sentinel appended by get_combined + let null_idx = combined.len() - 1; + let key_indices: Vec<usize> = rows + .iter() + .map(|&r| dict.key(r).unwrap_or(null_idx)) + .collect(); + self.inner.vectorized_append(&combined, &key_indices) + } + } + + fn len(&self) -> usize { + self.inner.len() + } + + fn size(&self) -> usize { + self.inner.size() + } + + fn build(self: Box<Self>) -> ArrayRef { + Self::into_dict(self.inner.build()) + } + + fn take_n(&mut self, n: usize) -> ArrayRef { + Self::into_dict(self.inner.take_n(n)) + } +} + +#[cfg(test)] +mod tests { Review Comment: test in this file can be reduced. testing the trait end to end in 1-3 test should be enough. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
