alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1768832579


##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+
+use std::sync::Arc;
+use std::vec;
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+/// Trait for group values column-wise row comparison
+pub trait ArrayRowEq: Send + Sync {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    fn len(&self) -> usize;
+    fn is_empty(&self) -> bool;
+    fn build(self: Box<Self>) -> ArrayRef;
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
+    group_values: Vec<T::Native>,
+    nulls: Vec<bool>,
+    // whether the array contains at least one null, for fast non-null path
+    has_null: bool,
+    nullable: bool,
+}
+
+impl<T> PrimitiveGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+{
+    pub fn new(nullable: bool) -> Self {
+        Self {
+            group_values: vec![],
+            nulls: vec![],
+            has_null: false,
+            nullable,
+        }
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        // non-null fast path
+        // both non-null
+        if !self.nullable {
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        // lhs is non-null
+        if self.nulls[lhs_row] {
+            if array.is_null(rhs_row) {
+                return false;
+            }
+
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        array.is_null(rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) {
+        // non-null fast path
+        if !self.nullable || !array.is_null(row) {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        } else {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        if self.has_null {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                Some(NullBuffer::from(self.nulls)),
+            ))
+        } else {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                None,
+            ))
+        }
+    }
+
+    fn take_n(&mut self, n: usize) -> ArrayRef {
+        if self.has_null {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(first_n),
+                Some(NullBuffer::from(first_n_nulls)),
+            ))
+        } else {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            self.nulls.truncate(self.nulls.len() - n);
+            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), 
None))
+        }
+    }
+}
+
+pub struct ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    output_type: OutputType,
+    buffer: BufferBuilder<u8>,
+    /// Offsets into `buffer` for each distinct  value. These offsets as used
+    /// directly to create the final `GenericBinaryArray`. The `i`th string is
+    /// stored in the range `offsets[i]..offsets[i+1]` in `buffer`. Null values
+    /// are stored as a zero length string.
+    offsets: Vec<O>,
+    /// Null indexes in offsets
+    nulls: Vec<usize>,
+}
+
+impl<O> ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    pub fn new(output_type: OutputType) -> Self {
+        Self {
+            output_type,
+            buffer: BufferBuilder::new(INITIAL_BUFFER_CAPACITY),
+            offsets: vec![O::default()],
+            nulls: vec![],
+        }
+    }
+
+    fn append_val_inner<B>(&mut self, array: &ArrayRef, row: usize)
+    where
+        B: ByteArrayType,
+    {
+        let arr = array.as_bytes::<B>();
+        if arr.is_null(row) {
+            self.nulls.push(self.len());
+            // nulls need a zero length in the offset buffer
+            let offset = self.buffer.len();
+
+            self.offsets.push(O::usize_as(offset));
+            return;
+        }
+
+        let value: &[u8] = arr.value(row).as_ref();
+        self.buffer.append_slice(value);
+        self.offsets.push(O::usize_as(self.buffer.len()));
+    }
+
+    fn equal_to_inner<B>(&self, lhs_row: usize, array: &ArrayRef, rhs_row: 
usize) -> bool
+    where
+        B: ByteArrayType,
+    {
+        // Handle nulls
+        let is_lhs_null = self.nulls.iter().any(|null_idx| *null_idx == 
lhs_row);
+        let arr = array.as_bytes::<B>();
+        if is_lhs_null {
+            return arr.is_null(rhs_row);
+        } else if arr.is_null(rhs_row) {
+            return false;
+        }
+
+        let arr = array.as_bytes::<B>();
+        let rhs_elem: &[u8] = arr.value(rhs_row).as_ref();
+        let rhs_elem_len = arr.value_length(rhs_row).as_usize();
+        assert_eq!(rhs_elem_len, rhs_elem.len());
+        let l = self.offsets[lhs_row].as_usize();
+        let r = self.offsets[lhs_row + 1].as_usize();
+        let existing_elem = unsafe { 
self.buffer.as_slice().get_unchecked(l..r) };
+        existing_elem.len() == rhs_elem.len() && rhs_elem == existing_elem
+    }
+}
+
+impl<O> ArrayRowEq for ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    fn equal_to(&self, lhs_row: usize, column: &ArrayRef, rhs_row: usize) -> 
bool {
+        // Sanity array type
+        match self.output_type {
+            OutputType::Binary => {
+                assert!(matches!(

Review Comment:
   Maybe we can make this go even faster with debug_assert or something.



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+
+use std::sync::Arc;
+use std::vec;
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+/// Trait for group values column-wise row comparison
+pub trait ArrayRowEq: Send + Sync {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    fn len(&self) -> usize;
+    fn is_empty(&self) -> bool;
+    fn build(self: Box<Self>) -> ArrayRef;
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
+    group_values: Vec<T::Native>,
+    nulls: Vec<bool>,
+    // whether the array contains at least one null, for fast non-null path
+    has_null: bool,
+    nullable: bool,
+}
+
+impl<T> PrimitiveGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+{
+    pub fn new(nullable: bool) -> Self {
+        Self {
+            group_values: vec![],
+            nulls: vec![],
+            has_null: false,
+            nullable,
+        }
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        // non-null fast path
+        // both non-null
+        if !self.nullable {
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        // lhs is non-null
+        if self.nulls[lhs_row] {
+            if array.is_null(rhs_row) {
+                return false;
+            }
+
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        array.is_null(rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) {
+        // non-null fast path
+        if !self.nullable || !array.is_null(row) {

Review Comment:
   should this be 
   
   ```suggestion
           if !self.nullable && !array.is_null(row) {
   ```
   
   To catch the first row that is nullable?



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+
+use std::sync::Arc;
+use std::vec;
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+/// Trait for group values column-wise row comparison
+pub trait ArrayRowEq: Send + Sync {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    fn len(&self) -> usize;
+    fn is_empty(&self) -> bool;
+    fn build(self: Box<Self>) -> ArrayRef;
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
+    group_values: Vec<T::Native>,
+    nulls: Vec<bool>,
+    // whether the array contains at least one null, for fast non-null path
+    has_null: bool,
+    nullable: bool,
+}
+
+impl<T> PrimitiveGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+{
+    pub fn new(nullable: bool) -> Self {
+        Self {
+            group_values: vec![],
+            nulls: vec![],
+            has_null: false,
+            nullable,
+        }
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        // non-null fast path
+        // both non-null
+        if !self.nullable {
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        // lhs is non-null
+        if self.nulls[lhs_row] {
+            if array.is_null(rhs_row) {
+                return false;
+            }
+
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        array.is_null(rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) {
+        // non-null fast path
+        if !self.nullable || !array.is_null(row) {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        } else {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        if self.has_null {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                Some(NullBuffer::from(self.nulls)),
+            ))
+        } else {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                None,
+            ))
+        }
+    }
+
+    fn take_n(&mut self, n: usize) -> ArrayRef {
+        if self.has_null {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(first_n),
+                Some(NullBuffer::from(first_n_nulls)),
+            ))
+        } else {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            self.nulls.truncate(self.nulls.len() - n);
+            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), 
None))
+        }
+    }
+}
+
+pub struct ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    output_type: OutputType,
+    buffer: BufferBuilder<u8>,
+    /// Offsets into `buffer` for each distinct  value. These offsets as used
+    /// directly to create the final `GenericBinaryArray`. The `i`th string is
+    /// stored in the range `offsets[i]..offsets[i+1]` in `buffer`. Null values
+    /// are stored as a zero length string.
+    offsets: Vec<O>,
+    /// Null indexes in offsets
+    nulls: Vec<usize>,
+}
+
+impl<O> ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    pub fn new(output_type: OutputType) -> Self {
+        Self {
+            output_type,
+            buffer: BufferBuilder::new(INITIAL_BUFFER_CAPACITY),
+            offsets: vec![O::default()],
+            nulls: vec![],
+        }
+    }
+
+    fn append_val_inner<B>(&mut self, array: &ArrayRef, row: usize)
+    where
+        B: ByteArrayType,
+    {
+        let arr = array.as_bytes::<B>();
+        if arr.is_null(row) {
+            self.nulls.push(self.len());
+            // nulls need a zero length in the offset buffer
+            let offset = self.buffer.len();
+
+            self.offsets.push(O::usize_as(offset));
+            return;
+        }
+
+        let value: &[u8] = arr.value(row).as_ref();
+        self.buffer.append_slice(value);
+        self.offsets.push(O::usize_as(self.buffer.len()));
+    }
+
+    fn equal_to_inner<B>(&self, lhs_row: usize, array: &ArrayRef, rhs_row: 
usize) -> bool
+    where
+        B: ByteArrayType,
+    {
+        // Handle nulls
+        let is_lhs_null = self.nulls.iter().any(|null_idx| *null_idx == 
lhs_row);
+        let arr = array.as_bytes::<B>();
+        if is_lhs_null {
+            return arr.is_null(rhs_row);
+        } else if arr.is_null(rhs_row) {
+            return false;
+        }
+
+        let arr = array.as_bytes::<B>();
+        let rhs_elem: &[u8] = arr.value(rhs_row).as_ref();
+        let rhs_elem_len = arr.value_length(rhs_row).as_usize();
+        assert_eq!(rhs_elem_len, rhs_elem.len());
+        let l = self.offsets[lhs_row].as_usize();
+        let r = self.offsets[lhs_row + 1].as_usize();
+        let existing_elem = unsafe { 
self.buffer.as_slice().get_unchecked(l..r) };
+        existing_elem.len() == rhs_elem.len() && rhs_elem == existing_elem
+    }
+}
+
+impl<O> ArrayRowEq for ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    fn equal_to(&self, lhs_row: usize, column: &ArrayRef, rhs_row: usize) -> 
bool {
+        // Sanity array type
+        match self.output_type {
+            OutputType::Binary => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Binary | DataType::LargeBinary
+                ));
+                self.equal_to_inner::<GenericBinaryType<O>>(lhs_row, column, 
rhs_row)
+            }
+            OutputType::Utf8 => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Utf8 | DataType::LargeUtf8
+                ));
+                self.equal_to_inner::<GenericStringType<O>>(lhs_row, column, 
rhs_row)
+            }
+            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
+        }
+    }
+
+    fn append_val(&mut self, column: &ArrayRef, row: usize) {
+        // Sanity array type
+        match self.output_type {
+            OutputType::Binary => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Binary | DataType::LargeBinary
+                ));
+                self.append_val_inner::<GenericBinaryType<O>>(column, row)
+            }
+            OutputType::Utf8 => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Utf8 | DataType::LargeUtf8
+                ));
+                self.append_val_inner::<GenericStringType<O>>(column, row)
+            }
+            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
+        };
+    }
+
+    fn len(&self) -> usize {
+        self.offsets.len() - 1
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        let Self {
+            output_type,
+            mut buffer,
+            offsets,
+            nulls,
+        } = *self;
+
+        let null_buffer = if nulls.is_empty() {
+            None
+        } else {
+            // Only make a `NullBuffer` if there was a null value
+            let num_values = offsets.len() - 1;
+            let mut bool_builder = BooleanBufferBuilder::new(num_values);
+            bool_builder.append_n(num_values, true);
+            nulls.into_iter().for_each(|null_index| {
+                bool_builder.set_bit(null_index, false);
+            });
+            Some(NullBuffer::from(bool_builder.finish()))
+        };
+
+        // SAFETY: the offsets were constructed correctly in `insert_if_new` --
+        // monotonically increasing, overflows were checked.
+        let offsets = unsafe { 
OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) };
+        let values = buffer.finish();
+        match output_type {
+            OutputType::Binary => {
+                // SAFETY: the offsets were constructed correctly
+                Arc::new(unsafe {
+                    GenericBinaryArray::new_unchecked(offsets, values, 
null_buffer)
+                })
+            }
+            OutputType::Utf8 => {
+                // SAFETY:
+                // 1. the offsets were constructed safely
+                //
+                // 2. we asserted the input arrays were all the correct type 
and

Review Comment:
   💯 



##########
datafusion/physical-plan/src/aggregates/group_values/mod.rs:
##########
@@ -92,5 +94,36 @@ pub fn new_group_values(schema: SchemaRef) -> Result<Box<dyn 
GroupValues>> {
         }
     }
 
-    Ok(Box::new(GroupValuesRows::try_new(schema)?))
+    if schema
+        .fields()
+        .iter()
+        .map(|f| f.data_type())
+        .all(has_row_like_feature)
+    {
+        Ok(Box::new(GroupValuesRowLike::try_new(schema)?))

Review Comment:
   Reading this from afar, I would say the name `GroupValuesRowLike` is 
confusing to me as it seems the key is that the group values are stored in 
columns rather than rows 🤔 
   
   Perhaps renaming `GroupValuesRowLike` to   `GroupValuesColumn` would make 
this clearer



##########
datafusion/sqllogictest/test_files/group_by.slt:
##########
@@ -5148,3 +5148,23 @@ NULL
 
 statement ok
 drop table test_case_expr
+
+statement ok
+drop table t;
+
+# test multi group by for binary type

Review Comment:
   perhaps we can also add a test without nulls as there is an alternative code 
path?



##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,330 @@
+// 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::GroupValues;
+use ahash::RandomState;
+use arrow::compute::cast;
+use arrow::datatypes::{
+    Date32Type, Date64Type, Float32Type, Float64Type, Int16Type, Int32Type, 
Int64Type,
+    Int8Type, UInt16Type, UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{DataFusionError, Result};
+use datafusion_execution::memory_pool::proxy::{RawTableAllocExt, VecAllocExt};
+use datafusion_expr::EmitTo;
+use datafusion_physical_expr::binary_map::OutputType;
+use datafusion_physical_expr_common::group_value_row::{
+    ArrayRowEq, ByteGroupValueBuilder, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// Compare GroupValue Rows column by column
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Logically maps group values to a group_index in
+    /// [`Self::group_values`] and in each accumulator
+    ///
+    /// Uses the raw API of hashbrown to avoid actually storing the
+    /// keys (group values) in the table
+    ///
+    /// keys: u64 hashes of the GroupValue
+    /// values: (hash, group_index)
+    map: RawTable<(u64, usize)>,
+
+    /// The size of `map` in bytes
+    map_size: usize,
+
+    /// The actual group by values, stored column-wise. Compare from
+    /// the left to right, each column is stored as `ArrayRowEq`.
+    /// This is shown faster than the row format
+    group_values: Option<Vec<Box<dyn ArrayRowEq>>>,

Review Comment:
   Could you explain the difference between what `None` and `Some(vec![])` is?
   
   I wonder if you can make this simpler by just using a Vec and checking for 
empty vec? 
   
   ```suggestion
       group_values: Vec<Box<dyn ArrayRowEq>>,
   ```



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   This module feels like it is an implementation detail of 
datafusion/physical-plan/src/aggregates/group_values/row_like.rs, so I suggest 
putting it in that module (`physical-plan` rather than `physical-expr-common`)



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+
+use std::sync::Arc;
+use std::vec;
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+/// Trait for group values column-wise row comparison
+pub trait ArrayRowEq: Send + Sync {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    fn len(&self) -> usize;
+    fn is_empty(&self) -> bool;
+    fn build(self: Box<Self>) -> ArrayRef;
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}

Review Comment:
   Here are some doc suggestions:
   
   ```suggestion
   /// Trait for group values column-wise row comparison
   ///
   /// Implementations of this trait store a in-progress collection of group 
values
   /// (similar to various builders in Arrow-rs) that allow for quick 
comparison to
   /// incoming rows.
   ///
   pub trait ArrayRowEq: Send + Sync {
       /// Returns equal if the row stored in this builder at `lhs_row` is 
equal to
       /// the row in `array` at `rhs_row`
       fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
       /// Appends the row at `row` in `array` to this builder
       fn append_val(&mut self, array: &ArrayRef, row: usize);
       /// Returns the number of rows stored in this builder
       fn len(&self) -> usize;
       /// Returns true if this builder is empty
       fn is_empty(&self) -> bool;
       /// Builds a new array from all of the stored rows
       fn build(self: Box<Self>) -> ArrayRef;
       /// Builds a new array from the first `n` stored rows, shifting the
       /// remaining rows to the start of the builder
       fn take_n(&mut self, n: usize) -> ArrayRef;
   }
   ```



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+
+use std::sync::Arc;
+use std::vec;
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+/// Trait for group values column-wise row comparison
+pub trait ArrayRowEq: Send + Sync {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    fn len(&self) -> usize;
+    fn is_empty(&self) -> bool;
+    fn build(self: Box<Self>) -> ArrayRef;
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {

Review Comment:
   At a high level, I feel like this builder and the `ByteGroupValueBuilder` 
feel like they are very similar to builders in arrow-rs. I don't know if we 
could actually upstream any of this / use the upstream builders, but if we 
could we could probably save some significant time



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,393 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow::array::BufferBuilder;
+use arrow::array::GenericBinaryArray;
+use arrow::array::GenericStringArray;
+use arrow::array::OffsetSizeTrait;
+use arrow::array::PrimitiveArray;
+use arrow::array::{Array, ArrayRef, ArrowPrimitiveType, AsArray};
+use arrow::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::ByteArrayType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+
+use std::sync::Arc;
+use std::vec;
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+/// Trait for group values column-wise row comparison
+pub trait ArrayRowEq: Send + Sync {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool;
+    fn append_val(&mut self, array: &ArrayRef, row: usize);
+    fn len(&self) -> usize;
+    fn is_empty(&self) -> bool;
+    fn build(self: Box<Self>) -> ArrayRef;
+    fn take_n(&mut self, n: usize) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType> {
+    group_values: Vec<T::Native>,
+    nulls: Vec<bool>,
+    // whether the array contains at least one null, for fast non-null path
+    has_null: bool,
+    nullable: bool,
+}
+
+impl<T> PrimitiveGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+{
+    pub fn new(nullable: bool) -> Self {
+        Self {
+            group_values: vec![],
+            nulls: vec![],
+            has_null: false,
+            nullable,
+        }
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayRowEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        // non-null fast path
+        // both non-null
+        if !self.nullable {
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        // lhs is non-null
+        if self.nulls[lhs_row] {
+            if array.is_null(rhs_row) {
+                return false;
+            }
+
+            return self.group_values[lhs_row]
+                == array.as_primitive::<T>().value(rhs_row);
+        }
+
+        array.is_null(rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) {
+        // non-null fast path
+        if !self.nullable || !array.is_null(row) {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        } else {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        if self.has_null {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                Some(NullBuffer::from(self.nulls)),
+            ))
+        } else {
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(self.group_values),
+                None,
+            ))
+        }
+    }
+
+    fn take_n(&mut self, n: usize) -> ArrayRef {
+        if self.has_null {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            let first_n_nulls = self.nulls.drain(0..n).collect::<Vec<_>>();
+            Arc::new(PrimitiveArray::<T>::new(
+                ScalarBuffer::from(first_n),
+                Some(NullBuffer::from(first_n_nulls)),
+            ))
+        } else {
+            let first_n = self.group_values.drain(0..n).collect::<Vec<_>>();
+            self.nulls.truncate(self.nulls.len() - n);
+            Arc::new(PrimitiveArray::<T>::new(ScalarBuffer::from(first_n), 
None))
+        }
+    }
+}
+
+pub struct ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    output_type: OutputType,
+    buffer: BufferBuilder<u8>,
+    /// Offsets into `buffer` for each distinct  value. These offsets as used
+    /// directly to create the final `GenericBinaryArray`. The `i`th string is
+    /// stored in the range `offsets[i]..offsets[i+1]` in `buffer`. Null values
+    /// are stored as a zero length string.
+    offsets: Vec<O>,
+    /// Null indexes in offsets
+    nulls: Vec<usize>,
+}
+
+impl<O> ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    pub fn new(output_type: OutputType) -> Self {
+        Self {
+            output_type,
+            buffer: BufferBuilder::new(INITIAL_BUFFER_CAPACITY),
+            offsets: vec![O::default()],
+            nulls: vec![],
+        }
+    }
+
+    fn append_val_inner<B>(&mut self, array: &ArrayRef, row: usize)
+    where
+        B: ByteArrayType,
+    {
+        let arr = array.as_bytes::<B>();
+        if arr.is_null(row) {
+            self.nulls.push(self.len());
+            // nulls need a zero length in the offset buffer
+            let offset = self.buffer.len();
+
+            self.offsets.push(O::usize_as(offset));
+            return;
+        }
+
+        let value: &[u8] = arr.value(row).as_ref();
+        self.buffer.append_slice(value);
+        self.offsets.push(O::usize_as(self.buffer.len()));
+    }
+
+    fn equal_to_inner<B>(&self, lhs_row: usize, array: &ArrayRef, rhs_row: 
usize) -> bool
+    where
+        B: ByteArrayType,
+    {
+        // Handle nulls
+        let is_lhs_null = self.nulls.iter().any(|null_idx| *null_idx == 
lhs_row);
+        let arr = array.as_bytes::<B>();
+        if is_lhs_null {
+            return arr.is_null(rhs_row);
+        } else if arr.is_null(rhs_row) {
+            return false;
+        }
+
+        let arr = array.as_bytes::<B>();
+        let rhs_elem: &[u8] = arr.value(rhs_row).as_ref();
+        let rhs_elem_len = arr.value_length(rhs_row).as_usize();
+        assert_eq!(rhs_elem_len, rhs_elem.len());
+        let l = self.offsets[lhs_row].as_usize();
+        let r = self.offsets[lhs_row + 1].as_usize();
+        let existing_elem = unsafe { 
self.buffer.as_slice().get_unchecked(l..r) };
+        existing_elem.len() == rhs_elem.len() && rhs_elem == existing_elem
+    }
+}
+
+impl<O> ArrayRowEq for ByteGroupValueBuilder<O>
+where
+    O: OffsetSizeTrait,
+{
+    fn equal_to(&self, lhs_row: usize, column: &ArrayRef, rhs_row: usize) -> 
bool {
+        // Sanity array type
+        match self.output_type {
+            OutputType::Binary => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Binary | DataType::LargeBinary
+                ));
+                self.equal_to_inner::<GenericBinaryType<O>>(lhs_row, column, 
rhs_row)
+            }
+            OutputType::Utf8 => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Utf8 | DataType::LargeUtf8
+                ));
+                self.equal_to_inner::<GenericStringType<O>>(lhs_row, column, 
rhs_row)
+            }
+            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
+        }
+    }
+
+    fn append_val(&mut self, column: &ArrayRef, row: usize) {
+        // Sanity array type
+        match self.output_type {
+            OutputType::Binary => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Binary | DataType::LargeBinary
+                ));
+                self.append_val_inner::<GenericBinaryType<O>>(column, row)
+            }
+            OutputType::Utf8 => {
+                assert!(matches!(
+                    column.data_type(),
+                    DataType::Utf8 | DataType::LargeUtf8
+                ));
+                self.append_val_inner::<GenericStringType<O>>(column, row)
+            }
+            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
+        };
+    }
+
+    fn len(&self) -> usize {
+        self.offsets.len() - 1
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        let Self {
+            output_type,
+            mut buffer,
+            offsets,
+            nulls,
+        } = *self;
+
+        let null_buffer = if nulls.is_empty() {
+            None
+        } else {
+            // Only make a `NullBuffer` if there was a null value
+            let num_values = offsets.len() - 1;
+            let mut bool_builder = BooleanBufferBuilder::new(num_values);
+            bool_builder.append_n(num_values, true);
+            nulls.into_iter().for_each(|null_index| {
+                bool_builder.set_bit(null_index, false);
+            });
+            Some(NullBuffer::from(bool_builder.finish()))
+        };
+
+        // SAFETY: the offsets were constructed correctly in `insert_if_new` --
+        // monotonically increasing, overflows were checked.
+        let offsets = unsafe { 
OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) };
+        let values = buffer.finish();
+        match output_type {
+            OutputType::Binary => {
+                // SAFETY: the offsets were constructed correctly
+                Arc::new(unsafe {
+                    GenericBinaryArray::new_unchecked(offsets, values, 
null_buffer)
+                })
+            }
+            OutputType::Utf8 => {
+                // SAFETY:
+                // 1. the offsets were constructed safely
+                //
+                // 2. we asserted the input arrays were all the correct type 
and
+                // thus since all the values that went in were valid (e.g. 
utf8)
+                // so are all the values that come out
+                Arc::new(unsafe {
+                    GenericStringArray::new_unchecked(offsets, values, 
null_buffer)
+                })
+            }
+            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
+        }
+    }
+
+    fn take_n(&mut self, n: usize) -> ArrayRef {
+        assert!(self.len() >= n);
+
+        let mut nulls_count = 0;

Review Comment:
   The null / shifting logic here feels like it should be unit tested to me 
(maybe fuzz testing would be enough)
   
   Also, I am reminded of @kazuyukitanimura 's PR in arrow to improve 
`set_bits` https://github.com/apache/arrow-rs/pull/6288 which I think could be 
used here as well and now even more optimized



##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,310 @@
+// 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::GroupValues;
+use ahash::RandomState;
+use arrow::compute::cast;
+use arrow::datatypes::{
+    Date32Type, Date64Type, Float32Type, Float64Type, Int16Type, Int32Type, 
Int64Type,
+    Int8Type, UInt16Type, UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{DataFusionError, Result};
+use datafusion_execution::memory_pool::proxy::{RawTableAllocExt, VecAllocExt};
+use datafusion_expr::EmitTo;
+use datafusion_physical_expr::binary_map::OutputType;
+use datafusion_physical_expr_common::group_value_row::{
+    ArrayRowEq, ByteGroupValueBuilder, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// Compare GroupValue Rows column by column
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Logically maps group values to a group_index in
+    /// [`Self::group_values`] and in each accumulator
+    ///
+    /// Uses the raw API of hashbrown to avoid actually storing the
+    /// keys (group values) in the table
+    ///
+    /// keys: u64 hashes of the GroupValue
+    /// values: (hash, group_index)
+    map: RawTable<(u64, usize)>,
+
+    /// The size of `map` in bytes
+    map_size: usize,
+
+    /// The actual group by values, stored column-wise. Compare from
+    /// the left to right, each column is stored as `ArrayRowEq`.
+    /// This is shown faster than the row format
+    group_values: Option<Vec<Box<dyn ArrayRowEq>>>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+}
+
+impl GroupValuesRowLike {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let map = RawTable::with_capacity(0);
+        Ok(Self {
+            schema,
+            map,
+            map_size: 0,
+            group_values: None,
+            hashes_buffer: Default::default(),
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesRowLike {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> 
Result<()> {
+        let n_rows = cols[0].len();
+        let mut group_values = match self.group_values.take() {
+            Some(group_values) => group_values,
+            None => {
+                let len = cols.len();
+                let mut v = Vec::with_capacity(len);
+
+                for f in self.schema.fields().iter() {
+                    match f.data_type() {
+                        &DataType::Int8 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Int8Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int16 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Int16Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int32 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Int32Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int64 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Int64Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt8 => {
+                            let b = 
PrimitiveGroupValueBuilder::<UInt8Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt16 => {
+                            let b = 
PrimitiveGroupValueBuilder::<UInt16Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt32 => {
+                            let b = 
PrimitiveGroupValueBuilder::<UInt32Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt64 => {
+                            let b = 
PrimitiveGroupValueBuilder::<UInt64Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float32 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Float32Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float64 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Float64Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Date32 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Date32Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Date64 => {
+                            let b = 
PrimitiveGroupValueBuilder::<Date64Type>::default();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Utf8 => {
+                            let b = 
ByteGroupValueBuilder::<i32>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::LargeUtf8 => {
+                            let b = 
ByteGroupValueBuilder::<i64>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        dt => todo!("{dt} not impl"),
+                    }
+                }
+                v
+            }
+        };
+
+        // tracks to which group each of the input rows belongs
+        groups.clear();
+
+        // 1.1 Calculate the group keys for the group values
+        let batch_hashes = &mut self.hashes_buffer;
+        batch_hashes.clear();
+        batch_hashes.resize(n_rows, 0);
+        create_hashes(cols, &self.random_state, batch_hashes)?;
+
+        for (row, &target_hash) in batch_hashes.iter().enumerate() {
+            let entry = self.map.get_mut(target_hash, |(exist_hash, 
group_idx)| {
+                // Somewhat surprisingly, this closure can be called even if 
the
+                // hash doesn't match, so check the hash first with an integer
+                // comparison first avoid the more expensive comparison with
+                // group value. https://github.com/apache/datafusion/pull/11718
+                if target_hash != *exist_hash {
+                    return false;
+                }
+
+                fn check_row_equal(
+                    array_row: &dyn ArrayRowEq,
+                    lhs_row: usize,
+                    array: &ArrayRef,
+                    rhs_row: usize,
+                ) -> bool {
+                    array_row.equal_to(lhs_row, array, rhs_row)

Review Comment:
   One idea I had is that you could defer actually copying the new rows into 
group_values so rather than calling the function once for each new group, you 
could call it once per batch, and it could insert all the new values in one 
function call
   
   That would save some function call overhead as well as the downcasting of 
arrays and maybe would vectorize better



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