coderfender commented on code in PR #2600: URL: https://github.com/apache/datafusion-comet/pull/2600#discussion_r2547766132
########## native/spark-expr/src/agg_funcs/sum_int.rs: ########## @@ -0,0 +1,576 @@ +// 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::{arithmetic_overflow_error, EvalMode}; +use arrow::array::{ + cast::AsArray, Array, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, BooleanArray, + Int64Array, PrimitiveArray, +}; +use arrow::datatypes::{ + ArrowNativeType, DataType, Field, FieldRef, Int16Type, Int32Type, Int64Type, Int8Type, +}; +use datafusion::common::{DataFusionError, Result as DFResult, ScalarValue}; +use datafusion::logical_expr::function::{AccumulatorArgs, StateFieldsArgs}; +use datafusion::logical_expr::Volatility::Immutable; +use datafusion::logical_expr::{ + Accumulator, AggregateUDFImpl, EmitTo, GroupsAccumulator, ReversedUDAF, Signature, +}; +use std::{any::Any, sync::Arc}; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SumInteger { + signature: Signature, + eval_mode: EvalMode, +} + +impl SumInteger { + pub fn try_new(data_type: DataType, eval_mode: EvalMode) -> DFResult<Self> { + match data_type { + DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => Ok(Self { + signature: Signature::user_defined(Immutable), + eval_mode, + }), + _ => Err(DataFusionError::Internal( + "Invalid data type for SumInteger".into(), + )), + } + } +} + +impl AggregateUDFImpl for SumInteger { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "sum" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> DFResult<DataType> { + Ok(DataType::Int64) + } + + fn accumulator(&self, _acc_args: AccumulatorArgs) -> DFResult<Box<dyn Accumulator>> { + Ok(Box::new(SumIntegerAccumulator::new(self.eval_mode))) + } + + fn state_fields(&self, _args: StateFieldsArgs) -> DFResult<Vec<FieldRef>> { + if self.eval_mode == EvalMode::Try { + Ok(vec![ + Arc::new(Field::new("sum", DataType::Int64, true)), + Arc::new(Field::new("has_all_nulls", DataType::Boolean, false)), + ]) + } else { + Ok(vec![Arc::new(Field::new("sum", DataType::Int64, true))]) + } + } + + fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool { + true + } + + fn create_groups_accumulator( + &self, + _args: AccumulatorArgs, + ) -> DFResult<Box<dyn GroupsAccumulator>> { + Ok(Box::new(SumIntGroupsAccumulator::new(self.eval_mode))) + } + + fn reverse_expr(&self) -> ReversedUDAF { + ReversedUDAF::Identical + } +} + +#[derive(Debug)] +struct SumIntegerAccumulator { + sum: Option<i64>, + eval_mode: EvalMode, + has_all_nulls: bool, +} + +impl SumIntegerAccumulator { + fn new(eval_mode: EvalMode) -> Self { + if eval_mode == EvalMode::Try { + Self { + // Try mode starts with 0 (because if this is init to None we cant say if it is none due to all nulls or due to an overflow) + sum: Some(0), + has_all_nulls: true, + eval_mode, + } + } else { + Self { + sum: None, + has_all_nulls: false, + eval_mode, + } + } + } +} + +impl Accumulator for SumIntegerAccumulator { + fn update_batch(&mut self, values: &[ArrayRef]) -> DFResult<()> { + // accumulator internal to add sum and return null sum (and has_nulls false) if there is an overflow in Try Eval mode + fn update_sum_internal<T>( + int_array: &PrimitiveArray<T>, + eval_mode: EvalMode, + mut sum: i64, + ) -> Result<Option<i64>, DataFusionError> + where + T: ArrowPrimitiveType, + { + for i in 0..int_array.len() { + if !int_array.is_null(i) { + let v = int_array.value(i).to_i64().unwrap(); + match eval_mode { + EvalMode::Legacy => { + sum = v.add_wrapping(sum); + } + EvalMode::Ansi | EvalMode::Try => { + match v.add_checked(sum) { + Ok(v) => sum = v, + Err(_e) => { + return if eval_mode == EvalMode::Ansi { + Err(DataFusionError::from(arithmetic_overflow_error( + "integer", + ))) + } else { + Ok(None) + }; + } + }; + } + } + } + } + Ok(Some(sum)) + } + + if self.eval_mode == EvalMode::Try && !self.has_all_nulls && self.sum.is_none() { + // we saw an overflow earlier (Try eval mode). Skip processing + return Ok(()); + } + let values = &values[0]; + if values.len() == values.null_count() { + Ok(()) + } else { + // No nulls so there should be a non-null sum / null incase overflow in Try eval + let running_sum = self.sum.unwrap_or(0); + let sum = match values.data_type() { + DataType::Int64 => update_sum_internal( + values + .as_any() + .downcast_ref::<PrimitiveArray<Int64Type>>() + .unwrap(), + self.eval_mode, + running_sum, + )?, + DataType::Int32 => update_sum_internal( + values + .as_any() + .downcast_ref::<PrimitiveArray<Int32Type>>() + .unwrap(), + self.eval_mode, + running_sum, + )?, + DataType::Int16 => update_sum_internal( + values + .as_any() + .downcast_ref::<PrimitiveArray<Int16Type>>() + .unwrap(), + self.eval_mode, + running_sum, + )?, + DataType::Int8 => update_sum_internal( + values + .as_any() + .downcast_ref::<PrimitiveArray<Int8Type>>() + .unwrap(), + self.eval_mode, + running_sum, + )?, + _ => { + return Err(DataFusionError::Internal(format!( + "unsupported data type: {:?}", + values.data_type() + ))); + } + }; + self.sum = sum; + self.has_all_nulls = false; + Ok(()) + } + } + + fn evaluate(&mut self) -> DFResult<ScalarValue> { + if self.has_all_nulls { + Ok(ScalarValue::Int64(None)) + } else { + Ok(ScalarValue::Int64(self.sum)) + } + } + + fn size(&self) -> usize { + std::mem::size_of_val(self) + } + + fn state(&mut self) -> DFResult<Vec<ScalarValue>> { + if self.eval_mode == EvalMode::Try { + Ok(vec![ + ScalarValue::Int64(self.sum), + ScalarValue::Boolean(Some(self.has_all_nulls)), + ]) + } else { + Ok(vec![ScalarValue::Int64(self.sum)]) + } + } + + fn merge_batch(&mut self, states: &[ArrayRef]) -> DFResult<()> { + let that_sum_array = states[0].as_primitive::<Int64Type>(); + let that_sum = if that_sum_array.is_null(0) { + None + } else { + Some(that_sum_array.value(0)) + }; + + // Check for overflow for early termination + if self.eval_mode == EvalMode::Try { + let that_has_all_nulls = states[1].as_boolean().value(0); + let that_overflowed = !that_has_all_nulls && that_sum.is_none(); + let this_overflowed = !self.has_all_nulls && self.sum.is_none(); + if that_overflowed || this_overflowed { + self.sum = None; + self.has_all_nulls = false; + return Ok(()); + } + self.has_all_nulls = self.has_all_nulls && that_has_all_nulls; + if that_has_all_nulls { + return Ok(()); + } + if self.has_all_nulls { + self.sum = that_sum; + return Ok(()); + } + } else { + if that_sum.is_none() { + return Ok(()); + } + if self.sum.is_none() { + self.sum = that_sum; + return Ok(()); + } + } + + let left = self.sum.unwrap(); + let right = that_sum.unwrap(); Review Comment: Sure. We are essentially checking the `has_null` arrays for early termination in Try mode and also explicitly checking if the sums are nulls in non-try mode (for early termination) which should make these unwraps safe. However, I do agree that we could add exception handling here to handle corrupt state situations. In try mode : ` let that_has_all_nulls = states[1].as_boolean().value(0); let that_overflowed = !that_has_all_nulls && that_sum.is_none(); let this_overflowed = !self.has_all_nulls && self.sum.is_none(); if that_overflowed || this_overflowed { self.sum = None; self.has_all_nulls = false; return Ok(()); } self.has_all_nulls = self.has_all_nulls && that_has_all_nulls; if that_has_all_nulls { return Ok(()); } if self.has_all_nulls { self.sum = that_sum; return Ok(()); } ` -- 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]
