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


##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/dictionary.rs:
##########
@@ -0,0 +1,373 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::aggregates::group_values::multi_group_by::GroupColumn;
+use arrow::array::{
+    Array, ArrayRef, AsArray, BooleanBufferBuilder, DictionaryArray, 
PrimitiveArray,
+};
+use arrow::datatypes::{ArrowDictionaryKeyType, ArrowNativeType, DataType, 
Field};
+use datafusion_common::{Result, exec_err};
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] implementation for dictionary arrays.
+/// wraps an inner [`GroupColumn`] that stores the dictionary values, and uses 
a null sentinel for null keys.
+pub struct DictionaryGroupValuesColumn<K: ArrowDictionaryKeyType + Send + 
Sync> {
+    inner: Box<dyn GroupColumn>,
+    // unary array used as a null sentinel for dictionary keys that are null
+    null_array: ArrayRef,
+    _phantom: PhantomData<K>,
+}
+
+impl<K: ArrowDictionaryKeyType + Send + Sync> DictionaryGroupValuesColumn<K> {
+    pub fn new(inner: Box<dyn GroupColumn>, field: &Field) -> Self {
+        let null_array = arrow::array::new_null_array(field.data_type(), 1);
+        Self {
+            inner,
+            null_array,
+            _phantom: PhantomData,
+        }
+    }
+
+    fn into_dict(values: ArrayRef) -> ArrayRef {
+        let num_values = values.len();
+        let keys: PrimitiveArray<K> = (0..num_values)
+            .map(|i| (!values.is_null(i)).then(|| K::Native::usize_as(i)))
+            .collect();
+        Arc::new(DictionaryArray::<K>::new(keys, values))
+    }
+
+    /// Returns the index of the first null in `values`, or `None` if there 
are no nulls.
+    fn null_sentinel_index(values: &ArrayRef) -> Option<usize> {
+        values.nulls()?.iter().position(|valid| !valid)
+    }
+
+    /// Returns an error if adding `additional` groups would overflow the key 
type's range.
+    // https://github.com/apache/datafusion/issues/23127
+    fn check_key_overflow(current_len: usize, additional: usize) -> Result<()> 
{
+        if !Self::valid_bounds::<K>(current_len + additional) {

Review Comment:
   > In a multi-column group-by, there can be more than 128 groups while an 
Int8 dictionary still has only a few distinct values. Told row path will 
successfully emits 129 groups with two dictionary values while this path return 
will be overflow error. 
   
   
   I created this test off of the main branch to test `GroupValueRows`
   ```rust
   fn test_dictionary_emit_logic() {
           let schema = Arc::new(Schema::new(vec![Field::new(
               "categories",
               DataType::Dictionary(Box::new(DataType::UInt8), 
Box::new(DataType::Utf8)),
               false,
           )]));
           let keys: Vec<u8> = (0..1000).map(|i| (i % 255) as u8).collect();
           let values = (0..255)
               .map(|i| format!("category_{}", i))
               .collect::<Vec<_>>();
   
           let values_vec: Vec<Option<&str>> =
               values.iter().map(|s| Some(s.as_str())).collect();
           let values_arr = Arc::new(StringArray::from(values_vec));
   
           let key_array = PrimitiveArray::<UInt8Type>::from(keys);
           let dict_array = Arc::new(
               DictionaryArray::<UInt8Type>::try_new(key_array, 
values_arr).unwrap(),
           ) as ArrayRef;
           let mut group_values_rows =
               new_group_values(schema, &GroupOrdering::None).unwrap();
           let mut groups = Vec::new();
           group_values_rows
               .intern(&[dict_array], &mut groups)
               .unwrap();
   
           let size = group_values_rows.len();
           // we are now at the max valid size to represent a uint8 key
           assert_eq!(size, 255);
   
           // Add two more groups and verify count rises to 257
           let additional_keys: Vec<u8> = vec![0, 1];
           let additional_values = vec![Some("extra_0"), Some("extra_1")];
           let key_array = PrimitiveArray::<UInt8Type>::from(additional_keys);
           let values_arr = Arc::new(StringArray::from(additional_values));
   
           let additional_dict_array = Arc::new(
               DictionaryArray::<UInt8Type>::try_new(key_array, 
values_arr).unwrap(),
           ) as ArrayRef;
   
           group_values_rows
               .intern(&[additional_dict_array], &mut groups)
               .unwrap();
           let new_size = group_values_rows.len();
           assert_eq!(new_size, 257);
   
           let output = group_values_rows.emit(super::EmitTo::All).unwrap();
           assert_eq!(output.len(), 1);
           let output_array = &output[0];
           assert_eq!(
               output_array.data_type(),
               &DataType::Dictionary(Box::new(DataType::UInt8), 
Box::new(DataType::Utf8))
           );
       }
   ```
   it panics on the `.emit(All).unwrap` call with this error
   ```
   thread 'aggregates::group_values::row::test::test_dictionary_emit_logic' 
(51728094) panicked at 
datafusion/physical-plan/src/aggregates/group_values/row.rs:390:65:
   called `Result::unwrap()` on an `Err` value: 
ArrowError(DictionaryKeyOverflowError, Some(""))
   ```
   
   This behavior already exist in `GroupValuesRows` this is because of the cast 
the happens in the emit path. if the strings `RowConverter` produces cannot be 
cast to the input schemas dictionary key type it will just fail.
   
   
   
   >Could we preserve dictionary encoding during emit, or keep narrow key types 
on the fallback path? Please also add this as a regression test.
   
   If `emit::all`/`build` is called, we need to produce every distinct value 
we've stored. If the number of stored values exceeds what the key type can 
represent, we can only emit the first key-type-sized number of outputs — e.g., 
if we've stored 300 distinct values but the input key type is uint8, we can 
only emit 255, which is logically incorrect.
   This matches existing behavior, so it won't introduce a regression, but it's 
worth fixing properly down the line, I've opened #23127 to track it, and I'll 
add a regression test to document the current behavior.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to