You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "jayzhan211 (via GitHub)" <gi...@apache.org> on 2024/08/31 03:58:42 UTC

[PR] Avoid RowConverter for multi group by [datafusion]

jayzhan211 opened a new pull request, #12269:
URL: https://github.com/apache/datafusion/pull/12269

   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   ## Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   To avoid Row converter in multi group by clause, we add equality check for group values Array.
   
   
   ## What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   ## Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   
   
   ## Benchmark
   
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃       main ┃  row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     0.40ms │     0.48ms │  1.19x slower │
   │ QQuery 1     │    43.92ms │    46.27ms │  1.05x slower │
   │ QQuery 2     │    76.59ms │    76.90ms │     no change │
   │ QQuery 3     │    63.93ms │    67.31ms │  1.05x slower │
   │ QQuery 4     │   447.49ms │   426.92ms │     no change │
   │ QQuery 5     │   704.75ms │   680.61ms │     no change │
   │ QQuery 6     │    36.18ms │    35.58ms │     no change │
   │ QQuery 7     │    37.50ms │    36.56ms │     no change │
   │ QQuery 8     │   687.91ms │   599.47ms │ +1.15x faster │
   │ QQuery 9     │   654.23ms │   615.37ms │ +1.06x faster │
   │ QQuery 10    │   204.86ms │   175.98ms │ +1.16x faster │
   │ QQuery 11    │   237.91ms │   195.13ms │ +1.22x faster │
   │ QQuery 12    │   758.26ms │   695.74ms │ +1.09x faster │
   │ QQuery 13    │  1011.35ms │   885.85ms │ +1.14x faster │
   │ QQuery 14    │   980.44ms │   883.32ms │ +1.11x faster │
   │ QQuery 15    │   544.60ms │   468.27ms │ +1.16x faster │
   │ QQuery 16    │  1751.52ms │  1318.86ms │ +1.33x faster │
   │ QQuery 17    │  1530.76ms │  1311.78ms │ +1.17x faster │
   │ QQuery 18    │  3702.09ms │  4322.81ms │  1.17x slower │
   │ QQuery 19    │    53.09ms │    52.30ms │     no change │
   │ QQuery 20    │  1535.97ms │  1475.38ms │     no change │
   │ QQuery 21    │  1830.57ms │  1747.03ms │     no change │
   │ QQuery 22    │  4105.92ms │  3851.14ms │ +1.07x faster │
   │ QQuery 23    │  8317.37ms │  8089.16ms │     no change │
   │ QQuery 24    │   498.14ms │   479.31ms │     no change │
   │ QQuery 25    │   506.65ms │   491.19ms │     no change │
   │ QQuery 26    │   571.42ms │   544.09ms │     no change │
   │ QQuery 27    │  1323.25ms │  1325.59ms │     no change │
   │ QQuery 28    │ 10284.17ms │ 10243.26ms │     no change │
   │ QQuery 29    │   404.45ms │   441.24ms │  1.09x slower │
   │ QQuery 30    │   837.55ms │   847.60ms │     no change │
   │ QQuery 31    │   829.55ms │   779.72ms │ +1.06x faster │
   │ QQuery 32    │  4698.41ms │  3555.64ms │ +1.32x faster │
   │ QQuery 33    │  4180.51ms │  4229.86ms │     no change │
   │ QQuery 34    │  4055.17ms │  3981.71ms │     no change │
   │ QQuery 35    │  1015.82ms │  1195.95ms │  1.18x slower │
   │ QQuery 36    │   143.36ms │   154.85ms │  1.08x slower │
   │ QQuery 37    │    99.73ms │   105.03ms │  1.05x slower │
   └──────────────┴────────────┴────────────┴───────────────┘


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1762826775


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -1380,24 +1380,16 @@ mod tests {
                 "+---+-----+-----------------+",
                 "| a | b   | COUNT(1)[count] |",
                 "+---+-----+-----------------+",
-                "|   | 1.0 | 1               |",

Review Comment:
   The behaviour of my branch is consistent with the one that run in slt.
   Not sure which one is the expected behaviour 🤔 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2351552824

   > @alamb I found `FirstN` mode is non-trivial If I switch to Arrow's Builder instead of `Vec` what I had done before. Is it reasonable to implement `takeN` logic in Arrow's Builder upstream?
   
   I think using Vec, if possible, is likely to be the best idea as Vec is well understood and highly optimized in Rust (and also has a fast conversion to Arrow arrays)
   
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1768828952


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

Review Comment:
   We can probably make this faster using a BooleanBufferBuilder or something similar 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1762826775


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -1380,24 +1380,16 @@ mod tests {
                 "+---+-----+-----------------+",
                 "| a | b   | COUNT(1)[count] |",
                 "+---+-----+-----------------+",
-                "|   | 1.0 | 1               |",

Review Comment:
   The change is consistent with the one that run in slt in `main`.
   Not sure which one is the expected behaviour 🤔 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1764225281


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -1380,24 +1380,16 @@ mod tests {
                 "+---+-----+-----------------+",
                 "| a | b   | COUNT(1)[count] |",
                 "+---+-----+-----------------+",
-                "|   | 1.0 | 1               |",

Review Comment:
   I have checked both postgres and duckdb, the `spill` one is the expected result. But why the `non-spill` version has the different result



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1750672515


##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,624 @@
+// 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::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+use arrow::{
+    array::{Array, ArrayRef, ArrowPrimitiveType, AsArray, PrimitiveArray},
+    datatypes::ByteArrayType,
+};
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+use std::sync::Arc;
+
+pub trait ArrayEq: 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 build(self: Box<Self>) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType>(Vec<Option<T::Native>>);
+
+impl<T: ArrowPrimitiveType> PrimitiveGroupValueBuilder<T> {
+    pub fn new() -> Self {
+        Self(vec![])
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool {
+        let elem = self.0[lhs_row];
+        let arr = array.as_primitive::<T>();
+        let is_rhs_null = arr.is_null(rhs_row);
+        if elem.is_none() && is_rhs_null {
+            true
+        } else if elem.is_some() && !is_rhs_null {
+            elem.unwrap() == arr.value(rhs_row)
+        } else {
+            false
+        }
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) {
+        let arr = array.as_primitive::<T>();
+        if arr.is_null(row) {
+            self.0.push(None)
+        } else {
+            let elem = arr.value(row);
+            self.0.push(Some(elem))
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.0.len()
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        Arc::new(PrimitiveArray::<T>::from_iter(self.0))
+    }
+}
+
+// pub struct StringGroupValueBuilder(Vec<Option<String>>);
+
+// impl StringGroupValueBuilder {
+//     pub fn new() -> Self {
+//         Self(vec![])
+//     }
+// }
+
+// impl ArrayEq for StringGroupValueBuilder {
+//     fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool {
+//         let elem = &self.0[lhs_row];
+//         let arr = array.as_string::<i32>();
+//         let is_rhs_null = arr.is_null(rhs_row);
+//         if elem.is_none() && is_rhs_null {
+//             true
+//         } else if elem.is_some() && !is_rhs_null {
+//             let e = elem.as_ref().unwrap();
+//             e.as_str() == arr.value(rhs_row)
+//         } else {
+//             false
+//         }
+//     }
+
+//     fn append_val(&mut self, array: &ArrayRef, row: usize) {
+//         let arr = array.as_string::<i32>();
+//         if arr.is_null(row) {
+//             self.0.push(None)
+//         } else {
+//             let elem = arr.value(row);
+//             self.0.push(Some(elem.to_string()))
+//         }
+//     }
+
+//     fn len(&self) -> usize {
+//         self.0.len()
+//     }
+
+//     fn build(self: Box<Self>) -> ArrayRef {
+//         Arc::new(StringArray::from_iter(self.0))
+//     }
+// }
+
+pub struct ByteGroupValueBuilderNaive<O>

Review Comment:
   Similar to my comment above, this looks very similar to the GenericBinaryBuilder in arrow -- it would be great if we could simply reuse that instead of a significant amount of copying 🤔 



##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,624 @@
+// 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::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+use arrow::{
+    array::{Array, ArrayRef, ArrowPrimitiveType, AsArray, PrimitiveArray},
+    datatypes::ByteArrayType,
+};
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+use std::sync::Arc;
+
+pub trait ArrayEq: 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 build(self: Box<Self>) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType>(Vec<Option<T::Native>>);

Review Comment:
   This looks very similar to `PrimitiveBuilder` in arrow-rs to me https://docs.rs/arrow/latest/arrow/array/struct.PrimitiveBuilder.html  (though I think `PrimitiveBuilder` is likely faster / handles nulls better)
   
   I wonder if you could implement `ArrayEq` for `PrimitiveBuilder` using the methods like https://docs.rs/arrow/latest/arrow/array/struct.PrimitiveBuilder.html#method.values_slice
   
   If so I think you would have a very compelling PR here



##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,392 @@
+// 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::{
+    Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
+    UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow::row::{RowConverter, Rows, SortField};
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{internal_err, 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::{
+    ArrayEq, ByteGroupValueBuilderNaive, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// A [`GroupValues`] making use of [`Rows`]
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Converter for the group values
+    row_converter: RowConverter,
+
+    /// 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 in arrow [`Row`] format.
+    /// `group_values[i]` holds the group value for group_index `i`.
+    ///
+    /// The row format is used to compare group keys quickly and store
+    /// them efficiently in memory. Quick comparison is especially
+    /// important for multi-column group keys.
+    ///
+    /// [`Row`]: arrow::row::Row
+    // group_values: Option<Rows>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// reused buffer to store rows
+    rows_buffer: Rows,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+    group_values_v2: Option<Vec<Box<dyn ArrayEq>>>,
+}
+
+impl GroupValuesRowLike {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let row_converter = RowConverter::new(
+            schema
+                .fields()
+                .iter()
+                .map(|f| SortField::new(f.data_type().clone()))
+                .collect(),
+        )?;
+
+        let map = RawTable::with_capacity(0);
+
+        let starting_rows_capacity = 1000;
+        let starting_data_capacity = 64 * starting_rows_capacity;
+        let rows_buffer =
+            row_converter.empty_rows(starting_rows_capacity, starting_data_capacity);
+        Ok(Self {
+            schema,
+            row_converter,
+            map,
+            map_size: 0,
+            // group_values: None,
+            group_values_v2: None,
+            hashes_buffer: Default::default(),
+            rows_buffer,
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesRowLike {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        // Convert the group keys into the row format
+        // let group_rows = &mut self.rows_buffer;
+        // group_rows.clear();
+        // self.row_converter.append(group_rows, cols)?;
+        // let n_rows = group_rows.num_rows();
+
+        // let mut group_values = match self.group_values.take() {
+        //     Some(group_values) => group_values,
+        //     None => self.row_converter.empty_rows(0, 0),
+        // };
+
+        let n_rows = cols[0].len();
+        let mut group_values_v2 = match self.group_values_v2.take() {
+            Some(group_values) => group_values,
+            None => {
+                let len = cols.len();
+                let mut v = Vec::with_capacity(len);
+                // Move to `try_new`
+                for (i, f) in self.schema.fields().iter().enumerate() {
+                    match f.data_type() {
+                        &DataType::Int8 => {
+                            let b = PrimitiveGroupValueBuilder::<Int8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int16 => {
+                            let b = PrimitiveGroupValueBuilder::<Int16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int32 => {
+                            let b = PrimitiveGroupValueBuilder::<Int32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int64 => {
+                            let b = PrimitiveGroupValueBuilder::<Int64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt8 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt16 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt32 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt64 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float32 => {
+                            let b = PrimitiveGroupValueBuilder::<Float32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float64 => {
+                            let b = PrimitiveGroupValueBuilder::<Float64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Utf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<i32>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::LargeUtf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<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;
+                }
+                // verify that the group that we are inserting with hash is
+                // actually the same key value as the group in
+                // existing_idx  (aka group_values @ row)
+                // && group_rows.row(row) == group_values.row(*group_idx)
+
+                fn compare_equal(
+                    arry_eq: &dyn ArrayEq,
+                    lhs_row: usize,
+                    array: &ArrayRef,
+                    rhs_row: usize,
+                ) -> bool {
+                    arry_eq.equal_to(lhs_row, array, rhs_row)
+                }
+
+                for (i, group_val) in group_values_v2.iter().enumerate() {
+                    if !compare_equal(group_val.as_ref(), *group_idx, &cols[i], row) {
+                        return false;
+                    }
+                }
+
+                true
+            });
+
+            let group_idx = match entry {
+                // Existing group_index for this group value
+                Some((_hash, group_idx)) => *group_idx,
+                //  1.2 Need to create new entry for the group
+                None => {
+                    // Add new entry to aggr_state and save newly created index
+                    // let group_idx = group_values.num_rows();
+                    // group_values.push(group_rows.row(row));
+
+                    let mut checklen = 0;
+                    let group_idx = group_values_v2[0].len();
+                    for (i, group_value) in group_values_v2.iter_mut().enumerate() {
+                        group_value.append_val(&cols[i], row);
+                        let len = group_value.len();
+                        if i == 0 {
+                            checklen = len;
+                        } else {
+                            assert_eq!(checklen, len);
+                        }
+                    }
+
+                    // for hasher function, use precomputed hash value
+                    self.map.insert_accounted(
+                        (target_hash, group_idx),
+                        |(hash, _group_index)| *hash,
+                        &mut self.map_size,
+                    );
+                    group_idx
+                }
+            };
+            groups.push(group_idx);
+        }
+
+        // self.group_values = Some(group_values);
+        self.group_values_v2 = Some(group_values_v2);
+
+        Ok(())
+    }
+
+    fn size(&self) -> usize {
+        // TODO: get real size
+        let group_values_size =
+            self.group_values_v2.as_ref().map(|v| v.len()).unwrap_or(0);
+        // let group_values_size = self.group_values.as_ref().map(|v| v.size()).unwrap_or(0);
+        self.row_converter.size()
+            + group_values_size
+            + self.map_size
+            + self.rows_buffer.size()
+            + self.hashes_buffer.allocated_size()
+    }
+
+    fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    fn len(&self) -> usize {
+        // self.group_values
+        //     .as_ref()
+        //     .map(|group_values| group_values.num_rows())
+        //     .unwrap_or(0)
+
+        self.group_values_v2
+            .as_ref()
+            .map(|v| v[0].len())
+            .unwrap_or(0)
+    }
+
+    fn emit(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
+        // println!("emit");
+        // let mut group_values = self
+        //     .group_values
+        //     .take()
+        //     .expect("Can not emit from empty rows");
+
+        let mut group_values_v2 = self
+            .group_values_v2
+            .take()
+            .expect("Can not emit from empty rows");

Review Comment:
   This is a neat optimization as well -- as it saves a copy of the intermediate group values 👍 



##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,392 @@
+// 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::{
+    Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
+    UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow::row::{RowConverter, Rows, SortField};
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{internal_err, 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::{
+    ArrayEq, ByteGroupValueBuilderNaive, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// A [`GroupValues`] making use of [`Rows`]
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Converter for the group values
+    row_converter: RowConverter,
+
+    /// 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 in arrow [`Row`] format.
+    /// `group_values[i]` holds the group value for group_index `i`.
+    ///
+    /// The row format is used to compare group keys quickly and store
+    /// them efficiently in memory. Quick comparison is especially
+    /// important for multi-column group keys.
+    ///
+    /// [`Row`]: arrow::row::Row
+    // group_values: Option<Rows>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// reused buffer to store rows
+    rows_buffer: Rows,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+    group_values_v2: Option<Vec<Box<dyn ArrayEq>>>,
+}
+
+impl GroupValuesRowLike {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let row_converter = RowConverter::new(
+            schema
+                .fields()
+                .iter()
+                .map(|f| SortField::new(f.data_type().clone()))
+                .collect(),
+        )?;
+
+        let map = RawTable::with_capacity(0);
+
+        let starting_rows_capacity = 1000;
+        let starting_data_capacity = 64 * starting_rows_capacity;
+        let rows_buffer =
+            row_converter.empty_rows(starting_rows_capacity, starting_data_capacity);
+        Ok(Self {
+            schema,
+            row_converter,
+            map,
+            map_size: 0,
+            // group_values: None,
+            group_values_v2: None,
+            hashes_buffer: Default::default(),
+            rows_buffer,
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesRowLike {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        // Convert the group keys into the row format
+        // let group_rows = &mut self.rows_buffer;
+        // group_rows.clear();
+        // self.row_converter.append(group_rows, cols)?;
+        // let n_rows = group_rows.num_rows();
+
+        // let mut group_values = match self.group_values.take() {
+        //     Some(group_values) => group_values,
+        //     None => self.row_converter.empty_rows(0, 0),
+        // };
+
+        let n_rows = cols[0].len();
+        let mut group_values_v2 = match self.group_values_v2.take() {
+            Some(group_values) => group_values,
+            None => {
+                let len = cols.len();
+                let mut v = Vec::with_capacity(len);
+                // Move to `try_new`
+                for (i, f) in self.schema.fields().iter().enumerate() {
+                    match f.data_type() {
+                        &DataType::Int8 => {
+                            let b = PrimitiveGroupValueBuilder::<Int8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int16 => {
+                            let b = PrimitiveGroupValueBuilder::<Int16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int32 => {
+                            let b = PrimitiveGroupValueBuilder::<Int32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int64 => {
+                            let b = PrimitiveGroupValueBuilder::<Int64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt8 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt16 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt32 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt64 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float32 => {
+                            let b = PrimitiveGroupValueBuilder::<Float32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float64 => {
+                            let b = PrimitiveGroupValueBuilder::<Float64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Utf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<i32>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::LargeUtf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<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;
+                }
+                // verify that the group that we are inserting with hash is
+                // actually the same key value as the group in
+                // existing_idx  (aka group_values @ row)
+                // && group_rows.row(row) == group_values.row(*group_idx)
+
+                fn compare_equal(
+                    arry_eq: &dyn ArrayEq,
+                    lhs_row: usize,
+                    array: &ArrayRef,
+                    rhs_row: usize,
+                ) -> bool {
+                    arry_eq.equal_to(lhs_row, array, rhs_row)
+                }
+
+                for (i, group_val) in group_values_v2.iter().enumerate() {
+                    if !compare_equal(group_val.as_ref(), *group_idx, &cols[i], row) {

Review Comment:
   I think the idea would be change compare_equal to take advantage of cases when, for example, it was known the values couldn't be null (so checking `Option` isn't needed)



##########
benchmarks/queries/clickbench/queries.sql:
##########
@@ -35,9 +35,4 @@ SELECT "URL", COUNT(*) AS c FROM hits GROUP BY "URL" ORDER BY c DESC LIMIT 10;
 SELECT 1, "URL", COUNT(*) AS c FROM hits GROUP BY 1, "URL" ORDER BY c DESC LIMIT 10;
 SELECT "ClientIP", "ClientIP" - 1, "ClientIP" - 2, "ClientIP" - 3, COUNT(*) AS c FROM hits GROUP BY "ClientIP", "ClientIP" - 1, "ClientIP" - 2, "ClientIP" - 3 ORDER BY c DESC LIMIT 10;
 SELECT "URL", COUNT(*) AS PageViews FROM hits WHERE "CounterID" = 62 AND "EventDate"::INT::DATE >= '2013-07-01' AND "EventDate"::INT::DATE <= '2013-07-31' AND "DontCountHits" = 0 AND "IsRefresh" = 0 AND "URL" <> '' GROUP BY "URL" ORDER BY PageViews DESC LIMIT 10;
-SELECT "Title", COUNT(*) AS PageViews FROM hits WHERE "CounterID" = 62 AND "EventDate"::INT::DATE >= '2013-07-01' AND "EventDate"::INT::DATE <= '2013-07-31' AND "DontCountHits" = 0 AND "IsRefresh" = 0 AND "Title" <> '' GROUP BY "Title" ORDER BY PageViews DESC LIMIT 10;

Review Comment:
   Why are these queries removed?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1762826775


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -1380,24 +1380,16 @@ mod tests {
                 "+---+-----+-----------------+",
                 "| a | b   | COUNT(1)[count] |",
                 "+---+-----+-----------------+",
-                "|   | 1.0 | 1               |",

Review Comment:
   The change is consistent with the one that run in slt in `main`.
   Not sure which one is the expected behaviour 🤔 
   
   The only difference is that we use `GroupValuesRowLike` instead `GroupValuesRows` for Float



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1760473214


##########
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:
   Nulls is handled in the `equal_to`, is there any other place we could further optimize?



##########
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:
   Nulls are handled in the `equal_to`, is there any other place we could further optimize?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769693596


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

Review Comment:
   `BooleanBufferBuilder ` is not friendly for `take_n` cases



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

Review Comment:
   `BooleanBufferBuilder ` is not friendly for `take_n` case



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2351882121

   Query that compute with Datetime are slower 🤔 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769693596


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

Review Comment:
   `BooleanBufferBuilder ` is not friendly for `take_n` case



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #12269:
URL: https://github.com/apache/datafusion/pull/12269


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769693469


##########
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:
   Utilizing bitmap is challenging since we need to deal with shifting bitmap for `take_n` cases.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1740912268


##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,392 @@
+// 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::{
+    Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
+    UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow::row::{RowConverter, Rows, SortField};
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{internal_err, 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::{
+    ArrayEq, ByteGroupValueBuilderNaive, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// A [`GroupValues`] making use of [`Rows`]
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Converter for the group values
+    row_converter: RowConverter,
+
+    /// 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 in arrow [`Row`] format.
+    /// `group_values[i]` holds the group value for group_index `i`.
+    ///
+    /// The row format is used to compare group keys quickly and store
+    /// them efficiently in memory. Quick comparison is especially
+    /// important for multi-column group keys.
+    ///
+    /// [`Row`]: arrow::row::Row
+    // group_values: Option<Rows>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// reused buffer to store rows
+    rows_buffer: Rows,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+    group_values_v2: Option<Vec<Box<dyn ArrayEq>>>,
+}
+
+impl GroupValuesRowLike {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let row_converter = RowConverter::new(
+            schema
+                .fields()
+                .iter()
+                .map(|f| SortField::new(f.data_type().clone()))
+                .collect(),
+        )?;
+
+        let map = RawTable::with_capacity(0);
+
+        let starting_rows_capacity = 1000;
+        let starting_data_capacity = 64 * starting_rows_capacity;
+        let rows_buffer =
+            row_converter.empty_rows(starting_rows_capacity, starting_data_capacity);
+        Ok(Self {
+            schema,
+            row_converter,
+            map,
+            map_size: 0,
+            // group_values: None,
+            group_values_v2: None,
+            hashes_buffer: Default::default(),
+            rows_buffer,
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesRowLike {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        // Convert the group keys into the row format
+        // let group_rows = &mut self.rows_buffer;
+        // group_rows.clear();
+        // self.row_converter.append(group_rows, cols)?;
+        // let n_rows = group_rows.num_rows();
+
+        // let mut group_values = match self.group_values.take() {
+        //     Some(group_values) => group_values,
+        //     None => self.row_converter.empty_rows(0, 0),
+        // };
+
+        let n_rows = cols[0].len();
+        let mut group_values_v2 = match self.group_values_v2.take() {
+            Some(group_values) => group_values,
+            None => {
+                let len = cols.len();
+                let mut v = Vec::with_capacity(len);
+                // Move to `try_new`
+                for (i, f) in self.schema.fields().iter().enumerate() {
+                    match f.data_type() {
+                        &DataType::Int8 => {
+                            let b = PrimitiveGroupValueBuilder::<Int8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int16 => {
+                            let b = PrimitiveGroupValueBuilder::<Int16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int32 => {
+                            let b = PrimitiveGroupValueBuilder::<Int32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int64 => {
+                            let b = PrimitiveGroupValueBuilder::<Int64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt8 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt16 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt32 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt64 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float32 => {
+                            let b = PrimitiveGroupValueBuilder::<Float32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float64 => {
+                            let b = PrimitiveGroupValueBuilder::<Float64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Utf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<i32>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::LargeUtf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<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;
+                }
+                // verify that the group that we are inserting with hash is
+                // actually the same key value as the group in
+                // existing_idx  (aka group_values @ row)
+                // && group_rows.row(row) == group_values.row(*group_idx)
+
+                fn compare_equal(
+                    arry_eq: &dyn ArrayEq,
+                    lhs_row: usize,
+                    array: &ArrayRef,
+                    rhs_row: usize,
+                ) -> bool {
+                    arry_eq.equal_to(lhs_row, array, rhs_row)
+                }
+
+                for (i, group_val) in group_values_v2.iter().enumerate() {
+                    if !compare_equal(group_val.as_ref(), *group_idx, &cols[i], row) {

Review Comment:
   As this is called in a loop, this can be optimized/specialized for certain cases like: do the arrays have any nulls or not.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2323874269

   @alamb The approach in this PR is to replace RowConverter and check the equality of the group by values by accessing the certain row and iterate all the group by expressions. The downside is that we need to have type-specific implementation but we could see it outperform Rows by eliminating the cost of `Rows` append and push. Also, this doesn't make sense to upstream to Arrow for me, it is group by specific implementation, so we need to maintain this in Datafusion. Would like an early feedback on this approach!


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2368451062

   > 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
   
   I think the challenge of processing in batch is that if we got multiple same row, we should push the first one in group values but reject another n-1 ones as duplicated row values. The dependency is not vectorizable, since we need to check them iteratively.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "eejbyfeldt (via GitHub)" <gi...@apache.org>.
eejbyfeldt commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1771340393


##########
datafusion/physical-plan/src/aggregates/group_values/column_wise.rs:
##########
@@ -0,0 +1,315 @@
+// 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::group_value_row::{
+    ArrayRowEq, ByteGroupValueBuilder, PrimitiveGroupValueBuilder,
+};
+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 hashbrown::raw::RawTable;
+
+/// Compare GroupValue Rows column by column
+pub struct GroupValuesColumn {
+    /// 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: Vec<Box<dyn ArrayRowEq>>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+}
+
+impl GroupValuesColumn {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let map = RawTable::with_capacity(0);
+        Ok(Self {
+            schema,
+            map,
+            map_size: 0,
+            group_values: vec![],
+            hashes_buffer: Default::default(),
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesColumn {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        let n_rows = cols[0].len();
+
+        if self.group_values.is_empty() {
+            let len = cols.len();
+            let mut v = Vec::with_capacity(len);

Review Comment:
   I think we should give `len` a better name like `n_cols`  or just "inline" it like
   ```suggestion
               let mut v = Vec::with_capacity(cols.len());
   ```
   because for me it currently just hurts readability. 
   



##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -0,0 +1,446 @@
+// 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 datafusion_physical_expr_common::binary_map::{OutputType, INITIAL_BUFFER_CAPACITY};
+
+/// 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;
+    /// 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;
+}
+
+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 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, if `i` is in nulls, `offsets[i]` should be equals to `offsets[i+1]`
+    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();
+        debug_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

Review Comment:
   Do we really need to check the length manually? Will that not just be a part of the `==` for slices. (https://doc.rust-lang.org/1.81.0/src/core/slice/cmp.rs.html#59)
   ```suggestion
          rhs_elem == existing_elem
   ```



##########
datafusion/physical-plan/src/aggregates/group_values/column_wise.rs:
##########
@@ -0,0 +1,315 @@
+// 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::group_value_row::{
+    ArrayRowEq, ByteGroupValueBuilder, PrimitiveGroupValueBuilder,
+};
+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 hashbrown::raw::RawTable;
+
+/// Compare GroupValue Rows column by column
+pub struct GroupValuesColumn {
+    /// 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: Vec<Box<dyn ArrayRowEq>>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+}
+
+impl GroupValuesColumn {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let map = RawTable::with_capacity(0);
+        Ok(Self {
+            schema,
+            map,
+            map_size: 0,
+            group_values: vec![],
+            hashes_buffer: Default::default(),
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesColumn {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        let n_rows = cols[0].len();
+
+        if self.group_values.is_empty() {
+            let len = cols.len();
+            let mut v = Vec::with_capacity(len);
+
+            for f in self.schema.fields().iter() {
+                let nullable = f.is_nullable();
+                match f.data_type() {
+                    &DataType::Int8 => {
+                        let b = PrimitiveGroupValueBuilder::<Int8Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int16 => {
+                        let b = PrimitiveGroupValueBuilder::<Int16Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int32 => {
+                        let b = PrimitiveGroupValueBuilder::<Int32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int64 => {
+                        let b = PrimitiveGroupValueBuilder::<Int64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt8 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt8Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt16 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt16Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt32 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt64 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Float32 => {
+                        let b = PrimitiveGroupValueBuilder::<Float32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Float64 => {
+                        let b = PrimitiveGroupValueBuilder::<Float64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Date32 => {
+                        let b = PrimitiveGroupValueBuilder::<Date32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Date64 => {
+                        let b = PrimitiveGroupValueBuilder::<Date64Type>::new(nullable);
+                        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 _)
+                    }
+                    &DataType::Binary => {
+                        let b = ByteGroupValueBuilder::<i32>::new(OutputType::Binary);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::LargeBinary => {
+                        let b = ByteGroupValueBuilder::<i64>::new(OutputType::Binary);
+                        v.push(Box::new(b) as _)
+                    }
+                    dt => todo!("{dt} not impl"),
+                }
+            }
+            self.group_values = 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)
+                }
+
+                for (i, group_val) in self.group_values.iter().enumerate() {
+                    if !check_row_equal(group_val.as_ref(), *group_idx, &cols[i], row) {
+                        return false;
+                    }
+                }
+
+                true
+            });
+
+            let group_idx = match entry {
+                // Existing group_index for this group value
+                Some((_hash, group_idx)) => *group_idx,
+                //  1.2 Need to create new entry for the group
+                None => {
+                    // Add new entry to aggr_state and save newly created index
+                    // let group_idx = group_values.num_rows();
+                    // group_values.push(group_rows.row(row));
+
+                    let mut checklen = 0;
+                    let group_idx = self.group_values[0].len();
+                    for (i, group_value) in self.group_values.iter_mut().enumerate() {
+                        group_value.append_val(&cols[i], row);
+                        let len = group_value.len();
+                        if i == 0 {
+                            checklen = len;
+                        } else {
+                            debug_assert_eq!(checklen, len);
+                        }
+                    }
+
+                    // for hasher function, use precomputed hash value
+                    self.map.insert_accounted(
+                        (target_hash, group_idx),
+                        |(hash, _group_index)| *hash,
+                        &mut self.map_size,
+                    );
+                    group_idx
+                }
+            };
+            groups.push(group_idx);
+        }
+
+        Ok(())
+    }
+
+    fn size(&self) -> usize {
+        let group_values_size = self.group_values.len();

Review Comment:
   My understanding is that size should return allocated size in bytes, so this does not look correct for `self.group_values`. I would expect us need to do something like
   ```
           let group_values_size = self.group_values.iter().map(|column| column.size()).sum()
   ```
   and add a size method to `ArrayRowEq` so it can do some size calculation based on the field.



##########
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:
   For me it also took sometime when reading to convince my self that `||` was correct. Maybe it would be easier to read if it we swaped the two cases and removed the `!`? e.g
   ```
           if self.nullable && array.is_null(row) {
               self.group_values.push(T::default_value());
               self.nulls.push(false);
               self.has_null = true;
           } else {
               let elem = array.as_primitive::<T>().value(row);
               self.group_values.push(elem);
               self.nulls.push(true);
           }
   ```



##########
datafusion/sqllogictest/test_files/group_by.slt:
##########
@@ -5148,3 +5148,42 @@ NULL
 
 statement ok
 drop table test_case_expr
+
+statement ok
+drop table t;
+
+# test multi group by for binary type with nulls
+statement ok
+create table t(a int, b bytea) as values (1, 0xa), (1, 0xa), (2, null), (null, 0xb), (null, 0xb);
+
+query I?I
+select a, b, count(*) from t group by grouping sets ((a, b), (a), (b));

Review Comment:
   Do we want to add a comment here to note that the result here is actually incorrect when compraing to other query engines. Due to https://github.com/apache/datafusion/issues/12570



##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -0,0 +1,446 @@
+// 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 datafusion_physical_expr_common::binary_map::{OutputType, INITIAL_BUFFER_CAPACITY};
+
+/// 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;
+    /// 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;
+}
+
+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 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, if `i` is in nulls, `offsets[i]` should be equals to `offsets[i+1]`
+    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();
+        debug_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 => {
+                debug_assert!(matches!(
+                    column.data_type(),
+                    DataType::Binary | DataType::LargeBinary
+                ));
+                self.equal_to_inner::<GenericBinaryType<O>>(lhs_row, column, rhs_row)
+            }
+            OutputType::Utf8 => {
+                debug_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 => {
+                debug_assert!(matches!(
+                    column.data_type(),
+                    DataType::Binary | DataType::LargeBinary
+                ));
+                self.append_val_inner::<GenericBinaryType<O>>(column, row)
+            }
+            OutputType::Utf8 => {
+                debug_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 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 {
+        debug_assert!(self.len() >= n);
+
+        let mut nulls_count = 0;

Review Comment:
   Seems like we never use the result in `nulls_count`? Could it just be removed?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769462304


##########
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:
   We should `or` them
   `nullable` is whether the column is nullable or not, so we don't need to check `array.is_null(row)` if the column is declared non-null, just assume every thing is non-null



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2356547159

   @jayzhan211  what is the status of this PR? Is it ready for another look? Do you need some help?


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2351553325

   @jayzhan211  BTW the results in https://github.com/apache/datafusion/pull/12269#issuecomment-2350774004 are quite impressive
   
   This is a great example of using data driven decisions to come to a better internal architecture / approach (e.g showing with data that using single row comparisons is actually better than using RowCoverter). Very nice 👌 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2357232258

   Given the comment here https://github.com/apache/datafusion/pull/7400#discussion_r1762851560
   
   1. I think we have different *final* result of grouping sets from postgres and duckdb, this PR doesn't change the behaviour
   2. The result change in `check_grouping_sets` is the *partial aggregate state* so it might be expected, but need to check.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1740962169


##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,392 @@
+// 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::{
+    Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
+    UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow::row::{RowConverter, Rows, SortField};
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{internal_err, 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::{
+    ArrayEq, ByteGroupValueBuilderNaive, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// A [`GroupValues`] making use of [`Rows`]
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Converter for the group values
+    row_converter: RowConverter,
+
+    /// 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 in arrow [`Row`] format.
+    /// `group_values[i]` holds the group value for group_index `i`.
+    ///
+    /// The row format is used to compare group keys quickly and store
+    /// them efficiently in memory. Quick comparison is especially
+    /// important for multi-column group keys.
+    ///
+    /// [`Row`]: arrow::row::Row
+    // group_values: Option<Rows>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// reused buffer to store rows
+    rows_buffer: Rows,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+    group_values_v2: Option<Vec<Box<dyn ArrayEq>>>,
+}
+
+impl GroupValuesRowLike {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let row_converter = RowConverter::new(
+            schema
+                .fields()
+                .iter()
+                .map(|f| SortField::new(f.data_type().clone()))
+                .collect(),
+        )?;
+
+        let map = RawTable::with_capacity(0);
+
+        let starting_rows_capacity = 1000;
+        let starting_data_capacity = 64 * starting_rows_capacity;
+        let rows_buffer =
+            row_converter.empty_rows(starting_rows_capacity, starting_data_capacity);
+        Ok(Self {
+            schema,
+            row_converter,
+            map,
+            map_size: 0,
+            // group_values: None,
+            group_values_v2: None,
+            hashes_buffer: Default::default(),
+            rows_buffer,
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesRowLike {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        // Convert the group keys into the row format
+        // let group_rows = &mut self.rows_buffer;
+        // group_rows.clear();
+        // self.row_converter.append(group_rows, cols)?;
+        // let n_rows = group_rows.num_rows();
+
+        // let mut group_values = match self.group_values.take() {
+        //     Some(group_values) => group_values,
+        //     None => self.row_converter.empty_rows(0, 0),
+        // };
+
+        let n_rows = cols[0].len();
+        let mut group_values_v2 = match self.group_values_v2.take() {
+            Some(group_values) => group_values,
+            None => {
+                let len = cols.len();
+                let mut v = Vec::with_capacity(len);
+                // Move to `try_new`
+                for (i, f) in self.schema.fields().iter().enumerate() {
+                    match f.data_type() {
+                        &DataType::Int8 => {
+                            let b = PrimitiveGroupValueBuilder::<Int8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int16 => {
+                            let b = PrimitiveGroupValueBuilder::<Int16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int32 => {
+                            let b = PrimitiveGroupValueBuilder::<Int32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int64 => {
+                            let b = PrimitiveGroupValueBuilder::<Int64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt8 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt16 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt32 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt64 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float32 => {
+                            let b = PrimitiveGroupValueBuilder::<Float32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float64 => {
+                            let b = PrimitiveGroupValueBuilder::<Float64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Utf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<i32>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::LargeUtf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<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;
+                }
+                // verify that the group that we are inserting with hash is
+                // actually the same key value as the group in
+                // existing_idx  (aka group_values @ row)
+                // && group_rows.row(row) == group_values.row(*group_idx)
+
+                fn compare_equal(
+                    arry_eq: &dyn ArrayEq,
+                    lhs_row: usize,
+                    array: &ArrayRef,
+                    rhs_row: usize,
+                ) -> bool {
+                    arry_eq.equal_to(lhs_row, array, rhs_row)
+                }
+
+                for (i, group_val) in group_values_v2.iter().enumerate() {
+                    if !compare_equal(group_val.as_ref(), *group_idx, &cols[i], row) {

Review Comment:
   I don't get it how could I further optimize the loop based on nulls 🤔 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1775416230


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -0,0 +1,456 @@
+// 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 datafusion_common::utils::proxy::VecAllocExt;
+
+use std::sync::Arc;
+use std::vec;
+
+use datafusion_physical_expr_common::binary_map::{OutputType, INITIAL_BUFFER_CAPACITY};
+
+/// 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 the number of bytes used by this [`ArrayRowEq`]
+    fn size(&self) -> usize;
+    /// 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;
+}
+
+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) {
+        if self.nullable && array.is_null(row) {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        } else {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn size(&self) -> usize {
+        self.group_values.allocated_size() + self.nulls.allocated_size()
+    }
+
+    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, if `i` is in nulls, `offsets[i]` should be equals to `offsets[i+1]`
+    nulls: Vec<usize>,

Review Comment:
   I took a shot at doing so in https://github.com/apache/datafusion/pull/12623 - I agree the `take_n` logic was the trickiest



##########
datafusion/physical-plan/src/aggregates/group_values/mod.rs:
##########
@@ -92,5 +96,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(GroupValuesColumn::try_new(schema)?))
+    } else {
+        Ok(Box::new(GroupValuesRows::try_new(schema)?))
+    }
+}
+
+fn has_row_like_feature(data_type: &DataType) -> bool {

Review Comment:
   in https://github.com/apache/datafusion/pull/12620



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2373873627

   I plan to file a few PRs to try an improve the code a bit before I file additional tickets to add more features. I will update this list:
   - [ ] https://github.com/apache/datafusion/pull/12617 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1750698814


##########
datafusion/physical-plan/src/aggregates/group_values/row_like.rs:
##########
@@ -0,0 +1,392 @@
+// 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::{
+    Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, UInt16Type,
+    UInt32Type, UInt64Type, UInt8Type,
+};
+use arrow::record_batch::RecordBatch;
+use arrow::row::{RowConverter, Rows, SortField};
+use arrow_array::{Array, ArrayRef};
+use arrow_schema::{DataType, SchemaRef};
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{internal_err, 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::{
+    ArrayEq, ByteGroupValueBuilderNaive, PrimitiveGroupValueBuilder,
+};
+use hashbrown::raw::RawTable;
+
+/// A [`GroupValues`] making use of [`Rows`]
+pub struct GroupValuesRowLike {
+    /// The output schema
+    schema: SchemaRef,
+
+    /// Converter for the group values
+    row_converter: RowConverter,
+
+    /// 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 in arrow [`Row`] format.
+    /// `group_values[i]` holds the group value for group_index `i`.
+    ///
+    /// The row format is used to compare group keys quickly and store
+    /// them efficiently in memory. Quick comparison is especially
+    /// important for multi-column group keys.
+    ///
+    /// [`Row`]: arrow::row::Row
+    // group_values: Option<Rows>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// reused buffer to store rows
+    rows_buffer: Rows,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+    group_values_v2: Option<Vec<Box<dyn ArrayEq>>>,
+}
+
+impl GroupValuesRowLike {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let row_converter = RowConverter::new(
+            schema
+                .fields()
+                .iter()
+                .map(|f| SortField::new(f.data_type().clone()))
+                .collect(),
+        )?;
+
+        let map = RawTable::with_capacity(0);
+
+        let starting_rows_capacity = 1000;
+        let starting_data_capacity = 64 * starting_rows_capacity;
+        let rows_buffer =
+            row_converter.empty_rows(starting_rows_capacity, starting_data_capacity);
+        Ok(Self {
+            schema,
+            row_converter,
+            map,
+            map_size: 0,
+            // group_values: None,
+            group_values_v2: None,
+            hashes_buffer: Default::default(),
+            rows_buffer,
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesRowLike {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        // Convert the group keys into the row format
+        // let group_rows = &mut self.rows_buffer;
+        // group_rows.clear();
+        // self.row_converter.append(group_rows, cols)?;
+        // let n_rows = group_rows.num_rows();
+
+        // let mut group_values = match self.group_values.take() {
+        //     Some(group_values) => group_values,
+        //     None => self.row_converter.empty_rows(0, 0),
+        // };
+
+        let n_rows = cols[0].len();
+        let mut group_values_v2 = match self.group_values_v2.take() {
+            Some(group_values) => group_values,
+            None => {
+                let len = cols.len();
+                let mut v = Vec::with_capacity(len);
+                // Move to `try_new`
+                for (i, f) in self.schema.fields().iter().enumerate() {
+                    match f.data_type() {
+                        &DataType::Int8 => {
+                            let b = PrimitiveGroupValueBuilder::<Int8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int16 => {
+                            let b = PrimitiveGroupValueBuilder::<Int16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int32 => {
+                            let b = PrimitiveGroupValueBuilder::<Int32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Int64 => {
+                            let b = PrimitiveGroupValueBuilder::<Int64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt8 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt8Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt16 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt16Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt32 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::UInt64 => {
+                            let b = PrimitiveGroupValueBuilder::<UInt64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float32 => {
+                            let b = PrimitiveGroupValueBuilder::<Float32Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Float64 => {
+                            let b = PrimitiveGroupValueBuilder::<Float64Type>::new();
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::Utf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<i32>::new(OutputType::Utf8);
+                            v.push(Box::new(b) as _)
+                        }
+                        &DataType::LargeUtf8 => {
+                            let b =
+                                ByteGroupValueBuilderNaive::<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;
+                }
+                // verify that the group that we are inserting with hash is
+                // actually the same key value as the group in
+                // existing_idx  (aka group_values @ row)
+                // && group_rows.row(row) == group_values.row(*group_idx)
+
+                fn compare_equal(
+                    arry_eq: &dyn ArrayEq,
+                    lhs_row: usize,
+                    array: &ArrayRef,
+                    rhs_row: usize,
+                ) -> bool {
+                    arry_eq.equal_to(lhs_row, array, rhs_row)
+                }
+
+                for (i, group_val) in group_values_v2.iter().enumerate() {
+                    if !compare_equal(group_val.as_ref(), *group_idx, &cols[i], row) {

Review Comment:
   Yes, indeed 👍 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2338869370

   TLDR is I ran the benchmarks and it does appear to make a measurable performance improvement on several queries 👍 
   
   ```
   ++ BENCH_BRANCH_NAME=row-group
   ++ ./bench.sh compare main_base row-group
   Comparing main_base and row-group
   --------------------
   Benchmark clickbench_1.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃  main_base ┃  row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     0.69ms │     0.70ms │     no change │
   │ QQuery 1     │    68.87ms │    69.04ms │     no change │
   │ QQuery 2     │   122.40ms │   122.39ms │     no change │
   │ QQuery 3     │   129.14ms │   129.84ms │     no change │
   │ QQuery 4     │   958.71ms │   950.60ms │     no change │
   │ QQuery 5     │  1072.42ms │  1065.00ms │     no change │
   │ QQuery 6     │    64.15ms │    65.46ms │     no change │
   │ QQuery 7     │    72.57ms │    72.23ms │     no change │
   │ QQuery 8     │  1427.25ms │  1352.90ms │ +1.05x faster │
   │ QQuery 9     │  1328.70ms │  1333.45ms │     no change │
   │ QQuery 10    │   444.86ms │   435.72ms │     no change │
   │ QQuery 11    │   493.91ms │   475.07ms │     no change │
   │ QQuery 12    │  1158.46ms │  1154.09ms │     no change │
   │ QQuery 13    │  2124.34ms │  1776.44ms │ +1.20x faster │
   │ QQuery 14    │  1607.17ms │  1306.73ms │ +1.23x faster │
   │ QQuery 15    │  1078.30ms │  1062.72ms │     no change │
   │ QQuery 16    │  2885.78ms │  2525.19ms │ +1.14x faster │
   │ QQuery 17    │  2799.52ms │  2470.93ms │ +1.13x faster │
   │ QQuery 18    │  5575.63ms │  5524.24ms │     no change │
   │ QQuery 19    │   119.57ms │   118.24ms │     no change │
   │ QQuery 20    │  1656.36ms │  1675.11ms │     no change │
   │ QQuery 21    │  2014.67ms │  2028.74ms │     no change │
   │ QQuery 22    │  4849.99ms │  4824.94ms │     no change │
   │ QQuery 23    │ 11274.06ms │ 11309.82ms │     no change │
   │ QQuery 24    │   761.95ms │   754.26ms │     no change │
   │ QQuery 25    │   667.54ms │   668.69ms │     no change │
   │ QQuery 26    │   821.70ms │   839.38ms │     no change │
   │ QQuery 27    │  2467.71ms │  2493.84ms │     no change │
   │ QQuery 28    │ 15737.24ms │ 15634.42ms │     no change │
   │ QQuery 29    │   560.78ms │   551.43ms │     no change │
   │ QQuery 30    │  1296.29ms │  1242.39ms │     no change │
   │ QQuery 31    │  1318.14ms │  1291.30ms │     no change │
   │ QQuery 32    │  4569.20ms │  4241.25ms │ +1.08x faster │
   │ QQuery 33    │  5020.91ms │  5031.03ms │     no change │
   │ QQuery 34    │  5014.64ms │  4965.98ms │     no change │
   │ QQuery 35    │  1818.84ms │  1850.31ms │     no change │
   │ QQuery 36    │   316.76ms │   302.74ms │     no change │
   │ QQuery 37    │   217.15ms │   219.32ms │     no change │
   │ QQuery 38    │   188.03ms │   191.14ms │     no change │
   │ QQuery 39    │  1039.10ms │   788.09ms │ +1.32x faster │
   │ QQuery 40    │    86.06ms │    83.63ms │     no change │
   │ QQuery 41    │    77.68ms │    79.76ms │     no change │
   │ QQuery 42    │    97.39ms │    91.99ms │ +1.06x faster │
   └──────────────┴────────────┴────────────┴───────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
   ┃ Benchmark Summary        ┃            ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
   │ Total Time (main_base)   │ 85404.65ms │
   │ Total Time (row-group)   │ 83170.54ms │
   │ Average Time (main_base) │  1986.15ms │
   │ Average Time (row-group) │  1934.20ms │
   │ Queries Faster           │          8 │
   │ Queries Slower           │          0 │
   │ Queries with No Change   │         35 │
   └──────────────────────────┴────────────┘
   --------------------
   Benchmark clickbench_extended.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓
   ┃ Query        ┃ main_base ┃ row-group ┃    Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩
   │ QQuery 0     │ 2652.87ms │ 2682.38ms │ no change │
   │ QQuery 1     │  793.53ms │  794.12ms │ no change │
   │ QQuery 2     │ 1576.90ms │ 1609.73ms │ no change │
   │ QQuery 3     │  705.29ms │  718.99ms │ no change │
   └──────────────┴───────────┴───────────┴───────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
   ┃ Benchmark Summary        ┃           ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
   │ Total Time (main_base)   │ 5728.58ms │
   │ Total Time (row-group)   │ 5805.22ms │
   │ Average Time (main_base) │ 1432.15ms │
   │ Average Time (row-group) │ 1451.31ms │
   │ Queries Faster           │         0 │
   │ Queries Slower           │         0 │
   │ Queries with No Change   │         4 │
   └──────────────────────────┴───────────┘
   --------------------
   Benchmark clickbench_partitioned.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃  main_base ┃  row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     2.29ms │     2.27ms │     no change │
   │ QQuery 1     │    38.05ms │    37.76ms │     no change │
   │ QQuery 2     │    93.47ms │    93.56ms │     no change │
   │ QQuery 3     │    98.55ms │    96.67ms │     no change │
   │ QQuery 4     │   902.00ms │   910.55ms │     no change │
   │ QQuery 5     │   937.33ms │   936.86ms │     no change │
   │ QQuery 6     │    34.33ms │    33.78ms │     no change │
   │ QQuery 7     │    40.59ms │    39.35ms │     no change │
   │ QQuery 8     │  1368.30ms │  1296.26ms │ +1.06x faster │
   │ QQuery 9     │  1293.07ms │  1273.53ms │     no change │
   │ QQuery 10    │   339.78ms │   331.25ms │     no change │
   │ QQuery 11    │   375.98ms │   381.26ms │     no change │
   │ QQuery 12    │  1025.16ms │  1034.74ms │     no change │
   │ QQuery 13    │  1811.09ms │  1792.68ms │     no change │
   │ QQuery 14    │  1453.37ms │  1448.76ms │     no change │
   │ QQuery 15    │  1012.38ms │  1012.83ms │     no change │
   │ QQuery 16    │  2746.71ms │  2728.55ms │     no change │
   │ QQuery 17    │  2719.38ms │  2632.64ms │     no change │
   │ QQuery 18    │  5524.24ms │  5525.66ms │     no change │
   │ QQuery 19    │    92.83ms │    90.08ms │     no change │
   │ QQuery 20    │  1752.39ms │  1751.25ms │     no change │
   │ QQuery 21    │  1946.27ms │  1981.08ms │     no change │
   │ QQuery 22    │  4974.66ms │  5049.46ms │     no change │
   │ QQuery 23    │  9841.76ms │  9781.88ms │     no change │
   │ QQuery 24    │   549.84ms │   559.25ms │     no change │
   │ QQuery 25    │   467.91ms │   475.16ms │     no change │
   │ QQuery 26    │   631.52ms │   617.63ms │     no change │
   │ QQuery 27    │  2445.52ms │  2463.11ms │     no change │
   │ QQuery 28    │ 14923.62ms │ 15024.79ms │     no change │
   │ QQuery 29    │   530.70ms │   523.81ms │     no change │
   │ QQuery 30    │  1106.49ms │  1060.93ms │     no change │
   │ QQuery 31    │  1140.91ms │  1090.09ms │     no change │
   │ QQuery 32    │  4550.65ms │  4133.54ms │ +1.10x faster │
   │ QQuery 33    │  4929.55ms │  4922.02ms │     no change │
   │ QQuery 34    │  4789.55ms │  4834.44ms │     no change │
   │ QQuery 35    │  1753.55ms │  1829.42ms │     no change │
   │ QQuery 36    │   283.39ms │   267.52ms │ +1.06x faster │
   │ QQuery 37    │   120.66ms │   122.89ms │     no change │
   │ QQuery 38    │   141.70ms │   136.39ms │     no change │
   │ QQuery 39    │   897.86ms │   918.07ms │     no change │
   │ QQuery 40    │    58.14ms │    61.45ms │  1.06x slower │
   │ QQuery 41    │    48.73ms │    48.17ms │     no change │
   │ QQuery 42    │    66.33ms │    63.97ms │     no change │
   └──────────────┴────────────┴────────────┴───────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
   ┃ Benchmark Summary        ┃            ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
   │ Total Time (main_base)   │ 79860.62ms │
   │ Total Time (row-group)   │ 79415.32ms │
   │ Average Time (main_base) │  1857.22ms │
   │ Average Time (row-group) │  1846.87ms │
   │ Queries Faster           │          3 │
   │ Queries Slower           │          1 │
   │ Queries with No Change   │         39 │
   ```


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1774233692


##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -0,0 +1,456 @@
+// 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 datafusion_common::utils::proxy::VecAllocExt;
+
+use std::sync::Arc;
+use std::vec;
+
+use datafusion_physical_expr_common::binary_map::{OutputType, INITIAL_BUFFER_CAPACITY};
+
+/// 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 the number of bytes used by this [`ArrayRowEq`]
+    fn size(&self) -> usize;
+    /// 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;
+}
+
+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) {
+        if self.nullable && array.is_null(row) {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        } else {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn size(&self) -> usize {
+        self.group_values.allocated_size() + self.nulls.allocated_size()
+    }
+
+    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, if `i` is in nulls, `offsets[i]` should be equals to `offsets[i+1]`
+    nulls: Vec<usize>,

Review Comment:
   It is not easy to handle `take_n` logic with `BooleanBufferBuilder`



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769015724


##########
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:
   Actually, when @wiedld and I were discussing this PR, we realized this is quite similar to 
   
   https://github.com/apache/datafusion/blob/f2159e6cae658a0a3f561ec2d15ea948213fd0f8/datafusion/physical-plan/src/aggregates/group_values/primitive.rs#L92
   
   I wonder if we could potentially use that (i.e. impl `ArrayRowEq` for `GroupValuesPrimitive`) 🤔  -- that code is already pretty well tested and optimized 🤔 
   
   Though maybe null handling has to be different 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769532140


##########
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:
   I guess I was imagining that `GroupValuesRowLike` would continue to have a `Vec<Box<dyn ArrayRowEq>>` but we could implement `ArrayRowEq` for GroupValuesPrimtive and GroupValuesBinary, etc



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2369774073

   @alamb @eejbyfeldt Thanks for your review, could take another quick look then merge this PR.
   
   TODOs of follow on
   - [ ] Implement a ByteGroupValueBuilder for StringView and the other primitive based types (e.g. DecimalArray, the date/time stuff, etc)
   - [ ] Simplify / Improve single group value case `GroupValuesPrimitive` and `GroupValuesByes`, maybe with `ArrowRowEq`
   - [ ] Vectorize the row equality check + append row


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1775416740


##########
datafusion/physical-plan/src/aggregates/group_values/column_wise.rs:
##########
@@ -0,0 +1,314 @@
+// 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::group_value_row::{
+    ArrayRowEq, ByteGroupValueBuilder, PrimitiveGroupValueBuilder,
+};
+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 hashbrown::raw::RawTable;
+
+/// Compare GroupValue Rows column by column
+pub struct GroupValuesColumn {
+    /// 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: Vec<Box<dyn ArrayRowEq>>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+}
+
+impl GroupValuesColumn {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let map = RawTable::with_capacity(0);
+        Ok(Self {
+            schema,
+            map,
+            map_size: 0,
+            group_values: vec![],
+            hashes_buffer: Default::default(),
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesColumn {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        let n_rows = cols[0].len();
+
+        if self.group_values.is_empty() {
+            let mut v = Vec::with_capacity(cols.len());
+
+            for f in self.schema.fields().iter() {
+                let nullable = f.is_nullable();
+                match f.data_type() {
+                    &DataType::Int8 => {
+                        let b = PrimitiveGroupValueBuilder::<Int8Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int16 => {
+                        let b = PrimitiveGroupValueBuilder::<Int16Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int32 => {
+                        let b = PrimitiveGroupValueBuilder::<Int32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int64 => {
+                        let b = PrimitiveGroupValueBuilder::<Int64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt8 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt8Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt16 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt16Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt32 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt64 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Float32 => {
+                        let b = PrimitiveGroupValueBuilder::<Float32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Float64 => {
+                        let b = PrimitiveGroupValueBuilder::<Float64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Date32 => {
+                        let b = PrimitiveGroupValueBuilder::<Date32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Date64 => {
+                        let b = PrimitiveGroupValueBuilder::<Date64Type>::new(nullable);
+                        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 _)
+                    }
+                    &DataType::Binary => {
+                        let b = ByteGroupValueBuilder::<i32>::new(OutputType::Binary);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::LargeBinary => {
+                        let b = ByteGroupValueBuilder::<i64>::new(OutputType::Binary);
+                        v.push(Box::new(b) as _)
+                    }
+                    dt => todo!("{dt} not impl"),

Review Comment:
   in https://github.com/apache/datafusion/pull/12620



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2372471154

   I plan to spend some time tomorrow morning (my time) perhaps making some tweaks to this code (e,g no panics) and filing a ticket to track follow on work per @jayzhan211 's comment here: https://github.com/apache/datafusion/pull/12269#issuecomment-2369774073
   


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769504390


##########
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:
   I found my `take_n` for string is completely wrong 😅 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1740364031


##########
datafusion/physical-expr-common/src/group_value_row.rs:
##########
@@ -0,0 +1,624 @@
+// 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::buffer::NullBuffer;
+use arrow::buffer::OffsetBuffer;
+use arrow::buffer::ScalarBuffer;
+use arrow::datatypes::ArrowNativeType;
+use arrow::datatypes::DataType;
+use arrow::datatypes::GenericBinaryType;
+use arrow::datatypes::GenericStringType;
+use arrow::{
+    array::{Array, ArrayRef, ArrowPrimitiveType, AsArray, PrimitiveArray},
+    datatypes::ByteArrayType,
+};
+
+use crate::binary_map::OutputType;
+use crate::binary_map::INITIAL_BUFFER_CAPACITY;
+
+use std::sync::Arc;
+
+pub trait ArrayEq: 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 build(self: Box<Self>) -> ArrayRef;
+}
+
+pub struct PrimitiveGroupValueBuilder<T: ArrowPrimitiveType>(Vec<Option<T::Native>>);
+
+impl<T: ArrowPrimitiveType> PrimitiveGroupValueBuilder<T> {
+    pub fn new() -> Self {
+        Self(vec![])
+    }
+}
+
+impl<T: ArrowPrimitiveType> ArrayEq for PrimitiveGroupValueBuilder<T> {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> bool {

Review Comment:
   `equal_to` and `append_val` are two core functions.
   
   `equal_to` is to compare the incoming row with the row in group value builder
   `append_val` is to add row into group value builder



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2358621444

   Thanks @jayzhan211  -- I am running the benchmarks on this PR and plan to review it carefully either later today or tomorrow 
   
   🚀 


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2357214982

   > @jayzhan211 what is the status of this PR? Is it ready for another look? Do you need some help?
   
   The biggest challenge now is that the grouping sets result changed after I add the Float type support, and it seems that the result is not consistent with postgres. It is also not consistent for slt test on main branch.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2363878539

   this is next on my list


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2350774004

   ```
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃       main ┃  row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     0.53ms │     0.41ms │ +1.31x faster │
   │ QQuery 1     │    49.01ms │    41.52ms │ +1.18x faster │
   │ QQuery 2     │    88.41ms │    79.98ms │ +1.11x faster │
   │ QQuery 3     │    71.89ms │    73.76ms │     no change │
   │ QQuery 4     │   475.98ms │   435.24ms │ +1.09x faster │
   │ QQuery 5     │   715.67ms │   689.91ms │     no change │
   │ QQuery 6     │    36.87ms │    38.72ms │  1.05x slower │
   │ QQuery 7     │    42.85ms │    44.72ms │     no change │
   │ QQuery 8     │   767.47ms │   682.42ms │ +1.12x faster │
   │ QQuery 9     │   698.12ms │   687.16ms │     no change │
   │ QQuery 10    │   214.09ms │   202.99ms │ +1.05x faster │
   │ QQuery 11    │   233.88ms │   227.44ms │     no change │
   │ QQuery 12    │   765.70ms │   763.87ms │     no change │
   │ QQuery 13    │  1105.55ms │   967.40ms │ +1.14x faster │
   │ QQuery 14    │  1087.28ms │   904.65ms │ +1.20x faster │
   │ QQuery 15    │   538.36ms │   528.94ms │     no change │
   │ QQuery 16    │  1707.60ms │  1418.83ms │ +1.20x faster │
   │ QQuery 17    │  1580.22ms │  1281.82ms │ +1.23x faster │
   │ QQuery 18    │  4503.70ms │  4718.10ms │     no change │
   │ QQuery 19    │    58.30ms │    68.69ms │  1.18x slower │
   │ QQuery 20    │  1015.23ms │  1086.18ms │  1.07x slower │
   │ QQuery 21    │  1306.73ms │  1345.37ms │     no change │
   │ QQuery 22    │  3515.27ms │  3727.30ms │  1.06x slower │
   │ QQuery 23    │  8564.19ms │  8835.99ms │     no change │
   │ QQuery 24    │   509.14ms │   524.45ms │     no change │
   │ QQuery 25    │   506.78ms │   517.49ms │     no change │
   │ QQuery 26    │   586.24ms │   566.43ms │     no change │
   │ QQuery 27    │  1418.28ms │  1498.42ms │  1.06x slower │
   │ QQuery 28    │ 10867.59ms │ 11017.18ms │     no change │
   │ QQuery 29    │   410.02ms │   419.97ms │     no change │
   │ QQuery 30    │   865.76ms │   820.34ms │ +1.06x faster │
   │ QQuery 31    │   779.85ms │   776.05ms │     no change │
   │ QQuery 32    │  4989.34ms │  3710.45ms │ +1.34x faster │
   │ QQuery 33    │  5195.54ms │  5364.02ms │     no change │
   │ QQuery 34    │  4955.46ms │  5048.30ms │     no change │
   │ QQuery 35    │  1082.95ms │  1171.24ms │  1.08x slower │
   │ QQuery 36    │   143.30ms │   144.68ms │     no change │
   │ QQuery 37    │    99.65ms │   108.31ms │  1.09x slower │
   │ QQuery 38    │   104.12ms │   108.27ms │     no change │
   │ QQuery 39    │   383.56ms │   321.16ms │ +1.19x faster │
   │ QQuery 40    │    37.12ms │    36.89ms │     no change │
   │ QQuery 41    │    34.16ms │    33.11ms │     no change │
   │ QQuery 42    │    42.21ms │    41.49ms │     no change │
   └──────────────┴────────────┴────────────┴───────────────┘
   ```


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2350812028

   @alamb I found `FirstN` mode is non-trivial If I switch to Arrow's Builder instead of `Vec` what I had done before. Is it reasonable to implement `takeN` logic in Arrow's Builder upstream?


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2358797369

   I tried to run the benchmarks and they failed like this:
   
   ```
   ote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   thread 'tokio-runtime-worker' panicked at datafusion/physical-plan/src/aggregates/group_values/row_like.rs:161:31:
   not yet implemented: Binary not impl
   Error: External(Context("Join Error", External(JoinError::Panic(Id(26806), "not yet implemented: Binary not impl", ...))))
   ```


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2372076611

   I am running the benchmarks one more time


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1763644611


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -1380,24 +1380,16 @@ mod tests {
                 "+---+-----+-----------------+",
                 "| a | b   | COUNT(1)[count] |",
                 "+---+-----+-----------------+",
-                "|   | 1.0 | 1               |",

Review Comment:
   When in doubt, I always run in postgres to see what it says
   



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1762826775


##########
datafusion/physical-plan/src/aggregates/mod.rs:
##########
@@ -1380,24 +1380,16 @@ mod tests {
                 "+---+-----+-----------------+",
                 "| a | b   | COUNT(1)[count] |",
                 "+---+-----+-----------------+",
-                "|   | 1.0 | 1               |",

Review Comment:
   The change is consistent with the one that run in slt in `main`.
   Not sure which one is the expected behaviour 🤔 
   
   The only difference is that we use RowLike instead Row



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1769459683


##########
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:
   There is another difference. `GroupValuesRowLike` can handle mixed type like i32 + utf8. `GroupValuesPrimitive` could only be extended to multiple primitive types but not mixed with utf8. Otherwise, it will be the same as `GroupValuesRowLike` 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1771365793


##########
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:
   Another way is to handle single column with `GroupValuesColumn` (`GroupValuesRowLike`) without slowdown



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2372324497

   ```
   --------------------
   Benchmark clickbench_1.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃  main_base ┃  row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     0.65ms │     0.65ms │     no change │
   │ QQuery 1     │    69.31ms │    70.17ms │     no change │
   │ QQuery 2     │   126.99ms │   121.74ms │     no change │
   │ QQuery 3     │   134.96ms │   135.57ms │     no change │
   │ QQuery 4     │   993.97ms │   987.83ms │     no change │
   │ QQuery 5     │  1064.89ms │  1041.30ms │     no change │
   │ QQuery 6     │    66.24ms │    65.07ms │     no change │
   │ QQuery 7     │    82.73ms │    83.22ms │     no change │
   │ QQuery 8     │  1516.58ms │  1399.62ms │ +1.08x faster │
   │ QQuery 9     │  1380.23ms │  1403.17ms │     no change │
   │ QQuery 10    │   473.74ms │   454.26ms │     no change │
   │ QQuery 11    │   513.17ms │   503.41ms │     no change │
   │ QQuery 12    │  1200.73ms │  1207.25ms │     no change │
   │ QQuery 13    │  2175.58ms │  1856.97ms │ +1.17x faster │
   │ QQuery 14    │  1626.70ms │  1328.44ms │ +1.22x faster │
   │ QQuery 15    │  1152.71ms │  1150.77ms │     no change │
   │ QQuery 16    │  3058.97ms │  2612.74ms │ +1.17x faster │
   │ QQuery 17    │  2805.61ms │  2415.64ms │ +1.16x faster │
   │ QQuery 18    │  5904.12ms │  5091.17ms │ +1.16x faster │
   │ QQuery 19    │   122.17ms │   120.53ms │     no change │
   │ QQuery 20    │  1619.79ms │  1655.86ms │     no change │
   │ QQuery 21    │  2075.67ms │  2042.54ms │     no change │
   │ QQuery 22    │  4569.65ms │  4636.64ms │     no change │
   │ QQuery 23    │ 11455.17ms │ 11516.52ms │     no change │
   │ QQuery 24    │   744.04ms │   774.71ms │     no change │
   │ QQuery 25    │   662.80ms │   662.52ms │     no change │
   │ QQuery 26    │   824.42ms │   829.10ms │     no change │
   │ QQuery 27    │  2610.68ms │  2555.47ms │     no change │
   │ QQuery 28    │ 16169.74ms │ 16193.85ms │     no change │
   │ QQuery 29    │   571.62ms │   575.85ms │     no change │
   │ QQuery 30    │  1264.40ms │  1197.98ms │ +1.06x faster │
   │ QQuery 31    │  1331.55ms │  1284.00ms │     no change │
   │ QQuery 32    │  4779.21ms │  4314.61ms │ +1.11x faster │
   │ QQuery 33    │  5370.97ms │  5326.00ms │     no change │
   │ QQuery 34    │  5329.12ms │  5331.64ms │     no change │
   │ QQuery 35    │  1905.69ms │  1938.82ms │     no change │
   │ QQuery 36    │   318.31ms │   326.24ms │     no change │
   │ QQuery 37    │   209.91ms │   208.10ms │     no change │
   │ QQuery 38    │   191.92ms │   188.58ms │     no change │
   │ QQuery 39    │  1033.41ms │   798.70ms │ +1.29x faster │
   │ QQuery 40    │    89.63ms │    87.00ms │     no change │
   │ QQuery 41    │    79.13ms │    79.93ms │     no change │
   │ QQuery 42    │    89.63ms │    98.59ms │  1.10x slower │
   
   --------------------
   Benchmark clickbench_partitioned.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃  main_base ┃  row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     2.29ms │     2.24ms │     no change │
   │ QQuery 1     │    37.95ms │    36.63ms │     no change │
   │ QQuery 2     │    91.18ms │    94.10ms │     no change │
   │ QQuery 3     │    99.70ms │   102.18ms │     no change │
   │ QQuery 4     │   924.55ms │   922.81ms │     no change │
   │ QQuery 5     │   974.73ms │   967.65ms │     no change │
   │ QQuery 6     │    33.49ms │    34.13ms │     no change │
   │ QQuery 7     │    42.11ms │    40.81ms │     no change │
   │ QQuery 8     │  1462.34ms │  1401.97ms │     no change │
   │ QQuery 9     │  1347.10ms │  1352.15ms │     no change │
   │ QQuery 10    │   353.28ms │   343.14ms │     no change │
   │ QQuery 11    │   394.97ms │   397.55ms │     no change │
   │ QQuery 12    │  1080.53ms │  1083.58ms │     no change │
   │ QQuery 13    │  1816.98ms │  1745.72ms │     no change │
   │ QQuery 14    │  1502.91ms │  1261.70ms │ +1.19x faster │
   │ QQuery 15    │  1084.91ms │  1087.88ms │     no change │
   │ QQuery 16    │  2993.31ms │  2553.79ms │ +1.17x faster │
   │ QQuery 17    │  2693.79ms │  2368.53ms │ +1.14x faster │
   │ QQuery 18    │  5883.96ms │  4961.15ms │ +1.19x faster │
   │ QQuery 19    │    97.37ms │    93.87ms │     no change │
   │ QQuery 20    │  1676.69ms │  1723.33ms │     no change │
   │ QQuery 21    │  1958.76ms │  2012.30ms │     no change │
   │ QQuery 22    │  4715.60ms │  4695.54ms │     no change │
   │ QQuery 23    │ 10499.53ms │ 10452.82ms │     no change │
   │ QQuery 24    │   586.87ms │   575.49ms │     no change │
   │ QQuery 25    │   504.91ms │   491.04ms │     no change │
   │ QQuery 26    │   649.56ms │   657.69ms │     no change │
   │ QQuery 27    │  2557.90ms │  2536.86ms │     no change │
   │ QQuery 28    │ 15545.61ms │ 15410.83ms │     no change │
   │ QQuery 29    │   515.39ms │   522.92ms │     no change │
   │ QQuery 30    │  1101.35ms │  1076.15ms │     no change │
   │ QQuery 31    │  1171.23ms │  1093.86ms │ +1.07x faster │
   │ QQuery 32    │  4797.56ms │  4238.85ms │ +1.13x faster │
   │ QQuery 33    │  5217.26ms │  5227.87ms │     no change │
   │ QQuery 34    │  5185.00ms │  5195.91ms │     no change │
   │ QQuery 35    │  1862.76ms │  2149.75ms │  1.15x slower │
   │ QQuery 36    │   277.32ms │   258.05ms │ +1.07x faster │
   │ QQuery 37    │   122.28ms │   122.62ms │     no change │
   │ QQuery 38    │   140.98ms │   145.85ms │     no change │
   │ QQuery 39    │   984.01ms │   775.28ms │ +1.27x faster │
   │ QQuery 40    │    59.33ms │    54.72ms │ +1.08x faster │
   │ QQuery 41    │    50.05ms │    46.63ms │ +1.07x faster │
   │ QQuery 42    │    61.86ms │    63.49ms │     no change │
   └──────────────┴────────────┴────────────┴───────────────┘
   
   --------------------
   Benchmark tpch_sf1.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃ main_base ┃ row-group ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 1     │  252.62ms │  211.14ms │ +1.20x faster │
   │ QQuery 2     │  131.31ms │  120.09ms │ +1.09x faster │
   │ QQuery 3     │  138.74ms │  114.57ms │ +1.21x faster │
   │ QQuery 4     │   92.29ms │   84.86ms │ +1.09x faster │
   │ QQuery 5     │  180.88ms │  158.23ms │ +1.14x faster │
   │ QQuery 6     │   60.26ms │   44.42ms │ +1.36x faster │
   │ QQuery 7     │  223.37ms │  201.96ms │ +1.11x faster │
   │ QQuery 8     │  165.38ms │  149.05ms │ +1.11x faster │
   │ QQuery 9     │  259.49ms │  239.59ms │ +1.08x faster │
   │ QQuery 10    │  244.94ms │  216.64ms │ +1.13x faster │
   │ QQuery 11    │  104.23ms │   92.60ms │ +1.13x faster │
   │ QQuery 12    │  135.08ms │  144.47ms │  1.07x slower │
   │ QQuery 13    │  304.56ms │  213.47ms │ +1.43x faster │
   │ QQuery 14    │   97.08ms │   72.11ms │ +1.35x faster │
   │ QQuery 15    │  128.14ms │  115.86ms │ +1.11x faster │
   │ QQuery 16    │   85.69ms │   80.46ms │ +1.07x faster │
   │ QQuery 17    │  246.47ms │  201.71ms │ +1.22x faster │
   │ QQuery 18    │  344.79ms │  316.85ms │ +1.09x faster │
   │ QQuery 19    │  162.78ms │  138.60ms │ +1.17x faster │
   │ QQuery 20    │  145.63ms │  137.61ms │ +1.06x faster │
   │ QQuery 21    │  276.08ms │  273.78ms │     no change │
   │ QQuery 22    │   65.63ms │   65.42ms │     no change │
   └──────────────┴───────────┴───────────┴───────────────┘
   
   ```


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi column grouping (10% faster clickbench queries) [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1773892921


##########
datafusion/physical-plan/src/aggregates/group_values/mod.rs:
##########
@@ -92,5 +96,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(GroupValuesColumn::try_new(schema)?))
+    } else {
+        Ok(Box::new(GroupValuesRows::try_new(schema)?))
+    }
+}
+
+fn has_row_like_feature(data_type: &DataType) -> bool {

Review Comment:
   Minor nit -- but since this list of types needs to remain in sync with `GroupValuesColumn` it might make sense to move it into that module too
   
   Like `GroupValuesColumn::is_supported` or something



##########
datafusion/physical-plan/src/aggregates/group_values/group_value_row.rs:
##########
@@ -0,0 +1,456 @@
+// 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 datafusion_common::utils::proxy::VecAllocExt;
+
+use std::sync::Arc;
+use std::vec;
+
+use datafusion_physical_expr_common::binary_map::{OutputType, INITIAL_BUFFER_CAPACITY};
+
+/// 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 the number of bytes used by this [`ArrayRowEq`]
+    fn size(&self) -> usize;
+    /// 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;
+}
+
+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) {
+        if self.nullable && array.is_null(row) {
+            self.group_values.push(T::default_value());
+            self.nulls.push(false);
+            self.has_null = true;
+        } else {
+            let elem = array.as_primitive::<T>().value(row);
+            self.group_values.push(elem);
+            self.nulls.push(true);
+        }
+    }
+
+    fn len(&self) -> usize {
+        self.group_values.len()
+    }
+
+    fn size(&self) -> usize {
+        self.group_values.allocated_size() + self.nulls.allocated_size()
+    }
+
+    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, if `i` is in nulls, `offsets[i]` should be equals to `offsets[i+1]`
+    nulls: Vec<usize>,

Review Comment:
   Is there a reason to use Vec<usize> rather than `Vec<bool>` as used in `PrimitiveGroupValueBuilder`?
   
   Maybe as a follow on PR we can explore using [`BooleanBufferBuilder`](https://docs.rs/datafusion/latest/datafusion/common/arrow/array/struct.BooleanBufferBuilder.html) from arrow-rs directly



##########
datafusion/physical-plan/src/aggregates/group_values/column_wise.rs:
##########
@@ -0,0 +1,314 @@
+// 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::group_value_row::{
+    ArrayRowEq, ByteGroupValueBuilder, PrimitiveGroupValueBuilder,
+};
+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 hashbrown::raw::RawTable;
+
+/// Compare GroupValue Rows column by column
+pub struct GroupValuesColumn {
+    /// 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: Vec<Box<dyn ArrayRowEq>>,
+
+    /// reused buffer to store hashes
+    hashes_buffer: Vec<u64>,
+
+    /// Random state for creating hashes
+    random_state: RandomState,
+}
+
+impl GroupValuesColumn {
+    pub fn try_new(schema: SchemaRef) -> Result<Self> {
+        let map = RawTable::with_capacity(0);
+        Ok(Self {
+            schema,
+            map,
+            map_size: 0,
+            group_values: vec![],
+            hashes_buffer: Default::default(),
+            random_state: Default::default(),
+        })
+    }
+}
+
+impl GroupValues for GroupValuesColumn {
+    fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec<usize>) -> Result<()> {
+        let n_rows = cols[0].len();
+
+        if self.group_values.is_empty() {
+            let mut v = Vec::with_capacity(cols.len());
+
+            for f in self.schema.fields().iter() {
+                let nullable = f.is_nullable();
+                match f.data_type() {
+                    &DataType::Int8 => {
+                        let b = PrimitiveGroupValueBuilder::<Int8Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int16 => {
+                        let b = PrimitiveGroupValueBuilder::<Int16Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int32 => {
+                        let b = PrimitiveGroupValueBuilder::<Int32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Int64 => {
+                        let b = PrimitiveGroupValueBuilder::<Int64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt8 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt8Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt16 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt16Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt32 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::UInt64 => {
+                        let b = PrimitiveGroupValueBuilder::<UInt64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Float32 => {
+                        let b = PrimitiveGroupValueBuilder::<Float32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Float64 => {
+                        let b = PrimitiveGroupValueBuilder::<Float64Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Date32 => {
+                        let b = PrimitiveGroupValueBuilder::<Date32Type>::new(nullable);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::Date64 => {
+                        let b = PrimitiveGroupValueBuilder::<Date64Type>::new(nullable);
+                        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 _)
+                    }
+                    &DataType::Binary => {
+                        let b = ByteGroupValueBuilder::<i32>::new(OutputType::Binary);
+                        v.push(Box::new(b) as _)
+                    }
+                    &DataType::LargeBinary => {
+                        let b = ByteGroupValueBuilder::<i64>::new(OutputType::Binary);
+                        v.push(Box::new(b) as _)
+                    }
+                    dt => todo!("{dt} not impl"),

Review Comment:
   It would be nice if this was an internal error rather than a panic



##########
datafusion/sqllogictest/test_files/group_by.slt:
##########
@@ -5148,3 +5148,42 @@ NULL
 
 statement ok
 drop table test_case_expr
+
+statement ok
+drop table t;
+
+# test multi group by for binary type with nulls
+statement ok
+create table t(a int, b bytea) as values (1, 0xa), (1, 0xa), (2, null), (null, 0xb), (null, 0xb);
+
+query I?I
+select a, b, count(*) from t group by grouping sets ((a, b), (a), (b));

Review Comment:
   That appears to be added above by @jayzhan211 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#issuecomment-2324460170

   Thanks @jayzhan211  -- I will try and review this over the next day or two


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Avoid RowConverter for multi group by [datafusion]

Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #12269:
URL: https://github.com/apache/datafusion/pull/12269#discussion_r1751067326


##########
benchmarks/queries/clickbench/queries.sql:
##########
@@ -35,9 +35,4 @@ SELECT "URL", COUNT(*) AS c FROM hits GROUP BY "URL" ORDER BY c DESC LIMIT 10;
 SELECT 1, "URL", COUNT(*) AS c FROM hits GROUP BY 1, "URL" ORDER BY c DESC LIMIT 10;
 SELECT "ClientIP", "ClientIP" - 1, "ClientIP" - 2, "ClientIP" - 3, COUNT(*) AS c FROM hits GROUP BY "ClientIP", "ClientIP" - 1, "ClientIP" - 2, "ClientIP" - 3 ORDER BY c DESC LIMIT 10;
 SELECT "URL", COUNT(*) AS PageViews FROM hits WHERE "CounterID" = 62 AND "EventDate"::INT::DATE >= '2013-07-01' AND "EventDate"::INT::DATE <= '2013-07-31' AND "DontCountHits" = 0 AND "IsRefresh" = 0 AND "URL" <> '' GROUP BY "URL" ORDER BY PageViews DESC LIMIT 10;
-SELECT "Title", COUNT(*) AS PageViews FROM hits WHERE "CounterID" = 62 AND "EventDate"::INT::DATE >= '2013-07-01' AND "EventDate"::INT::DATE <= '2013-07-31' AND "DontCountHits" = 0 AND "IsRefresh" = 0 AND "Title" <> '' GROUP BY "Title" ORDER BY PageViews DESC LIMIT 10;

Review Comment:
   Because I haven't implement DateTime builder, so couldn't pass the test



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org