Apache DataFusion SQL Query Engine
fix: overcounting of memory in first/last. (#15924)
Eshed Schachamd6fe1defb728
diff --git a/datafusion/common/src/scalar/mod.rs b/datafusion/common/src/scalar/mod.rsindex 8d0d6ed5a1..6558ea3fe4 100644--- a/datafusion/common/src/scalar/mod.rs+++ b/datafusion/common/src/scalar/mod.rs@@ -3449,49 +3449,80 @@ impl ScalarValue {.sum::<usize>()}- /// Performs a deep clone of the ScalarValue, creating new copies of all nested data structures.- /// This is different from the standard `clone()` which may share data through `Arc`.- /// Aggregation functions like `max` will cost a lot of memory if the data is not cloned.- pub fn force_clone(&self) -> Self {+ /// Compacts the allocation referenced by `self` to the minimum, copying the data if+ /// necessary.+ ///+ /// This can be relevant when `self` is a list or contains a list as a nested value, as+ /// a single list holds an Arc to its entire original array buffer.+ pub fn compact(&mut self) {match self {- // Complex types need deep clone of their contents- ScalarValue::List(array) => {- let array = copy_array_data(&array.to_data());- let new_array = ListArray::from(array);- ScalarValue::List(Arc::new(new_array))+ ScalarValue::Null+ | ScalarValue::Boolean(_)+ | ScalarValue::Float16(_)+ | ScalarValue::Float32(_)+ | ScalarValue::Float64(_)+ | ScalarValue::Decimal128(_, _, _)+ | ScalarValue::Decimal256(_, _, _)+ | ScalarValue::Int8(_)+ | ScalarValue::Int16(_)+ | ScalarValue::Int32(_)+ | ScalarValue::Int64(_)+ | ScalarValue::UInt8(_)+ | ScalarValue::UInt16(_)+ | ScalarValue::UInt32(_)+ | ScalarValue::UInt64(_)+ | ScalarValue::Date32(_)+ | ScalarValue::Date64(_)+ | ScalarValue::Time32Second(_)+ | ScalarValue::Time32Millisecond(_)+ | ScalarValue::Time64Microsecond(_)+ | ScalarValue::Time64Nanosecond(_)+ | ScalarValue::IntervalYearMonth(_)+ | ScalarValue::IntervalDayTime(_)+ | ScalarValue::IntervalMonthDayNano(_)+ | ScalarValue::DurationSecond(_)+ | ScalarValue::DurationMillisecond(_)+ | ScalarValue::DurationMicrosecond(_)+ | ScalarValue::DurationNanosecond(_)+ | ScalarValue::Utf8(_)+ | ScalarValue::LargeUtf8(_)+ | ScalarValue::Utf8View(_)+ | ScalarValue::TimestampSecond(_, _)+ | ScalarValue::TimestampMillisecond(_, _)+ | ScalarValue::TimestampMicrosecond(_, _)+ | ScalarValue::TimestampNanosecond(_, _)+ | ScalarValue::Binary(_)+ | ScalarValue::FixedSizeBinary(_, _)+ | ScalarValue::LargeBinary(_)+ | ScalarValue::BinaryView(_) => (),+ ScalarValue::FixedSizeList(arr) => {+ let array = copy_array_data(&arr.to_data());+ *Arc::make_mut(arr) = FixedSizeListArray::from(array);}- ScalarValue::LargeList(array) => {- let array = copy_array_data(&array.to_data());- let new_array = LargeListArray::from(array);- ScalarValue::LargeList(Arc::new(new_array))+ ScalarValue::List(arr) => {+ let array = copy_array_data(&arr.to_data());+ *Arc::make_mut(arr) = ListArray::from(array);}- ScalarValue::FixedSizeList(arr) => {+ ScalarValue::LargeList(arr) => {let array = copy_array_data(&arr.to_data());- let new_array = FixedSizeListArray::from(array);- ScalarValue::FixedSizeList(Arc::new(new_array))+ *Arc::make_mut(arr) = LargeListArray::from(array)}ScalarValue::Struct(arr) => {let array = copy_array_data(&arr.to_data());- let new_array = StructArray::from(array);- ScalarValue::Struct(Arc::new(new_array))+ *Arc::make_mut(arr) = StructArray::from(array);}ScalarValue::Map(arr) => {let array = copy_array_data(&arr.to_data());- let new_array = MapArray::from(array);- ScalarValue::Map(Arc::new(new_array))- }- ScalarValue::Union(Some((type_id, value)), fields, mode) => {- let new_value = Box::new(value.force_clone());- ScalarValue::Union(Some((*type_id, new_value)), fields.clone(), *mode)+ *Arc::make_mut(arr) = MapArray::from(array);}- ScalarValue::Union(None, fields, mode) => {- ScalarValue::Union(None, fields.clone(), *mode)+ ScalarValue::Union(val, _, _) => {+ if let Some((_, value)) = val.as_mut() {+ value.compact();+ }}- ScalarValue::Dictionary(key_type, value) => {- let new_value = Box::new(value.force_clone());- ScalarValue::Dictionary(key_type.clone(), new_value)+ ScalarValue::Dictionary(_, value) => {+ value.compact();}- _ => self.clone(),}}}diff --git a/datafusion/functions-aggregate/src/first_last.rs b/datafusion/functions-aggregate/src/first_last.rsindex ec8c440b77..530b462080 100644--- a/datafusion/functions-aggregate/src/first_last.rs+++ b/datafusion/functions-aggregate/src/first_last.rs@@ -752,7 +752,7 @@ wherefn size(&self) -> usize {self.vals.capacity() * size_of::<T::Native>()- + self.null_builder.capacity() / 8 // capacity is in bits, so convert to bytes+ + self.null_builder.capacity() / 8 // capacity is in bits, so convert to bytes+ self.is_sets.capacity() / 8+ self.size_of_orderings+ self.min_of_each_group_buf.0.capacity() * size_of::<usize>()@@ -827,9 +827,14 @@ impl FirstValueAccumulator {}// Updates state with the values in the given row.- fn update_with_new_row(&mut self, row: &[ScalarValue]) {- self.first = row[0].clone();- self.orderings = row[1..].to_vec();+ fn update_with_new_row(&mut self, mut row: Vec<ScalarValue>) {+ // Ensure any Array based scalars hold have a single value to reduce memory pressure+ row.iter_mut().for_each(|s| {+ s.compact();+ });++ self.first = row.remove(0);+ self.orderings = row;self.is_set = true;}@@ -888,7 +893,7 @@ impl Accumulator for FirstValueAccumulator {if !self.is_set {if let Some(first_idx) = self.get_first_idx(values)? {let row = get_row_at_idx(values, first_idx)?;- self.update_with_new_row(&row);+ self.update_with_new_row(row);}} else if !self.requirement_satisfied {if let Some(first_idx) = self.get_first_idx(values)? {@@ -901,7 +906,7 @@ impl Accumulator for FirstValueAccumulator {)?.is_gt(){- self.update_with_new_row(&row);+ self.update_with_new_row(row);}}}@@ -925,7 +930,7 @@ impl Accumulator for FirstValueAccumulator {let min = (0..filtered_states[0].len()).min_by(|&a, &b| comparator.compare(a, b));if let Some(first_idx) = min {- let first_row = get_row_at_idx(&filtered_states, first_idx)?;+ let mut first_row = get_row_at_idx(&filtered_states, first_idx)?;// When collecting orderings, we exclude the is_set flag from the state.let first_ordering = &first_row[1..is_set_idx];let sort_options = get_sort_options(self.ordering_req.as_ref());@@ -936,7 +941,9 @@ impl Accumulator for FirstValueAccumulator {// Update with first value in the state. Note that we should exclude the// is_set flag from the state. Otherwise, we will end up with a state// containing two is_set flags.- self.update_with_new_row(&first_row[0..is_set_idx]);+ assert!(is_set_idx <= first_row.len());+ first_row.resize(is_set_idx, ScalarValue::Null);+ self.update_with_new_row(first_row);}}Ok(())@@ -1226,9 +1233,14 @@ impl LastValueAccumulator {}// Updates state with the values in the given row.- fn update_with_new_row(&mut self, row: &[ScalarValue]) {- self.last = row[0].clone();- self.orderings = row[1..].to_vec();+ fn update_with_new_row(&mut self, mut row: Vec<ScalarValue>) {+ // Ensure any Array based scalars hold have a single value to reduce memory pressure+ row.iter_mut().for_each(|s| {+ s.compact();+ });++ self.last = row.remove(0);+ self.orderings = row;self.is_set = true;}@@ -1289,7 +1301,7 @@ impl Accumulator for LastValueAccumulator {if !self.is_set || self.requirement_satisfied {if let Some(last_idx) = self.get_last_idx(values)? {let row = get_row_at_idx(values, last_idx)?;- self.update_with_new_row(&row);+ self.update_with_new_row(row);}} else if let Some(last_idx) = self.get_last_idx(values)? {let row = get_row_at_idx(values, last_idx)?;@@ -1302,7 +1314,7 @@ impl Accumulator for LastValueAccumulator {)?.is_lt(){- self.update_with_new_row(&row);+ self.update_with_new_row(row);}}@@ -1326,7 +1338,7 @@ impl Accumulator for LastValueAccumulator {let max = (0..filtered_states[0].len()).max_by(|&a, &b| comparator.compare(a, b));if let Some(last_idx) = max {- let last_row = get_row_at_idx(&filtered_states, last_idx)?;+ let mut last_row = get_row_at_idx(&filtered_states, last_idx)?;// When collecting orderings, we exclude the is_set flag from the state.let last_ordering = &last_row[1..is_set_idx];let sort_options = get_sort_options(self.ordering_req.as_ref());@@ -1339,7 +1351,9 @@ impl Accumulator for LastValueAccumulator {// Update with last value in the state. Note that we should exclude the// is_set flag from the state. Otherwise, we will end up with a state// containing two is_set flags.- self.update_with_new_row(&last_row[0..is_set_idx]);+ assert!(is_set_idx <= last_row.len());+ last_row.resize(is_set_idx, ScalarValue::Null);+ self.update_with_new_row(last_row);}}Ok(())@@ -1382,7 +1396,13 @@ fn convert_to_sort_cols(arrs: &[ArrayRef], sort_exprs: &LexOrdering) -> Vec<Sort#[cfg(test)]mod tests {- use arrow::{array::Int64Array, compute::SortOptions, datatypes::Schema};+ use std::iter::repeat_with;++ use arrow::{+ array::{Int64Array, ListArray},+ compute::SortOptions,+ datatypes::Schema,+ };use datafusion_physical_expr::{expressions::col, PhysicalSortExpr};use super::*;@@ -1772,4 +1792,60 @@ mod tests {Ok(())}++ #[test]+ fn test_first_list_acc_size() -> Result<()> {+ fn size_after_batch(values: &[ArrayRef]) -> Result<usize> {+ let mut first_accumulator = FirstValueAccumulator::try_new(+ &DataType::List(Arc::new(Field::new_list_field(DataType::Int64, false))),+ &[],+ LexOrdering::default(),+ false,+ )?;++ first_accumulator.update_batch(values)?;++ Ok(first_accumulator.size())+ }++ let batch1 = ListArray::from_iter_primitive::<Int32Type, _, _>(+ repeat_with(|| Some(vec![Some(1)])).take(10000),+ );+ let batch2 =+ ListArray::from_iter_primitive::<Int32Type, _, _>([Some(vec![Some(1)])]);++ let size1 = size_after_batch(&[Arc::new(batch1)])?;+ let size2 = size_after_batch(&[Arc::new(batch2)])?;+ assert_eq!(size1, size2);++ Ok(())+ }++ #[test]+ fn test_last_list_acc_size() -> Result<()> {+ fn size_after_batch(values: &[ArrayRef]) -> Result<usize> {+ let mut last_accumulator = LastValueAccumulator::try_new(+ &DataType::List(Arc::new(Field::new_list_field(DataType::Int64, false))),+ &[],+ LexOrdering::default(),+ false,+ )?;++ last_accumulator.update_batch(values)?;++ Ok(last_accumulator.size())+ }++ let batch1 = ListArray::from_iter_primitive::<Int32Type, _, _>(+ repeat_with(|| Some(vec![Some(1)])).take(10000),+ );+ let batch2 =+ ListArray::from_iter_primitive::<Int32Type, _, _>([Some(vec![Some(1)])]);++ let size1 = size_after_batch(&[Arc::new(batch1)])?;+ let size2 = size_after_batch(&[Arc::new(batch2)])?;+ assert_eq!(size1, size2);++ Ok(())+ }}diff --git a/datafusion/functions-aggregate/src/min_max.rs b/datafusion/functions-aggregate/src/min_max.rsindex 4bd842dc03..2d51926a7b 100644--- a/datafusion/functions-aggregate/src/min_max.rs+++ b/datafusion/functions-aggregate/src/min_max.rs@@ -646,19 +646,29 @@ fn min_max_batch_generic(array: &ArrayRef, ordering: Ordering) -> Result<ScalarV}}}- // use force_clone to free array reference- Ok(extreme.force_clone())++ Ok(extreme)}macro_rules! min_max_generic {($VALUE:expr, $DELTA:expr, $OP:ident) => {{if $VALUE.is_null() {- $DELTA.clone()+ let mut delta_copy = $DELTA.clone();+ // When the new value won we want to compact it to+ // avoid storing the entire input+ delta_copy.compact();+ delta_copy} else if $DELTA.is_null() {$VALUE.clone()} else {match $VALUE.partial_cmp(&$DELTA) {- Some(choose_min_max!($OP)) => $DELTA.clone(),+ Some(choose_min_max!($OP)) => {+ // When the new value won we want to compact it to+ // avoid storing the entire input+ let mut delta_copy = $DELTA.clone();+ delta_copy.compact();+ delta_copy+ }_ => $VALUE.clone(),}}