Rich-T-kid commented on code in PR #23187:
URL: https://github.com/apache/datafusion/pull/23187#discussion_r3531819304


##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs:
##########
@@ -0,0 +1,425 @@
+// 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::DataType;
+use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field};
+use datafusion_common::Result;
+use std::marker::PhantomData;
+use std::sync::Arc;
+use std::sync::Mutex;
+
+pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + 
Sync> {
+    inner: Box<dyn GroupColumn>,
+    null_array: ArrayRef,
+    cached_values: Option<ArrayRef>,
+    cached_combined: Option<ArrayRef>,
+    /// Per-call group equality cache for the low-cardinality path. `Mutex`
+    /// because `vectorized_equal_to` takes `&self`; always uncontended.
+    group_eq_cache: Mutex<Vec<Option<bool>>>,
+    _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,
+            group_eq_cache: Mutex::new(Vec::new()),
+            _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 num_values = values.len();
+        assert!(
+            Self::valid_bounds::<K>(num_values),
+            "Dictionary key type {:?} cannot hold {} values",
+            K::DATA_TYPE,
+            num_values
+        );
+        let keys: PrimitiveArray<K> = (0..num_values)
+            .map(|idx| {
+                if values.is_null(idx) {
+                    None
+                } else {
+                    Some(K::Native::usize_as(idx))
+                }
+            })
+            .collect();
+        Arc::new(DictionaryArray::<K>::new(keys, values))
+    }
+
+    fn valid_bounds<T: ArrowDictionaryKeyType>(num_values: usize) -> bool {

Review Comment:
   this could be a const function? I think ive seen similar patterns to this. 
Will look into it



##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs:
##########
@@ -0,0 +1,425 @@
+// 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::DataType;
+use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field};
+use datafusion_common::Result;
+use std::marker::PhantomData;
+use std::sync::Arc;
+use std::sync::Mutex;
+
+pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + 
Sync> {
+    inner: Box<dyn GroupColumn>,
+    null_array: ArrayRef,
+    cached_values: Option<ArrayRef>,
+    cached_combined: Option<ArrayRef>,
+    /// Per-call group equality cache for the low-cardinality path. `Mutex`
+    /// because `vectorized_equal_to` takes `&self`; always uncontended.
+    group_eq_cache: Mutex<Vec<Option<bool>>>,
+    _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,
+            group_eq_cache: Mutex::new(Vec::new()),
+            _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 num_values = values.len();
+        assert!(
+            Self::valid_bounds::<K>(num_values),
+            "Dictionary key type {:?} cannot hold {} values",
+            K::DATA_TYPE,
+            num_values
+        );
+        let keys: PrimitiveArray<K> = (0..num_values)
+            .map(|idx| {
+                if values.is_null(idx) {
+                    None
+                } else {
+                    Some(K::Native::usize_as(idx))
+                }
+            })
+            .collect();
+        Arc::new(DictionaryArray::<K>::new(keys, values))
+    }
+
+    fn valid_bounds<T: ArrowDictionaryKeyType>(num_values: usize) -> bool {
+        let max: usize = match T::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,
+        };
+        num_values == 0 || num_values - 1 <= max
+    }
+}
+
+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 unique_group_count: hashbrown::HashSet<usize> =

Review Comment:
   we only need the number of unique values from this or a rough estimate. 
going through a hashset for this may or may not be overkill. I need to research 
alternatives. For now its fine since the speedups that come from the low 
cardinality path make up the difference by a large degree.
   



##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs:
##########
@@ -0,0 +1,425 @@
+// 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::DataType;
+use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field};
+use datafusion_common::Result;
+use std::marker::PhantomData;
+use std::sync::Arc;
+use std::sync::Mutex;
+
+pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + 
Sync> {
+    inner: Box<dyn GroupColumn>,
+    null_array: ArrayRef,
+    cached_values: Option<ArrayRef>,
+    cached_combined: Option<ArrayRef>,
+    /// Per-call group equality cache for the low-cardinality path. `Mutex`
+    /// because `vectorized_equal_to` takes `&self`; always uncontended.
+    group_eq_cache: Mutex<Vec<Option<bool>>>,
+    _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,
+            group_eq_cache: Mutex::new(Vec::new()),
+            _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 num_values = values.len();
+        assert!(
+            Self::valid_bounds::<K>(num_values),
+            "Dictionary key type {:?} cannot hold {} values",
+            K::DATA_TYPE,
+            num_values
+        );
+        let keys: PrimitiveArray<K> = (0..num_values)
+            .map(|idx| {
+                if values.is_null(idx) {
+                    None
+                } else {
+                    Some(K::Native::usize_as(idx))
+                }
+            })
+            .collect();
+        Arc::new(DictionaryArray::<K>::new(keys, values))
+    }
+
+    fn valid_bounds<T: ArrowDictionaryKeyType>(num_values: usize) -> bool {
+        let max: usize = match T::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,
+        };
+        num_values == 0 || num_values - 1 <= max
+    }
+}
+
+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 unique_group_count: hashbrown::HashSet<usize> =
+            lhs_rows.iter().copied().collect();
+        let low_cardinality = unique_group_count.len() <= rhs_rows.len() / 5;

Review Comment:
   **This can be tuned**. `1/5` seems like a reasonable threshold for 
cardinality.



##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs:
##########
@@ -0,0 +1,425 @@
+// 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::DataType;
+use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field};
+use datafusion_common::Result;
+use std::marker::PhantomData;
+use std::sync::Arc;
+use std::sync::Mutex;
+
+pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + 
Sync> {
+    inner: Box<dyn GroupColumn>,
+    null_array: ArrayRef,
+    cached_values: Option<ArrayRef>,
+    cached_combined: Option<ArrayRef>,
+    /// Per-call group equality cache for the low-cardinality path. `Mutex`
+    /// because `vectorized_equal_to` takes `&self`; always uncontended.
+    group_eq_cache: Mutex<Vec<Option<bool>>>,

Review Comment:
   This is a work around needed because `vectorized_equal_to` takes in a 
`&self` as opposed to `&mut self`. This means the alternative is needing to 
allocate `target_batch_size` arrays for each `intern()` call instead of 
re-using the vector.
   
   Originally planned to use `RefCell` but its not Send + Sync



##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs:
##########
@@ -0,0 +1,425 @@
+// 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::DataType;
+use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, Field};
+use datafusion_common::Result;
+use std::marker::PhantomData;
+use std::sync::Arc;
+use std::sync::Mutex;
+
+pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + 
Sync> {
+    inner: Box<dyn GroupColumn>,
+    null_array: ArrayRef,
+    cached_values: Option<ArrayRef>,
+    cached_combined: Option<ArrayRef>,
+    /// Per-call group equality cache for the low-cardinality path. `Mutex`
+    /// because `vectorized_equal_to` takes `&self`; always uncontended.
+    group_eq_cache: Mutex<Vec<Option<bool>>>,

Review Comment:
   this shouldn't incur any overhead since there no contention but I'm happy to 
explore other ideas.



-- 
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]

Reply via email to