ariel-miculas commented on code in PR #22712: URL: https://github.com/apache/datafusion/pull/22712#discussion_r3344330120
########## datafusion/physical-plan/src/aggregates/group_values/single_group_by/blocked_primitive.rs: ########## @@ -0,0 +1,318 @@ +// 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 crate::aggregates::group_values::single_group_by::primitive::HashValue; + +use arrow::array::{ + ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, NullBufferBuilder, PrimitiveArray, + cast::AsArray, +}; +use arrow::datatypes::DataType; +use datafusion_common::Result; +use datafusion_common::hash_utils::RandomState; +use datafusion_execution::memory_pool::proxy::VecAllocExt; +use datafusion_expr::EmitTo; +use hashbrown::hash_table::HashTable; +use std::mem::size_of; +use std::sync::Arc; + +/// A single-column primitive [`GroupValues`] that stores group keys in fixed +/// sized blocks. Group ids are still logically contiguous: +/// +/// ```text +/// group_id = block_index * block_size + offset_in_block +/// ``` +/// +/// `EmitTo::Block` consumes exactly one stored block, so callers that configure +/// accumulators with the same block size can build output batches without first +/// materializing one large contiguous values vector. +pub struct GroupValuesPrimitiveBlock<T: ArrowPrimitiveType> { + data_type: DataType, + map: HashTable<(usize, u64)>, + null_group: Option<usize>, + blocks: Vec<Box<[T::Native]>>, + len: usize, + block_size: usize, + random_state: RandomState, +} + +impl<T: ArrowPrimitiveType> GroupValuesPrimitiveBlock<T> { + pub fn new(data_type: DataType, block_size: usize) -> Self { + assert!(block_size > 0); + assert!(PrimitiveArray::<T>::is_compatible(&data_type)); + Self { + data_type, + map: HashTable::with_capacity(128), + blocks: Vec::with_capacity(1), + null_group: None, + len: 0, + block_size, + random_state: crate::aggregates::AGGREGATION_HASH_SEED, + } + } + + fn push_value(&mut self, value: T::Native) -> usize + where + T::Native: Default + Copy, + { + let group_id = self.len; + if group_id.is_multiple_of(self.block_size) { + self.blocks + .push(vec![T::Native::default(); self.block_size].into_boxed_slice()); + } + + let block_idx = group_id / self.block_size; + let value_idx = group_id % self.block_size; + self.blocks[block_idx][value_idx] = value; + self.len += 1; + group_id + } + + fn release_map(&mut self) { + self.map.clear(); + self.map.shrink_to(0, |_| 0); + } + + fn nulls_for( + null_idx: Option<usize>, + len: usize, + ) -> Option<arrow::buffer::NullBuffer> { + null_idx.map(|null_idx| { + let mut buffer = NullBufferBuilder::new(len); + buffer.append_n_non_nulls(null_idx); + buffer.append_null(); + buffer.append_n_non_nulls(len - null_idx - 1); + buffer.finish().unwrap() + }) + } + + fn build_array( + data_type: &DataType, + values: Vec<T::Native>, + null_idx: Option<usize>, + ) -> ArrayRef { + let nulls = Self::nulls_for(null_idx, values.len()); + Arc::new( + PrimitiveArray::<T>::new(values.into(), nulls) + .with_data_type(data_type.clone()), + ) + } + + fn take_null_for_emit(&mut self, emit_len: usize) -> Option<usize> { + match self.null_group { + Some(null_group) if null_group < emit_len => { + self.null_group = None; + Some(null_group) + } + Some(null_group) => { + self.null_group = Some(null_group - emit_len); + None + } + None => None, + } + } + + fn values_range(&self, start: usize, len: usize) -> Vec<T::Native> + where + T::Native: Copy, + { + let mut output = Vec::with_capacity(len); + let mut remaining = len; + let mut group_id = start; + + while remaining > 0 { + let block_idx = group_id / self.block_size; + let offset = group_id % self.block_size; + let take = remaining.min(self.block_size - offset); + output.extend_from_slice(&self.blocks[block_idx][offset..offset + take]); + remaining -= take; + group_id += take; + } + + output + } + + fn rebuild_from_values(&mut self, values: &[T::Native]) + where + T::Native: Default + Copy, + { + self.blocks.clear(); + self.len = 0; + + for chunk in values.chunks(self.block_size) { + let mut block = + vec![T::Native::default(); self.block_size].into_boxed_slice(); + block[..chunk.len()].copy_from_slice(chunk); + self.blocks.push(block); + self.len += chunk.len(); + } + } + + fn take_all_values(&mut self) -> Vec<T::Native> + where + T::Native: Copy, + { + let output = self.values_range(0, self.len); + self.blocks.clear(); + self.len = 0; + output + } + + fn take_block_values(&mut self) -> (Vec<T::Native>, Option<usize>) { + self.release_map(); + + let emit_len = self.len.min(self.block_size); + let block = self.blocks.remove(0); + let mut values = block.into_vec(); + values.truncate(emit_len); Review Comment: truncating leads to a memory accounting inaccuracy, should `shrink_to_fit` be considered here? It leads to a reallocation, so I'm not sure if it's the right thing; however, it's worth mentioning the overaccounting in the last block's case, when len is smaller than Vec's capacity (and RecordBatch::get_array_memory_size reports the capacity, not the length) -- 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]
