diff --git a/datafusion-examples/examples/udf/advanced_udaf.rs b/datafusion-examples/examples/udf/advanced_udaf.rs index b990740159906..9a1c6e6552f30 100644 --- a/datafusion-examples/examples/udf/advanced_udaf.rs +++ b/datafusion-examples/examples/udf/advanced_udaf.rs @@ -18,7 +18,7 @@ //! See `main.rs` for how to run it. use arrow::datatypes::{Field, Schema}; -use datafusion::physical_expr::NullState; +use datafusion::physical_expr::FlatNullState; use datafusion::{arrow::datatypes::DataType, logical_expr::Volatility}; use std::sync::Arc; @@ -215,7 +215,7 @@ struct GeometricMeanGroupsAccumulator { prods: Vec, /// Track nulls in the input / filters - null_state: NullState, + null_state: FlatNullState, } impl GeometricMeanGroupsAccumulator { @@ -225,7 +225,7 @@ impl GeometricMeanGroupsAccumulator { return_data_type: DataType::Float64, counts: vec![], prods: vec![], - null_state: NullState::new(), + null_state: FlatNullState::new(), } } } @@ -246,13 +246,17 @@ impl GroupsAccumulator for GeometricMeanGroupsAccumulator { // increment counts, update sums self.counts.resize(total_num_groups, 0); self.prods.resize(total_num_groups, 1.0); - // Use the `NullState` structure to generate specialized code for null / non null input elements + // Use the `NullState` structure to generate specialized code for null / non null input elements. + // `block_id` is ignored in `value_fn`, because `AvgGroupsAccumulator` + // still not support blocked groups. + // More details can see `GroupsAccumulator::supports_blocked_groups`. self.null_state.accumulate( group_indices, values, opt_filter, total_num_groups, - |group_index, new_value| { + |_, group_index, new_value| { + let group_index = group_index as usize; let prod = &mut self.prods[group_index]; *prod = prod.mul_wrapping(new_value); @@ -276,13 +280,16 @@ impl GroupsAccumulator for GeometricMeanGroupsAccumulator { let partial_counts = values[1].as_primitive::(); // update counts with partial counts self.counts.resize(total_num_groups, 0); + // `block_id` is ignored in `value_fn`, because `AvgGroupsAccumulator` + // still not support blocked groups. + // More details can see `GroupsAccumulator::supports_blocked_groups`. self.null_state.accumulate( group_indices, partial_counts, None, total_num_groups, - |group_index, partial_count| { - self.counts[group_index] += partial_count; + |_, group_index, partial_count| { + self.counts[group_index as usize] += partial_count; }, ); @@ -293,8 +300,8 @@ impl GroupsAccumulator for GeometricMeanGroupsAccumulator { partial_prods, None, total_num_groups, - |group_index, new_value: ::Native| { - let prod = &mut self.prods[group_index]; + |_, group_index, new_value: ::Native| { + let prod = &mut self.prods[group_index as usize]; *prod = prod.mul_wrapping(new_value); }, ); diff --git a/datafusion-testing b/datafusion-testing index 13bbae38776c2..eccb0e4a42634 160000 --- a/datafusion-testing +++ b/datafusion-testing @@ -1 +1 @@ -Subproject commit 13bbae38776c2bfbc1fab1be7e7220222d4284bf +Subproject commit eccb0e4a426344ef3faf534cd60e02e9c3afd3ac diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index 536afbfed4613..fe1dfa3c3aa3d 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -852,6 +852,16 @@ config_namespace! { /// the remote end point. pub objectstore_writer_buffer_size: usize, default = 10 * 1024 * 1024 + /// Should DataFusion use a blocked approach to manage grouping state. + /// When enabled, the blocked approach + /// allocates capacity based on a predefined block size firstly. + /// When the block reaches its limit, we allocate a new block (also with + /// the same predefined block size based capacity) instead of expanding + /// the current one and copying the data. + /// If `false`, a single allocation approach is used, where + /// values are managed within a single large memory block. + /// As this block grows, it often triggers numerous copies, resulting in poor performance. + pub enable_aggregation_blocked_groups: bool, default = false /// Whether to enable ANSI SQL mode. /// /// The flag is experimental and relevant only for DataFusion Spark built-in functions diff --git a/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs b/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs index 4726e7c4aca5c..f895c2bda0641 100644 --- a/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs +++ b/datafusion/core/tests/fuzz_cases/aggregate_fuzz.rs @@ -18,10 +18,12 @@ use std::sync::Arc; use super::record_batch_generator::get_supported_types_columns; -use crate::fuzz_cases::aggregation_fuzzer::query_builder::QueryBuilder; use crate::fuzz_cases::aggregation_fuzzer::{ AggregationFuzzerBuilder, DatasetGeneratorConfig, }; +use crate::fuzz_cases::aggregation_fuzzer::{ + SessionContextOptions, query_builder::QueryBuilder, +}; use arrow::array::{ Array, ArrayRef, AsArray, Int32Array, Int64Array, RecordBatch, StringArray, @@ -230,6 +232,60 @@ async fn test_median() { .await; } +// Testing `blocked groups optimization` +// Details of this optimization can see: +// https://github.com/apache/datafusion/issues/7065 +// +// To ensure the blocked groups path is actually exercised, we must satisfy +// *all* conditions checked by `can_enable_blocked_groups`: +// +// 1. `GroupOrdering::None` — disable sort hints (`sort_hint: Some(false)`) +// so the aggregation is not streaming. +// 2. `OutOfMemoryMode::ReportError` — no memory limit / spilling (default). +// 3. `group_values.supports_blocked_groups() == true` +// — only `GroupValuesPrimitive` returns true, so we restrict to +// *single* numeric group-by column (`with_max_group_by_columns(1)` +// + `set_group_by_columns(numeric_columns())`). +// 4. Every accumulator `supports_blocked_groups() == true` +// — currently only sum/min/max support this, so we limit aggregates +// to those functions with numeric arguments. +// 5. Config knob enabled — force it via `enable_blocked_groups: Some(true)`. +// +// With all five conditions met, `enable_blocked_groups` is guaranteed true +// and `alter_block_size` will be called on both group values and accumulators. +#[tokio::test(flavor = "multi_thread")] +async fn test_blocked_groups_optimization() { + let data_gen_config = baseline_config(); + + // Test `Numeric aggregation` + `Single group by` + let aggr_functions = ["sum", "min", "max"]; + let aggr_arguments = data_gen_config.numeric_columns(); + let groups_by_columns = data_gen_config.numeric_columns(); + + let mut query_builder = QueryBuilder::new() + .with_table_name("fuzz_table") + .with_aggregate_arguments(aggr_arguments) + .set_group_by_columns(groups_by_columns) + .with_min_group_by_columns(1) + .with_max_group_by_columns(1) + .with_no_grouping(false); + + for func in aggr_functions { + query_builder = query_builder.with_aggregate_function(func); + } + + AggregationFuzzerBuilder::from(data_gen_config) + .add_query_builder(query_builder) + .session_context_options(SessionContextOptions { + enable_blocked_groups: Some(true), + sort_hint: Some(false), + ..Default::default() + }) + .build() + .run() + .await; +} + /// Return a standard set of columns for testing data generation /// /// Includes numeric and string types diff --git a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/context_generator.rs b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/context_generator.rs index 3579c6af844bb..6627413b7861d 100644 --- a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/context_generator.rs +++ b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/context_generator.rs @@ -63,10 +63,33 @@ pub struct SessionContextGenerator { /// The upper bound of the randomly generated target partitions, /// and the lower bound will be 1 max_target_partitions: usize, + + /// Force-enable or force-disable specific options, overriding random generation + options: SessionContextOptions, +} + +/// Options to force-enable or force-disable specific session config knobs. +/// +/// - `None` → randomized by the fuzzer (default behavior) +/// - `Some(true)` → always enabled +/// - `Some(false)` → always disabled +#[derive(Debug, Clone, Default)] +pub struct SessionContextOptions { + pub skip_partial: Option, + pub sort_hint: Option, + pub enable_blocked_groups: Option, } impl SessionContextGenerator { pub fn new(dataset_ref: Arc, table_name: &str) -> Self { + Self::new_with_options(dataset_ref, table_name, SessionContextOptions::default()) + } + + pub fn new_with_options( + dataset_ref: Arc, + table_name: &str, + options: SessionContextOptions, + ) -> Self { let candidate_skip_partial_params = vec![ SkipPartialParams::ensure_trigger(), SkipPartialParams::ensure_not_trigger(), @@ -81,6 +104,7 @@ impl SessionContextGenerator { max_batch_size, candidate_skip_partial_params, max_target_partitions, + options, } } } @@ -105,6 +129,7 @@ impl SessionContextGenerator { skip_partial_params, enable_migration_aggregate, sort_hint: false, + enable_aggregation_blocked_groups: false, table_name: self.table_name.clone(), table_provider: Arc::new(provider), }; @@ -130,15 +155,23 @@ impl SessionContextGenerator { let target_partitions = rng.random_range(1..=self.max_target_partitions); - let skip_partial_params_idx = - rng.random_range(0..self.candidate_skip_partial_params.len()); - let skip_partial_params = - self.candidate_skip_partial_params[skip_partial_params_idx]; + let skip_partial_params = match self.options.skip_partial { + Some(true) => SkipPartialParams::ensure_trigger(), + Some(false) => SkipPartialParams::ensure_not_trigger(), + None => { + let idx = rng.random_range(0..self.candidate_skip_partial_params.len()); + self.candidate_skip_partial_params[idx] + } + }; + let sort_hint_enabled = self + .options + .sort_hint + .unwrap_or_else(|| rng.random_bool(0.5)); let enable_migration_aggregate = rng.random_bool(0.5); let (provider, sort_hint) = - if rng.random_bool(0.5) && !self.dataset.sort_keys.is_empty() { + if sort_hint_enabled && !self.dataset.sort_keys.is_empty() { // Sort keys exist and random to push down let sort_exprs = self .dataset @@ -151,11 +184,17 @@ impl SessionContextGenerator { (provider, false) }; + let enable_aggregation_blocked_groups = self + .options + .enable_blocked_groups + .unwrap_or_else(|| rng.random_bool(0.5)); + let builder = GeneratedSessionContextBuilder { batch_size, target_partitions, sort_hint, skip_partial_params, + enable_aggregation_blocked_groups, enable_migration_aggregate, table_name: self.table_name.clone(), table_provider: Arc::new(provider), @@ -180,6 +219,7 @@ struct GeneratedSessionContextBuilder { target_partitions: usize, sort_hint: bool, skip_partial_params: SkipPartialParams, + enable_aggregation_blocked_groups: bool, enable_migration_aggregate: bool, table_name: String, table_provider: Arc, @@ -205,6 +245,10 @@ impl GeneratedSessionContextBuilder { "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", &ScalarValue::Float64(Some(self.skip_partial_params.ratio_threshold)), ); + session_config = session_config.set( + "datafusion.execution.enable_aggregation_blocked_groups", + &ScalarValue::Boolean(Some(self.enable_aggregation_blocked_groups)), + ); session_config = session_config.set_bool( "datafusion.execution.enable_migration_aggregate", self.enable_migration_aggregate, @@ -218,6 +262,7 @@ impl GeneratedSessionContextBuilder { target_partitions: self.target_partitions, sort_hint: self.sort_hint, skip_partial_params: self.skip_partial_params, + enable_aggregation_blocked_groups: self.enable_aggregation_blocked_groups, enable_migration_aggregate: self.enable_migration_aggregate, }; @@ -233,6 +278,7 @@ pub struct SessionContextParams { target_partitions: usize, sort_hint: bool, skip_partial_params: SkipPartialParams, + enable_aggregation_blocked_groups: bool, enable_migration_aggregate: bool, } diff --git a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/fuzzer.rs b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/fuzzer.rs index 430762b1c28db..e473355e40bd4 100644 --- a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/fuzzer.rs +++ b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/fuzzer.rs @@ -26,7 +26,9 @@ use rand::{Rng, rng}; use crate::fuzz_cases::aggregation_fuzzer::query_builder::QueryBuilder; use crate::fuzz_cases::aggregation_fuzzer::{ check_equality_of_batches, - context_generator::{SessionContextGenerator, SessionContextWithParams}, + context_generator::{ + SessionContextGenerator, SessionContextOptions, SessionContextWithParams, + }, data_generator::{Dataset, DatasetGenerator, DatasetGeneratorConfig}, run_sql, }; @@ -50,6 +52,9 @@ pub struct AggregationFuzzerBuilder { /// See `data_gen_rounds` in [`AggregationFuzzer`], default 16 data_gen_rounds: usize, + + /// Session context options to force-enable or force-disable specific knobs + session_context_options: SessionContextOptions, } impl AggregationFuzzerBuilder { @@ -59,6 +64,7 @@ impl AggregationFuzzerBuilder { table_name: None, data_gen_config: None, data_gen_rounds: 16, + session_context_options: SessionContextOptions::default(), } } @@ -90,6 +96,11 @@ impl AggregationFuzzerBuilder { self } + pub fn session_context_options(mut self, options: SessionContextOptions) -> Self { + self.session_context_options = options; + self + } + pub fn build(self) -> AggregationFuzzer { assert!(!self.candidate_sqls.is_empty()); let candidate_sqls = self.candidate_sqls; @@ -104,6 +115,7 @@ impl AggregationFuzzerBuilder { table_name, dataset_generator, data_gen_rounds, + session_context_options: self.session_context_options, } } } @@ -139,6 +151,9 @@ pub struct AggregationFuzzer { /// It is suggested to set value 2x or more bigger than num of /// `candidate_sqls` for better test coverage. data_gen_rounds: usize, + + /// Session context options to force-enable or force-disable specific knobs + session_context_options: SessionContextOptions, } /// Query group including the tested dataset and its sql query @@ -210,8 +225,11 @@ impl AggregationFuzzer { let mut tasks = Vec::with_capacity(query_groups.len() * CTX_GEN_ROUNDS); for QueryGroup { dataset, sql } in query_groups { let dataset_ref = Arc::new(dataset); - let ctx_generator = - SessionContextGenerator::new(dataset_ref.clone(), &self.table_name); + let ctx_generator = SessionContextGenerator::new_with_options( + dataset_ref.clone(), + &self.table_name, + self.session_context_options.clone(), + ); // Generate the baseline context, and get the baseline result firstly let baseline_ctx_with_params = ctx_generator diff --git a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/mod.rs b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/mod.rs index e7ce557d2267d..757f836ae87aa 100644 --- a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/mod.rs +++ b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/mod.rs @@ -46,6 +46,7 @@ mod fuzzer; pub mod query_builder; pub use crate::fuzz_cases::record_batch_generator::ColumnDescr; +pub use context_generator::SessionContextOptions; pub use data_generator::DatasetGeneratorConfig; pub use fuzzer::*; diff --git a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs index 7bb6177c31010..a9e143754143b 100644 --- a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs +++ b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/query_builder.rs @@ -182,13 +182,11 @@ impl QueryBuilder { /// Add max columns num in group by(default: 3), for example if it is set to 1, /// the generated sql will group by at most 1 column - #[expect(dead_code)] pub fn with_max_group_by_columns(mut self, max_group_by_columns: usize) -> Self { self.max_group_by_columns = max_group_by_columns; self } - #[expect(dead_code)] pub fn with_min_group_by_columns(mut self, min_group_by_columns: usize) -> Self { self.min_group_by_columns = min_group_by_columns; self @@ -202,7 +200,6 @@ impl QueryBuilder { } /// Add if also test the no grouping aggregation case(default: true) - #[expect(dead_code)] pub fn with_no_grouping(mut self, no_grouping: bool) -> Self { self.no_grouping = no_grouping; self @@ -245,7 +242,6 @@ impl QueryBuilder { fn generate_query(&self) -> String { let group_by = self.random_group_by(); - dbg!(&group_by); let mut query = String::from("SELECT "); query.push_str(&group_by.join(", ")); if !group_by.is_empty() { diff --git a/datafusion/expr-common/src/groups_accumulator.rs b/datafusion/expr-common/src/groups_accumulator.rs index b021674cbec2c..7d909cb3a7a93 100644 --- a/datafusion/expr-common/src/groups_accumulator.rs +++ b/datafusion/expr-common/src/groups_accumulator.rs @@ -18,12 +18,14 @@ //! Vectorized [`GroupsAccumulator`] use arrow::array::{ArrayRef, BooleanArray}; -use datafusion_common::{Result, not_impl_err, utils::split_vec_min_alloc}; +use datafusion_common::{ + DataFusionError, Result, not_impl_err, utils::split_vec_min_alloc, +}; /// Describes how many rows should be emitted during grouping. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EmitTo { - /// Emit all groups + /// Emit all groups, will clear all existing group indexes All, /// Emit only the first `n` groups and shift all existing group /// indexes down by `n`. @@ -31,6 +33,10 @@ pub enum EmitTo { /// For example, if `n=10`, group_index `0, 1, ... 9` are emitted /// and group indexes `10, 11, 12, ...` become `0, 1, 2, ...`. First(usize), + /// Emit next block in the blocked managed groups + /// + /// Similar as `Emit::All`, will also clear all existing group indexes + NextBlock, } impl EmitTo { @@ -39,6 +45,9 @@ impl EmitTo { /// remaining values in `v`. /// /// This avoids copying if Self::All + /// + /// NOTICE: only support emit strategies: `Self::All` and `Self::First` + /// pub fn take_needed(&self, v: &mut Vec) -> Vec { match self { Self::All => { @@ -46,6 +55,7 @@ impl EmitTo { std::mem::take(v) } Self::First(n) => split_vec_min_alloc(v, *n), + Self::NextBlock => unreachable!("don't support take block in take_needed"), } } } @@ -249,6 +259,51 @@ pub trait GroupsAccumulator: Send + std::any::Any { /// This function is called once per batch, so it should be `O(n)` to /// compute, not `O(num_groups)` fn size(&self) -> usize; + + /// Returns `true` if this accumulator supports blocked groups. + /// + /// Blocked groups(or called blocked management approach) is an optimization + /// to reduce the cost of managing aggregation intermediate states. + /// + /// Here is brief introduction for two states management approaches: + /// - Blocked approach, states are stored and managed in multiple `Vec`s, + /// we call it `Block`s. Organize like this is for avoiding to resize `Vec` + /// and allocate a new `Vec` instead to reduce cost and get better performance. + /// When locating data in `Block`s, we need to use `block_id` to locate the + /// needed `Block` at first, and use `block_offset` to locate the needed + /// data in `Block` after. + /// + /// - Single approach, all states are stored and managed in a single large `Block`. + /// So when locating data, `block_id` will always be 0, and we only need `block_offset` + /// to locate data in the single `Block`. + /// + /// More details can see: + /// + /// + fn supports_blocked_groups(&self) -> bool { + false + } + + /// Alter the block size in the accumulator + /// + /// If the target block size is `None`, it will use a single big + /// block(can think it a `Vec`) to manage the state. + /// + /// If the target block size` is `Some(blk_size)`, it will try to + /// set the block size to `blk_size`, and the try will only success + /// when the accumulator has supported blocked mode. + /// + /// NOTICE: After altering block size, all data in previous will be cleared. + /// + fn alter_block_size(&mut self, block_size: Option) -> Result<()> { + if block_size.is_some() { + return Err(DataFusionError::NotImplemented( + "this accumulator doesn't support blocked mode yet".to_string(), + )); + } + + Ok(()) + } } #[cfg(test)] diff --git a/datafusion/ffi/src/udaf/groups_accumulator.rs b/datafusion/ffi/src/udaf/groups_accumulator.rs index 272afdb6abfb1..98530adf197a5 100644 --- a/datafusion/ffi/src/udaf/groups_accumulator.rs +++ b/datafusion/ffi/src/udaf/groups_accumulator.rs @@ -432,6 +432,7 @@ impl GroupsAccumulator for ForeignGroupsAccumulator { pub enum FFI_EmitTo { All, First(usize), + NextBlock, } impl From for FFI_EmitTo { @@ -439,6 +440,7 @@ impl From for FFI_EmitTo { match value { EmitTo::All => Self::All, EmitTo::First(v) => Self::First(v), + EmitTo::NextBlock => Self::NextBlock, } } } @@ -448,6 +450,7 @@ impl From for EmitTo { match value { FFI_EmitTo::All => Self::All, FFI_EmitTo::First(v) => Self::First(v), + FFI_EmitTo::NextBlock => Self::NextBlock, } } } diff --git a/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs b/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs index 60fe0388c430f..7fae562364e7d 100644 --- a/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs +++ b/datafusion/functions-aggregate-common/src/aggregate/count_distinct/groups.rs @@ -20,8 +20,8 @@ use arrow::array::{ }; use arrow::buffer::{OffsetBuffer, ScalarBuffer}; use arrow::datatypes::{ArrowPrimitiveType, Field}; -use datafusion_common::HashSet; use datafusion_common::hash_utils::RandomState; +use datafusion_common::{HashSet, internal_err}; use datafusion_expr_common::groups_accumulator::{EmitTo, GroupsAccumulator}; use std::hash::Hash; use std::mem::size_of; @@ -97,6 +97,11 @@ where } self.seen = remaining; } + EmitTo::NextBlock => { + return internal_err!( + "count distinct primitive does not support blocked groups" + ); + } } Ok(Arc::new(Int64Array::from(counts))) @@ -106,6 +111,11 @@ where let num_emitted = match emit_to { EmitTo::All => self.counts.len(), EmitTo::First(n) => n, + EmitTo::NextBlock => { + return internal_err!( + "count distinct primitive does not support blocked groups" + ); + } }; // Prefix-sum counts[..num_emitted] into offsets diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs index b412b4ffe09f2..72fefcaba2f4a 100644 --- a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator.rs @@ -19,7 +19,9 @@ //! Adapter that makes [`GroupsAccumulator`] out of [`Accumulator`] pub mod accumulate; +pub mod block_store; pub mod bool_op; +pub mod group_index_operations; pub mod nulls; pub mod prim_op; diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/accumulate.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/accumulate.rs index 09e1df4eae70c..11428bd3d004d 100644 --- a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/accumulate.rs +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/accumulate.rs @@ -19,13 +19,73 @@ //! //! [`GroupsAccumulator`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator -use arrow::array::{Array, BooleanArray, BooleanBufferBuilder, PrimitiveArray}; +use std::fmt::Debug; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut, Index, IndexMut}; + use arrow::buffer::NullBuffer; use arrow::datatypes::ArrowPrimitiveType; +use arrow::{ + array::{Array, BooleanArray, BooleanBufferBuilder, PrimitiveArray}, + buffer::BooleanBuffer, +}; use crate::aggregate::groups_accumulator::nulls::filter_to_validity; use datafusion_expr_common::groups_accumulator::EmitTo; +use crate::aggregate::groups_accumulator::block_store::{ + Block, BlockStore, BlockedBlockStore, FlatBlockStore, +}; +use crate::aggregate::groups_accumulator::group_index_operations::{ + BlockedGroupIndexOperations, FlatGroupIndexOperations, GroupIndexOperations, +}; + +/// Newtype wrapper around [`BooleanBufferBuilder`] that implements [`Default`] +/// (and thus [`Block`]) so it can be used in [`Blocks`]. +#[derive(Debug)] +pub struct BooleanBlock(BooleanBufferBuilder); + +impl BooleanBlock { + pub fn new(capacity: usize) -> Self { + Self(BooleanBufferBuilder::new(capacity)) + } +} + +impl Default for BooleanBlock { + fn default() -> Self { + Self(BooleanBufferBuilder::new(0)) + } +} + +impl Deref for BooleanBlock { + type Target = BooleanBufferBuilder; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for BooleanBlock { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl Block for BooleanBlock { + type T = bool; + + fn new(capacity: usize) -> Self { + Self(BooleanBufferBuilder::new(capacity)) + } + + fn fill_default_value(&mut self, fill_len: usize, default_value: Self::T) { + self.0.append_n(fill_len, default_value); + } + + fn len(&self) -> usize { + self.0.len() + } +} /// If the input has nulls, then the accumulator must potentially /// handle each input null value specially (e.g. for `SUM` to mark the /// corresponding sum as null) @@ -36,52 +96,183 @@ use datafusion_expr_common::groups_accumulator::EmitTo; /// had at least one value to accumulate so they do not need to track /// if they have seen values for a particular group. #[derive(Debug)] -pub enum SeenValues { - /// All groups seen so far have seen at least one non-null value +pub enum SeenValues +where + S: BlockStore, +{ + /// All groups seen so far have seen at least one non-null value. + /// + /// `pending_builder` carries the empty seen-values store supplied at + /// [`NullState`] construction time. It is wrapped in an [`Option`] so + /// that it can be taken out via [`Option::take`] when transitioning to + /// [`SeenValues::Some`]. While the variant is `All`, it is always + /// `Some(_)`; `None` is only observed transiently during that + /// transition. All { num_values: usize, + pending_builder: Option>, }, - // Some groups have not yet seen a non-null value - Some { - values: BooleanBufferBuilder, - }, + /// Some groups have not yet seen a non-null value. + Some { builder: SeenValueStore }, } -impl Default for SeenValues { - fn default() -> Self { - SeenValues::All { num_values: 0 } +/// Wrapper around a [`BlockStore`] that tracks per-group +/// "have we seen a non-null value yet" bits and produces [`NullBuffer`]s on +/// emit. +/// +/// `emit` is implemented purely via [`BlockStore::push_block`] and +/// [`BlockStore::pop_block`] so it works uniformly over flat and blocked +/// storage; per-store specialization is no longer needed. +#[derive(Debug)] +pub struct SeenValueStore +where + S: BlockStore, +{ + inner: S, +} + +impl SeenValueStore +where + S: BlockStore, +{ + pub fn new(inner: S) -> Self { + Self { inner } + } + + pub fn set_bit(&mut self, block_id: u32, block_offset: u64, value: bool) { + self.inner[block_id as usize].set_bit(block_offset as usize, value); + } + + pub fn size(&self) -> usize { + if self.inner.num_blocks() == 0 { + return 0; + } + self.inner[0].capacity() / 8 * self.inner.num_blocks() + } + + pub fn resize(&mut self, total_num_groups: usize, default_value: bool) { + self.inner.resize(total_num_groups, default_value); + } + + pub fn num_blocks(&self) -> usize { + self.inner.num_blocks() + } + + pub fn block_size(&self) -> Option { + self.inner.block_size() + } + + /// Emit seen-values according to `emit_to`, expressed only in terms of + /// [`BlockStore::push_block`] / [`BlockStore::pop_block`]. + /// + /// - [`EmitTo::All`] / [`EmitTo::NextBlock`]: pop one block and finish it. + /// - [`EmitTo::First`]`(n)`: pop the (only) block, finish it, take the first + /// `n` bits, rebuild a block from the remainder and push it back. Only + /// meaningful when the first block holds at least `n` bits (true for flat + /// storage). + pub fn emit(&mut self, emit_to: EmitTo) -> NullBuffer { + match emit_to { + EmitTo::All | EmitTo::NextBlock => { + let mut block = self + .inner + .pop_block() + .expect("should not try to emit empty seen-values block"); + NullBuffer::new(block.finish()) + } + EmitTo::First(n) => { + let mut block = self + .inner + .pop_block() + .expect("should not try to emit empty seen-values block"); + let buffer = block.finish(); + let first_n: BooleanBuffer = buffer.iter().take(n).collect(); + let mut rest = BooleanBlock::new(0); + for seen in buffer.iter().skip(n) { + rest.append(seen); + } + self.inner.push_block(rest); + NullBuffer::new(first_n) + } + } + } +} + +impl Index for SeenValueStore +where + S: BlockStore, +{ + type Output = BooleanBlock; + + #[inline] + fn index(&self, index: usize) -> &Self::Output { + &self.inner[index] + } +} + +impl IndexMut for SeenValueStore +where + S: BlockStore, +{ + #[inline] + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.inner[index] } } -impl SeenValues { +impl SeenValues +where + S: BlockStore, +{ + fn block_size(&self) -> Option { + match self { + SeenValues::All { + pending_builder, .. + } => pending_builder + .as_ref() + .expect("pending_builder must be Some while SeenValues is All") + .block_size(), + SeenValues::Some { builder } => builder.block_size(), + } + } + /// Return a mutable reference to the `BooleanBufferBuilder` in `SeenValues::Some`. /// /// If `self` is `SeenValues::All`, it is transitioned to `SeenValues::Some` - /// by creating a new `BooleanBufferBuilder` where the first `num_values` are true. + /// by taking out its embedded `pending_builder` and seeding the first + /// `num_values` entries to true. /// /// The builder is then ensured to have at least `total_num_groups` length, /// with any new entries initialized to false. - fn get_builder(&mut self, total_num_groups: usize) -> &mut BooleanBufferBuilder { - match self { - SeenValues::All { num_values } => { - let mut builder = BooleanBufferBuilder::new(total_num_groups); - builder.append_n(*num_values, true); - if total_num_groups > *num_values { - builder.append_n(total_num_groups - *num_values, false); - } - *self = SeenValues::Some { values: builder }; + fn get_big_enough_builder( + &mut self, + total_num_groups: usize, + ) -> &mut SeenValueStore { + // If `self` is `SeenValues::All`, transition it to `SeenValues::Some` with `num_values trues` firstly, + // then return mutable reference to the builder. + // If `self` is `SeenValues::Some`, just directly return mutable reference to the builder. + let builder = match self { + SeenValues::All { + num_values, + pending_builder, + } => { + // Switch to `SeenValues::Some` with `num_values` trues, taking the + // empty builder that was provided at NullState construction time. + let mut builder = pending_builder + .take() + .expect("pending_builder must be Some while SeenValues is All"); + builder.resize(*num_values, true); + *self = SeenValues::Some { builder }; match self { - SeenValues::Some { values } => values, + SeenValues::Some { builder } => builder, _ => unreachable!(), } } - SeenValues::Some { values } => { - if values.len() < total_num_groups { - values.append_n(total_num_groups - values.len(), false); - } - values - } - } + SeenValues::Some { builder } => builder, + }; + + // Ensure the builder has `total_num_groups` length and return it + builder.resize(total_num_groups, false); + builder } } @@ -111,7 +302,11 @@ impl SeenValues { /// /// [`GroupsAccumulator`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator #[derive(Debug)] -pub struct NullState { +pub struct NullState +where + O: GroupIndexOperations, + S: BlockStore, +{ /// Have we seen any non-filtered input values for `group_index`? /// /// If `seen_values` is `SeenValues::Some(buffer)` and buffer\[i\] is true, have seen at least one non null @@ -121,27 +316,22 @@ pub struct NullState { /// pass the filter yet for group `i` /// /// If `seen_values` is `SeenValues::All`, all groups have seen at least one non null value - seen_values: SeenValues, -} + seen_values: SeenValues, -impl Default for NullState { - fn default() -> Self { - Self::new() - } + /// phantom data for required type `` + _phantom: PhantomData, } -impl NullState { - pub fn new() -> Self { - Self { - seen_values: SeenValues::All { num_values: 0 }, - } - } - +impl NullState +where + O: GroupIndexOperations, + S: BlockStore + Send, +{ /// return the size of all buffers allocated by this null state, not including self pub fn size(&self) -> usize { match &self.seen_values { SeenValues::All { .. } => 0, - SeenValues::Some { values } => values.capacity() / 8, + SeenValues::Some { builder: values } => values.size(), } } @@ -170,22 +360,32 @@ impl NullState { mut value_fn: F, ) where T: ArrowPrimitiveType + Send, - F: FnMut(usize, T::Native) + Send, + F: FnMut(u32, u64, T::Native) + Send, { // skip null handling if no nulls in input or accumulator - if let SeenValues::All { num_values } = &mut self.seen_values + if let SeenValues::All { num_values, .. } = &mut self.seen_values && opt_filter.is_none() && values.null_count() == 0 { - accumulate(group_indices, values, None, value_fn); + accumulate(group_indices, values, None, |packed_index, value| { + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + value_fn(block_id, block_offset, value); + }); *num_values = total_num_groups; return; } - let seen_values = self.seen_values.get_builder(total_num_groups); - accumulate(group_indices, values, opt_filter, |group_index, value| { - seen_values.set_bit(group_index, true); - value_fn(group_index, value); + // Get big enough `seen_values_builder`(start everything at "not seen" valid) + let seen_values_builder = + self.seen_values.get_big_enough_builder(total_num_groups); + accumulate(group_indices, values, opt_filter, |packed_index, value| { + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + value_fn(block_id, block_offset, value); + seen_values_builder.set_bit(block_id, block_offset, true); }); } @@ -207,26 +407,32 @@ impl NullState { total_num_groups: usize, mut value_fn: F, ) where - F: FnMut(usize, bool) + Send, + F: FnMut(u32, u64, bool) + Send, { let data = values.values(); assert_eq!(data.len(), group_indices.len()); // skip null handling if no nulls in input or accumulator - if let SeenValues::All { num_values } = &mut self.seen_values + if let SeenValues::All { num_values, .. } = &mut self.seen_values && opt_filter.is_none() && values.null_count() == 0 { - group_indices - .iter() - .zip(data.iter()) - .for_each(|(&group_index, new_value)| value_fn(group_index, new_value)); + group_indices.iter().zip(data.iter()).for_each( + |(&packed_index, new_value)| { + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + value_fn(block_id, block_offset, new_value); + }, + ); *num_values = total_num_groups; return; } - let seen_values = self.seen_values.get_builder(total_num_groups); + // Get big enough `seen_values_builder`(start everything at "not seen" valid) + let seen_values_builder = + self.seen_values.get_big_enough_builder(total_num_groups); // These could be made more performant by iterating in chunks of 64 bits at a time match (values.null_count() > 0, opt_filter) { @@ -235,9 +441,12 @@ impl NullState { // if we have previously seen nulls, ensure the null // buffer is big enough (start everything at valid) group_indices.iter().zip(data.iter()).for_each( - |(&group_index, new_value)| { - seen_values.set_bit(group_index, true); - value_fn(group_index, new_value) + |(&packed_index, new_value)| { + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + seen_values_builder.set_bit(block_id, block_offset, true); + value_fn(block_id, block_offset, new_value); }, ) } @@ -248,10 +457,13 @@ impl NullState { .iter() .zip(data.iter()) .zip(nulls.iter()) - .for_each(|((&group_index, new_value), is_valid)| { + .for_each(|((&packed_index, new_value), is_valid)| { if is_valid { - seen_values.set_bit(group_index, true); - value_fn(group_index, new_value); + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + seen_values_builder.set_bit(block_id, block_offset, true); + value_fn(block_id, block_offset, new_value); } }) } @@ -263,10 +475,13 @@ impl NullState { .iter() .zip(data.iter()) .zip(filter.iter()) - .for_each(|((&group_index, new_value), filter_value)| { + .for_each(|((&packed_index, new_value), filter_value)| { if let Some(true) = filter_value { - seen_values.set_bit(group_index, true); - value_fn(group_index, new_value); + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + seen_values_builder.set_bit(block_id, block_offset, true); + value_fn(block_id, block_offset, new_value); } }) } @@ -277,55 +492,203 @@ impl NullState { .iter() .zip(group_indices.iter()) .zip(values.iter()) - .for_each(|((filter_value, &group_index), new_value)| { + .for_each(|((filter_value, &packed_index), new_value)| { if let Some(true) = filter_value && let Some(new_value) = new_value { - seen_values.set_bit(group_index, true); - value_fn(group_index, new_value) + let packed_index = packed_index as u64; + let block_id = O::get_block_id(packed_index); + let block_offset = O::get_block_offset(packed_index); + seen_values_builder.set_bit(block_id, block_offset, true); + value_fn(block_id, block_offset, new_value); } }) } } } - /// Creates the a [`NullBuffer`] representing which group_indices - /// should have null values (because they never saw any values) - /// for the `emit_to` rows. - /// - /// resets the internal state appropriately pub fn build(&mut self, emit_to: EmitTo) -> Option { - match emit_to { - EmitTo::All => { - let old_seen = std::mem::take(&mut self.seen_values); - match old_seen { - SeenValues::All { .. } => None, - SeenValues::Some { mut values } => { - Some(NullBuffer::new(values.finish())) - } + let block_size = self.seen_values.block_size(); + + // If `self` is `SeenValues::All`, just modify `num_values`. + // If `self` is `SeenValues::Some`, perform the emit logic of `builder`. + match &mut self.seen_values { + SeenValues::All { num_values, .. } => match emit_to { + EmitTo::All => { + assert!( + block_size.is_none(), + "emit_to::All should only be used with flat groups" + ); + None } - } - EmitTo::First(n) => match &mut self.seen_values { - SeenValues::All { num_values } => { + EmitTo::First(n) => { + assert!( + block_size.is_none(), + "emit_to::First should only be used with flat groups" + ); *num_values = num_values.saturating_sub(n); None } - SeenValues::Some { .. } => { - let mut old_values = match std::mem::take(&mut self.seen_values) { - SeenValues::Some { values } => values, - _ => unreachable!(), - }; - let nulls = old_values.finish(); - let first_n_null = nulls.slice(0, n); - let remainder = nulls.slice(n, nulls.len() - n); - let mut new_builder = BooleanBufferBuilder::new(remainder.len()); - new_builder.append_buffer(&remainder); - self.seen_values = SeenValues::Some { - values: new_builder, - }; - Some(NullBuffer::new(first_n_null)) + EmitTo::NextBlock => { + let block_size = block_size.expect( + "emit_to::NextBlock should only be used with blocked groups", + ); + *num_values = num_values.saturating_sub(block_size); + None + } + }, + SeenValues::Some { builder } => Some(builder.emit(emit_to)), + } + } + + #[cfg(test)] + fn num_blocks(&self) -> usize { + match &self.seen_values { + SeenValues::All { .. } => 0, + SeenValues::Some { builder } => builder.num_blocks(), + } + } +} + +#[cfg(test)] +impl NullState +where + O: GroupIndexOperations, + S: BlockStore + Send, +{ + /// Clone and build a single [`BooleanBuffer`] from `seen_values`, + /// only used for testing. + fn build_cloned_seen_values(&self) -> TestSeenValuesResult { + match &self.seen_values { + SeenValues::All { num_values, .. } => TestSeenValuesResult::All(*num_values), + SeenValues::Some { builder } => { + let mut return_builder = BooleanBufferBuilder::new(0); + let num_blocks = builder.num_blocks(); + for blk_idx in 0..num_blocks { + let bool_builder = &builder[blk_idx]; + for idx in 0..bool_builder.len() { + return_builder.append(bool_builder.get_bit(idx)); + } + } + let seen_values = return_builder.finish(); + TestSeenValuesResult::Some(seen_values) + } + } + } + + #[cfg(test)] + fn build_single_null_buffer(&mut self) -> Option { + if self.seen_values.block_size().is_none() { + return self.build(EmitTo::All); + } + + let mut return_builder = BooleanBufferBuilder::new(0); + let num_blocks = self.num_blocks(); + let mut has_some_nulls = false; + for _ in 0..num_blocks { + let blocked_nulls = self.build(EmitTo::NextBlock); + if let Some(nulls) = blocked_nulls { + has_some_nulls = true; + for bit in nulls.inner().iter() { + return_builder.append(bit); } + } + } + + if has_some_nulls { + Some(NullBuffer::new(return_builder.finish())) + } else { + None + } + } +} + +#[cfg(test)] +enum TestSeenValuesResult { + All(usize), + Some(BooleanBuffer), +} + +/// [`NullState`] for `flat groups input` +/// +/// At first, you may need to see something about `block_id` and `block_offset` +/// from [`GroupsAccumulator::supports_blocked_groups`]. +/// +/// The `flat groups input` are organized like: +/// +/// ```text +/// row_0 group_index_0 +/// row_1 group_index_1 +/// row_2 group_index_2 +/// ... +/// row_n group_index_n +/// ``` +/// +/// If `row_x group_index_x` is not filtered(`group_index_x` is seen) +/// `seen_values[group_index_x]` will be set to `true`. +/// +/// For `set_bit(block_id, block_offset, value)`, `block_id` is unused, +/// `block_offset` will be set to `group_index`. +/// +/// [`GroupsAccumulator::supports_blocked_groups`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator::supports_blocked_groups +/// +pub type FlatNullState = + NullState>; + +/// [`NullState`] for `blocked groups input` +/// +/// At first, you may need to see something about `block_id` and `block_offset` +/// from [`GroupsAccumulator::supports_blocked_groups`]. +/// +/// The `flat groups input` are organized like: +/// +/// ```text +/// row_0 (block_id_0, block_offset_0) +/// row_1 (block_id_1, block_offset_1) +/// row_2 (block_id_1, block_offset_1) +/// ... +/// row_n (block_id_n, block_offset_n) +/// ``` +/// +/// If `row_x (block_id_x, block_offset_x)` is not filtered +/// (`block_id_x, block_offset_x` is seen), `seen_values[block_id_x][block_offset_x]` +/// will be set to `true`. +/// +/// [`GroupsAccumulator::supports_blocked_groups`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator::supports_blocked_groups +/// +pub type BlockedNullState = + NullState>; + +impl NullState> { + /// Create a new [`FlatNullState`]. + pub fn new() -> Self { + Self { + seen_values: SeenValues::All { + num_values: 0, + pending_builder: Some(SeenValueStore::new(FlatBlockStore::new())), }, + _phantom: PhantomData, + } + } +} + +impl Default for NullState> { + fn default() -> Self { + Self::new() + } +} + +impl NullState> { + /// Create a new [`BlockedNullState`] with the given block size. + pub fn new(block_size: usize) -> Self { + Self { + seen_values: SeenValues::All { + num_values: 0, + pending_builder: Some(SeenValueStore::new(BlockedBlockStore::new( + block_size, + ))), + }, + _phantom: PhantomData, } } } @@ -483,6 +846,8 @@ pub fn accumulate( /// * `group_idx`: The group index for the current row /// * `batch_idx`: The index of the current row in the input arrays /// * `columns`: Reference to all input arrays for accessing values +// TODO: support `blocked group index` for `accumulate_multiple` +// (for supporting `blocked group index` for correlation group accumulator) pub fn accumulate_multiple( group_indices: &[usize], value_columns: &[&PrimitiveArray], @@ -539,6 +904,8 @@ pub fn accumulate_multiple( /// /// See [`NullState::accumulate`], for more details on other /// arguments. +// TODO: support `blocked group index` for `accumulate_indices` +// (for supporting `blocked group index` for count group accumulator) pub fn accumulate_indices( group_indices: &[usize], nulls: Option<&NullBuffer>, @@ -678,41 +1045,97 @@ mod test { buffer::BooleanBuffer, }; use rand::{Rng, rngs::ThreadRng}; - use std::collections::HashSet; + use std::{cmp, collections::HashMap, collections::HashSet}; - #[test] - fn accumulate() { - let group_indices = (0..100).collect(); - let values = (0..100).map(|i| (i + 1) * 10).collect(); - let values_with_nulls = (0..100) - .map(|i| if i % 3 == 0 { None } else { Some((i + 1) * 10) }) - .collect(); - - // default to every fifth value being false, every even - // being null - let filter: BooleanArray = (0..100) - .map(|i| { - let is_even = i % 2 == 0; - let is_fifth = i % 5 == 0; - if is_even { - None - } else if is_fifth { - Some(false) - } else { - Some(true) - } - }) - .collect(); - - Fixture { - group_indices, - values, - values_with_nulls, - filter, + enum TestNullState { + Flat(FlatNullState), + Blocked(BlockedNullState), + } + + impl TestNullState { + fn accumulate( + &mut self, + group_indices: &[usize], + values: &PrimitiveArray, + opt_filter: Option<&BooleanArray>, + total_num_groups: usize, + value_fn: F, + ) where + T: ArrowPrimitiveType + Send, + F: FnMut(u32, u64, T::Native) + Send, + { + match self { + Self::Flat(null_state) => null_state.accumulate( + group_indices, + values, + opt_filter, + total_num_groups, + value_fn, + ), + Self::Blocked(null_state) => null_state.accumulate( + group_indices, + values, + opt_filter, + total_num_groups, + value_fn, + ), + } + } + + fn accumulate_boolean( + &mut self, + group_indices: &[usize], + values: &BooleanArray, + opt_filter: Option<&BooleanArray>, + total_num_groups: usize, + value_fn: F, + ) where + F: FnMut(u32, u64, bool) + Send, + { + match self { + Self::Flat(null_state) => null_state.accumulate_boolean( + group_indices, + values, + opt_filter, + total_num_groups, + value_fn, + ), + Self::Blocked(null_state) => null_state.accumulate_boolean( + group_indices, + values, + opt_filter, + total_num_groups, + value_fn, + ), + } + } + + fn build_cloned_seen_values(&self) -> TestSeenValuesResult { + match self { + Self::Flat(null_state) => null_state.build_cloned_seen_values(), + Self::Blocked(null_state) => null_state.build_cloned_seen_values(), + } + } + + fn build_single_null_buffer(&mut self) -> Option { + match self { + Self::Flat(null_state) => null_state.build_single_null_buffer(), + Self::Blocked(null_state) => null_state.build_single_null_buffer(), + } } - .run() } + /// Tests NullState accumulation with a deterministic fixture: 100 dense + /// group indices (0..100), fixed null/filter patterns, block_size=3, + /// acc_rounds=5. Covers flat and blocked modes, with/without nulls and filters. + #[test] + fn accumulate_fixed() { + Fixture::new_fixed().run(); + } + + /// Tests NullState accumulation with 100 randomized fixtures. + /// Group indices are generated via hash-table-style dedup (dense 0..N), + /// matching real GroupedHashAggregateStream behavior. #[test] fn accumulate_fuzz() { let mut rng = rand::rng(); @@ -735,22 +1158,86 @@ mod test { /// filter (defaults to None) filter: BooleanArray, + + /// block size for testing [`BlockedNullState`] + block_size: usize, + + acc_rounds: usize, } impl Fixture { + fn new_fixed() -> Self { + let group_indices = (0..100).collect(); + let values = (0..100).map(|i| (i + 1) * 10).collect(); + let values_with_nulls = (0..100) + .map(|i| if i % 3 == 0 { None } else { Some((i + 1) * 10) }) + .collect(); + + // default to every fifth value being false, every even + // being null + let filter: BooleanArray = (0..100) + .map(|i| { + let is_even = i % 2 == 0; + let is_fifth = i % 5 == 0; + if is_even { + None + } else if is_fifth { + Some(false) + } else { + Some(true) + } + }) + .collect(); + + Self { + group_indices, + values, + values_with_nulls, + filter, + block_size: 3, + acc_rounds: 5, + } + } + fn new_random(rng: &mut ThreadRng) -> Self { // Number of input values in a batch let num_values: usize = rng.random_range(1..200); - // number of distinct groups - let num_groups: usize = rng.random_range(2..1000); - let max_group = num_groups - 1; - + // number of distinct "raw keys" each row can map to + let num_distinct_keys: usize = rng.random_range(2..1000); + + // Simulate hash-table dedup: each row gets a random raw key, + // and a HashMap assigns group indices sequentially (0, 1, 2, …). + // This guarantees group_indices are dense in 0..num_groups, just + // like real GroupedHashAggregateStream behavior. + // + // Example: raw keys = [7, 3, 7, 5, 3] + // → first-seen order: 7→0, 3→1, 5→2 + // → group_indices : [0, 1, 0, 2, 1] + // → total_num_groups = 3 (all of 0,1,2 actually appeared) + let mut key_to_group: HashMap = HashMap::new(); + let mut next_group_index: usize = 0; let group_indices: Vec = (0..num_values) - .map(|_| rng.random_range(0..max_group)) + .map(|_| { + let raw_key = rng.random_range(0..num_distinct_keys); + let len = key_to_group.len(); + *key_to_group.entry(raw_key).or_insert_with(|| { + let idx = len; + next_group_index = len + 1; + idx + }) + }) .collect(); + let num_groups = next_group_index; + let values: Vec = (0..num_values).map(|_| rng.random()).collect(); + // random block size + let block_size = rng.random_range(1..cmp::max(num_groups, 2)); + + // random acc rounds + let acc_rounds = rng.random_range(1..=group_indices.len()); + // 10% chance of false // 10% change of null // 80% chance of true @@ -782,6 +1269,8 @@ mod test { values, values_with_nulls, filter, + block_size, + acc_rounds, } } @@ -806,7 +1295,14 @@ mod test { let filter = &self.filter; // no null, no filters - Self::accumulate_test(group_indices, &values_array, None, total_num_groups); + Self::accumulate_test( + group_indices, + &values_array, + None, + total_num_groups, + self.block_size, + self.acc_rounds, + ); // nulls, no filters Self::accumulate_test( @@ -814,6 +1310,8 @@ mod test { &values_with_nulls_array, None, total_num_groups, + self.block_size, + self.acc_rounds, ); // no nulls, filters @@ -822,6 +1320,8 @@ mod test { &values_array, Some(filter), total_num_groups, + self.block_size, + self.acc_rounds, ); // nulls, filters @@ -830,6 +1330,8 @@ mod test { &values_with_nulls_array, Some(filter), total_num_groups, + self.block_size, + self.acc_rounds, ); } @@ -840,26 +1342,97 @@ mod test { values: &UInt32Array, opt_filter: Option<&BooleanArray>, total_num_groups: usize, + block_size: usize, + acc_rounds: usize, ) { + // Test `accumulate` of `FlatNullState` + accumulate in once Self::accumulate_values_test( group_indices, values, opt_filter, total_num_groups, + None, + None, + ); + + // Test `accumulate` of `FlatNullState` + accumulate in multiple times + Self::accumulate_values_test( + group_indices, + values, + opt_filter, + total_num_groups, + None, + Some(acc_rounds), + ); + + // Test `accumulate` of `BlockedNullState` + accumulate in once + Self::accumulate_values_test( + group_indices, + values, + opt_filter, + total_num_groups, + Some(block_size), + None, + ); + + // Test `accumulate` of `BlockedNullState` + accumulate in multiple times + Self::accumulate_values_test( + group_indices, + values, + opt_filter, + total_num_groups, + Some(block_size), + Some(acc_rounds), ); - Self::accumulate_indices_test(group_indices, values.nulls(), opt_filter); // Convert values into a boolean array (anything above the // average is true, otherwise false) let avg: usize = values.iter().filter_map(|v| v.map(|v| v as usize)).sum(); let boolean_values: BooleanArray = values.iter().map(|v| v.map(|v| v as usize > avg)).collect(); + + // Test `accumulate_boolean` of `FlatNullState` + accumulate in once + Self::accumulate_boolean_test( + group_indices, + &boolean_values, + opt_filter, + total_num_groups, + None, + None, + ); + + // Test `accumulate_boolean` of `FlatNullState` + accumulate in multiple times + Self::accumulate_boolean_test( + group_indices, + &boolean_values, + opt_filter, + total_num_groups, + None, + Some(acc_rounds), + ); + + // Test `accumulate_boolean` of `BlockedNullState` + accumulate in once Self::accumulate_boolean_test( group_indices, &boolean_values, opt_filter, total_num_groups, + Some(block_size), + None, ); + + // Test `accumulate_boolean` of `BlockedNullState` + accumulate in multiple times + Self::accumulate_boolean_test( + group_indices, + &boolean_values, + opt_filter, + total_num_groups, + Some(block_size), + Some(acc_rounds), + ); + + // Test `accumulate_indices` + Self::accumulate_indices_test(group_indices, values.nulls(), opt_filter); } /// This is effectively a different implementation of @@ -869,19 +1442,109 @@ mod test { values: &UInt32Array, opt_filter: Option<&BooleanArray>, total_num_groups: usize, + block_size: Option, + acc_rounds: Option, ) { - let mut accumulated_values = vec![]; - let mut null_state = NullState::new(); + // Chunking `group_indices`, `values`, `opt_filter`, and we also need to generate + // `chunked acc_group_indices` basing on `group_indices` + let (group_indices_chunks, values_chunks, opt_filter_chunks) = + if let Some(rounds) = acc_rounds { + let chunk_size = group_indices.len() / rounds; + + let group_indices_chunks = group_indices + .chunks(chunk_size) + .map(|chunk| chunk.to_vec()) + .collect::>(); + + let values_chunks = values + .iter() + .collect::>() + .chunks(chunk_size) + .map(|chunk| UInt32Array::from_iter(chunk.iter().copied())) + .collect::>(); + + let opt_filter_chunks = if let Some(filter) = opt_filter { + filter + .iter() + .collect::>() + .chunks(chunk_size) + .map(|chunk| Some(BooleanArray::from_iter(chunk.iter()))) + .collect::>() + } else { + vec![None; values_chunks.len()] + }; - null_state.accumulate( - group_indices, - values, - opt_filter, - total_num_groups, - |group_index, value| { - accumulated_values.push((group_index, value)); - }, - ); + (group_indices_chunks, values_chunks, opt_filter_chunks) + } else { + ( + vec![group_indices.to_vec()], + vec![values.clone()], + vec![opt_filter.cloned()], + ) + }; + + let mut total_num_groups_chunks = vec![]; + let mut cur_total_num_groups = usize::MIN; + for group_indices in &group_indices_chunks { + let num_groups = *group_indices.iter().max().unwrap() + 1; + cur_total_num_groups = cmp::max(cur_total_num_groups, num_groups); + total_num_groups_chunks.push(cur_total_num_groups); + } + + // Build needed test contexts + let (mut null_state, block_size, acc_group_indices_chunks) = + if let Some(blk_size) = block_size { + let mut acc_group_indices_chunks = vec![]; + for group_indices in group_indices_chunks { + let acc_group_indices = group_indices + .into_iter() + .map(|index| { + let block_id = (index / blk_size) as u32; + let block_offset = (index % blk_size) as u64; + BlockedGroupIndexOperations::pack_index( + block_id, + block_offset, + ) as usize + }) + .collect::>(); + acc_group_indices_chunks.push(acc_group_indices); + } + + ( + TestNullState::Blocked(BlockedNullState::new(blk_size)), + blk_size, + acc_group_indices_chunks, + ) + } else { + ( + TestNullState::Flat(FlatNullState::new()), + 0, + group_indices_chunks, + ) + }; + + // Start the test + let mut accumulated_values = vec![]; + for (((acc_group_indices, values), total_num_groups), cur_opt_filter) in + acc_group_indices_chunks + .into_iter() + .zip(values_chunks) + .zip(total_num_groups_chunks) + .zip(opt_filter_chunks) + { + null_state.accumulate( + &acc_group_indices, + &values, + cur_opt_filter.as_ref(), + total_num_groups, + |block_id, block_offset, value| { + let flatten_index = ((block_id as u64 * block_size as u64) + + block_offset) + as usize; + accumulated_values.push((flatten_index, value)); + }, + ); + } // Figure out the expected values let mut expected_values = vec![]; @@ -917,21 +1580,20 @@ mod test { accumulated_values, expected_values, "\n\naccumulated_values:{accumulated_values:#?}\n\nexpected_values:{expected_values:#?}" ); - - match &null_state.seen_values { - SeenValues::All { num_values } => { - assert_eq!(*num_values, total_num_groups); + let seen_values_result = null_state.build_cloned_seen_values(); + match &seen_values_result { + TestSeenValuesResult::All(num_values) => { + assert_eq!(*num_values, total_num_groups) } - SeenValues::Some { values } => { - let seen_values = values.finish_cloned(); - mock.validate_seen_values(&seen_values); + TestSeenValuesResult::Some(seen_values) => { + mock.validate_seen_values(seen_values); } } // Validate the final buffer (one value per group) let expected_null_buffer = mock.expected_null_buffer(total_num_groups); - let null_buffer = null_state.build(EmitTo::All); + let null_buffer = null_state.build_single_null_buffer(); if let Some(nulls) = &null_buffer { assert_eq!(*nulls, expected_null_buffer); } @@ -998,19 +1660,109 @@ mod test { values: &BooleanArray, opt_filter: Option<&BooleanArray>, total_num_groups: usize, + block_size: Option, + acc_rounds: Option, ) { - let mut accumulated_values = vec![]; - let mut null_state = NullState::new(); + // Chunking `group_indices`, `values`, `opt_filter`, and we also need to generate + // `chunked acc_group_indices` basing on `group_indices` + let (group_indices_chunks, values_chunks, opt_filter_chunks) = + if let Some(rounds) = acc_rounds { + let chunk_size = group_indices.len() / rounds; + + let group_indices_chunks = group_indices + .chunks(chunk_size) + .map(|chunk| chunk.to_vec()) + .collect::>(); + + let values_chunks = values + .iter() + .collect::>() + .chunks(chunk_size) + .map(|chunk| BooleanArray::from_iter(chunk.iter().copied())) + .collect::>(); + + let opt_filter_chunks = if let Some(filter) = opt_filter { + filter + .iter() + .collect::>() + .chunks(chunk_size) + .map(|chunk| Some(BooleanArray::from_iter(chunk.iter()))) + .collect::>() + } else { + vec![None; values_chunks.len()] + }; - null_state.accumulate_boolean( - group_indices, - values, - opt_filter, - total_num_groups, - |group_index, value| { - accumulated_values.push((group_index, value)); - }, - ); + (group_indices_chunks, values_chunks, opt_filter_chunks) + } else { + ( + vec![group_indices.to_vec()], + vec![values.clone()], + vec![opt_filter.cloned()], + ) + }; + + let mut total_num_groups_chunks = vec![]; + let mut cur_total_num_groups = usize::MIN; + for group_indices in &group_indices_chunks { + let num_groups = *group_indices.iter().max().unwrap() + 1; + cur_total_num_groups = cmp::max(cur_total_num_groups, num_groups); + total_num_groups_chunks.push(cur_total_num_groups); + } + + // Build needed test contexts + let (mut null_state, block_size, acc_group_indices_chunks) = + if let Some(blk_size) = block_size { + let mut acc_group_indices_chunks = vec![]; + for group_indices in group_indices_chunks { + let acc_group_indices = group_indices + .into_iter() + .map(|index| { + let block_id = (index / blk_size) as u32; + let block_offset = (index % blk_size) as u64; + BlockedGroupIndexOperations::pack_index( + block_id, + block_offset, + ) as usize + }) + .collect::>(); + acc_group_indices_chunks.push(acc_group_indices); + } + + ( + TestNullState::Blocked(BlockedNullState::new(blk_size)), + blk_size, + acc_group_indices_chunks, + ) + } else { + ( + TestNullState::Flat(FlatNullState::new()), + 0, + group_indices_chunks, + ) + }; + + // Start the test + let mut accumulated_values = vec![]; + for (((acc_group_indices, values), total_num_groups), opt_filter) in + acc_group_indices_chunks + .into_iter() + .zip(values_chunks) + .zip(total_num_groups_chunks) + .zip(opt_filter_chunks) + { + null_state.accumulate_boolean( + &acc_group_indices, + &values, + opt_filter.as_ref(), + total_num_groups, + |block_id, block_offset, value| { + let flatten_index = ((block_id as u64 * block_size as u64) + + block_offset) + as usize; + accumulated_values.push((flatten_index, value)); + }, + ); + } // Figure out the expected values let mut expected_values = vec![]; @@ -1047,24 +1799,22 @@ mod test { "\n\naccumulated_values:{accumulated_values:#?}\n\nexpected_values:{expected_values:#?}" ); - match &null_state.seen_values { - SeenValues::All { num_values } => { - assert_eq!(*num_values, total_num_groups); + let seen_values_result = null_state.build_cloned_seen_values(); + match &seen_values_result { + TestSeenValuesResult::All(num_values) => { + assert_eq!(*num_values, total_num_groups) } - SeenValues::Some { values } => { - let seen_values = values.finish_cloned(); - mock.validate_seen_values(&seen_values); + TestSeenValuesResult::Some(seen_values) => { + mock.validate_seen_values(seen_values); } } // Validate the final buffer (one value per group) - let expected_null_buffer = Some(mock.expected_null_buffer(total_num_groups)); - - let is_all_seen = matches!(null_state.seen_values, SeenValues::All { .. }); - let null_buffer = null_state.build(EmitTo::All); + let expected_null_buffer = mock.expected_null_buffer(total_num_groups); + let null_buffer = null_state.build_single_null_buffer(); - if !is_all_seen { - assert_eq!(null_buffer, expected_null_buffer); + if let Some(buffer) = null_buffer { + assert_eq!(buffer, expected_null_buffer); } } } diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/blocked.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/blocked.rs new file mode 100644 index 0000000000000..02bc9a03d03f2 --- /dev/null +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/blocked.rs @@ -0,0 +1,436 @@ +// 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. + +//! Blocked [`BlockStore`] implementation. + +use std::{ + fmt::Debug, + mem, + ops::{Index, IndexMut}, +}; + +use crate::aggregate::groups_accumulator::block_store::{Block, BlockStore}; + +/// Structure used to store aggregation intermediate results in `blocked approach` +/// +/// Aggregation intermediate results will be stored as multiple [`Block`]s +/// (simply you can think a [`Block`] as a `Vec`). And `Blocks` is the structure +/// to represent such multiple [`Block`]s. +/// +/// Blocks are popped in FIFO order by keeping a cursor into `inner`. Popping a +/// block swaps it out in O(1) using `mem::take` and advances the cursor, +/// avoiding the O(n) shift cost of `Vec::remove(0)`. +/// +/// More details about `blocked approach` can see in: [`GroupsAccumulator::supports_blocked_groups`]. +/// +/// [`GroupsAccumulator::supports_blocked_groups`]: datafusion_expr_common::groups_accumulator::GroupsAccumulator::supports_blocked_groups +/// +#[derive(Debug)] +pub struct BlockedBlockStore { + inner: Vec, + /// Index of the next active block. + cursor: usize, + block_size: usize, +} + +impl BlockedBlockStore { + /// Create a new blocked store with the given fixed block size. + pub fn new(block_size: usize) -> Self { + Self { + inner: Vec::new(), + cursor: 0, + block_size, + } + } +} + +impl BlockStore for BlockedBlockStore { + fn push_block(&mut self, block: B) { + self.inner.push(block); + } + + fn pop_block(&mut self) -> Option { + if self.cursor >= self.inner.len() { + return None; + } + + let block = mem::take(&mut self.inner[self.cursor]); + self.cursor += 1; + Some(block) + } + + fn reserve_blocks(&mut self) { + let block_size = self.block_size; + if self.num_blocks() == 0 + || self + .inner + .last() + .is_some_and(|block| block.len() == block_size) + { + self.inner.push(B::new(block_size)); + } + } + + fn resize(&mut self, total_num_groups: usize, default_value: B::T) { + let block_size = self.block_size; + let num_blocks = self.num_blocks(); + let current_len = if num_blocks == 0 { + 0 + } else { + (num_blocks - 1) * block_size + self.inner.last().unwrap().len() + }; + + if current_len >= total_num_groups { + return; + } + + let mut to_fill = total_num_groups - current_len; + + if num_blocks > 0 { + let last_block = self.inner.last_mut().unwrap(); + let available = block_size - last_block.len(); + let fill_len = to_fill.min(available); + if fill_len > 0 { + last_block.fill_default_value(fill_len, default_value.clone()); + to_fill -= fill_len; + } + } + + while to_fill >= block_size { + let mut block = B::new(block_size); + block.fill_default_value(block_size, default_value.clone()); + self.inner.push(block); + to_fill -= block_size; + } + + if to_fill > 0 { + let mut block = B::new(block_size); + block.fill_default_value(to_fill, default_value.clone()); + self.inner.push(block); + } + } + + fn num_blocks(&self) -> usize { + debug_assert!(self.cursor <= self.inner.len()); + self.inner.len() - self.cursor + } + + fn block_size(&self) -> Option { + Some(self.block_size) + } + + fn clear(&mut self) { + self.inner.clear(); + self.cursor = 0; + } +} + +impl Index for BlockedBlockStore { + type Output = B; + + #[inline] + fn index(&self, index: usize) -> &Self::Output { + unsafe { self.inner.get_unchecked(self.cursor + index) } + } +} + +impl IndexMut for BlockedBlockStore { + #[inline] + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + unsafe { self.inner.get_unchecked_mut(self.cursor + index) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + type TestBlocks = BlockedBlockStore>; + + fn assert_block(block: &[u32], expected: &[u32]) { + assert_eq!(block, expected); + } + + // ---- push_block ---- + + // Covers the generic BlockStore trait behavior for Vec-backed blocks. + // Example: resize to 5 with block_size = 2 yields [42, 42], [42, 42], [42]. + #[test] + fn test_block_store_trait_resizes_vec_blocks() { + let mut store = BlockedBlockStore::>::new(2); + store.resize(5, 42); + assert_eq!(BlockStore::num_blocks(&store), 3); + assert_eq!(store[0], vec![42, 42]); + assert_eq!(store[1], vec![42, 42]); + assert_eq!(store[2], vec![42]); + } + + // ---- pop_block ---- + + // Covers draining blocks in FIFO order and updating active block count. + // Example: [[1, 42, 42], [2, 42, 42], [3]] pops in that exact order. + #[test] + fn test_pop_block_drains_blocks_in_fifo_order() { + let mut blocks = TestBlocks::new(3); + blocks.resize(7, 42); + blocks[0][0] = 1; + blocks[1][0] = 2; + blocks[2][0] = 3; + assert_eq!(blocks.num_blocks(), 3); + + let blk0 = blocks.pop_block().unwrap(); + assert_block(&blk0, &[1, 42, 42]); + assert_eq!(blocks.num_blocks(), 2); + assert_ne!(blocks.num_blocks(), 0); + + let blk1 = blocks.pop_block().unwrap(); + assert_block(&blk1, &[2, 42, 42]); + assert_eq!(blocks.num_blocks(), 1); + + let blk2 = blocks.pop_block().unwrap(); + assert_block(&blk2, &[3]); + assert_eq!(blocks.num_blocks(), 0); + assert_eq!(blocks.num_blocks(), 0); + assert!(blocks.pop_block().is_none()); + } + + // Covers push_block appending behind the current cursor. + // Example: after popping [1, 2], a newly pushed [4, 5] is emitted after existing [3]. + #[test] + fn test_push_block_appends_after_unpopped_blocks() { + let mut blocks = TestBlocks::new(2); + blocks.push_block(vec![1, 2]); + blocks.push_block(vec![3]); + + assert_eq!(blocks.pop_block(), Some(vec![1, 2])); + + blocks.push_block(vec![4, 5]); + assert_eq!(blocks.num_blocks(), 2); + assert_eq!(blocks.pop_block(), Some(vec![3])); + assert_eq!(blocks.pop_block(), Some(vec![4, 5])); + assert_eq!(blocks.pop_block(), None); + + blocks.push_block(vec![6]); + assert_eq!(blocks.num_blocks(), 1); + assert_eq!(blocks.pop_block(), Some(vec![6])); + } + + // Covers appending a fresh block after all existing blocks have been popped. + // Example: after [1] is emitted, pushing [2] makes [2] the only active block. + #[test] + fn test_push_block_appends_after_exhausted_prefix() { + let mut blocks = TestBlocks::new(2); + blocks.push_block(vec![1]); + + assert_eq!(blocks.pop_block(), Some(vec![1])); + assert_eq!(blocks.pop_block(), None); + + blocks.push_block(vec![2]); + assert_eq!(blocks.num_blocks(), 1); + assert_eq!(blocks[0], vec![2]); + assert_eq!(blocks.pop_block(), Some(vec![2])); + assert_eq!(blocks.pop_block(), None); + } + + // ---- index ---- + + // Covers index and index_mut addressing active blocks after the pop cursor moves. + // Example: after popping [1], store[0] addresses [2, 3] and can mutate it. + #[test] + fn test_index_accesses_active_blocks_after_pop_cursor_moves() { + let mut blocks = TestBlocks::new(2); + blocks.push_block(vec![1]); + blocks.push_block(vec![2, 3]); + + assert_eq!(blocks.pop_block(), Some(vec![1])); + assert_eq!(blocks[0], vec![2, 3]); + + blocks[0][0] = 4; + assert_eq!(blocks.pop_block(), Some(vec![4, 3])); + assert_eq!(blocks.pop_block(), None); + } + + // ---- reserve_blocks ---- + + // Covers reserve_blocks only appending when the current tail block is full. + // Example: block_size = 2 appends a second block only after pushing two values. + #[test] + fn test_reserve_blocks_appends_only_when_tail_block_is_full() { + let mut store = BlockedBlockStore::>::new(2); + store.reserve_blocks(); + assert_eq!(BlockStore::num_blocks(&store), 1); + assert_eq!(store[0].capacity(), 2); + + store[0].push(1); + store.reserve_blocks(); + assert_eq!(BlockStore::num_blocks(&store), 1); + + store[0].push(2); + store.reserve_blocks(); + assert_eq!(BlockStore::num_blocks(&store), 2); + assert_eq!(store[1].capacity(), 2); + assert!(store[1].is_empty()); + } + + // Covers reserve_blocks appending after all previous blocks have been popped. + // Example: after popping [1, 2], reserve_blocks creates a new active empty block. + #[test] + fn test_reserve_blocks_appends_after_pop_cursor_is_exhausted() { + let mut store = BlockedBlockStore::>::new(2); + store.push_block(vec![1, 2]); + + assert_eq!(store.pop_block(), Some(vec![1, 2])); + assert_eq!(store.num_blocks(), 0); + + store.reserve_blocks(); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store[0].capacity(), 2); + assert!(store[0].is_empty()); + } + + // ---- resize ---- + + // Covers growth that stays within a single block. + // Example: block_size = 10, resize 0 -> 5 -> 10 keeps one block: [42; 10]. + #[test] + fn test_resize_grows_within_one_block() { + let mut blocks = TestBlocks::new(10); + assert_eq!(blocks.num_blocks(), 0); + + for _ in 0..2 { + blocks.resize(5, 42); + assert_eq!(blocks.num_blocks(), 1); + assert_eq!(blocks[0].len(), 5); + blocks[0].iter().for_each(|num| assert_eq!(*num, 42)); + + blocks.resize(10, 42); + assert_eq!(blocks.num_blocks(), 1); + assert_eq!(blocks[0].len(), 10); + blocks[0].iter().for_each(|num| assert_eq!(*num, 42)); + + blocks.clear(); + assert_eq!(blocks.num_blocks(), 0); + } + } + + // Covers growth across multiple fixed-size blocks. + // Example: block_size = 3, resize to 10 creates [3, 3, 3, 1] sized blocks. + #[test] + fn test_resize_grows_across_multiple_blocks() { + let mut blocks = TestBlocks::new(3); + assert_eq!(blocks.num_blocks(), 0); + + for _ in 0..2 { + blocks.resize(5, 42); + assert_eq!(blocks.num_blocks(), 2); + assert_eq!(blocks[0].len(), 3); + blocks[0].iter().for_each(|num| assert_eq!(*num, 42)); + assert_eq!(blocks[1].len(), 2); + blocks[1].iter().for_each(|num| assert_eq!(*num, 42)); + + blocks.resize(10, 42); + assert_eq!(blocks.num_blocks(), 4); + assert_eq!(blocks[0].len(), 3); + blocks[0].iter().for_each(|num| assert_eq!(*num, 42)); + assert_eq!(blocks[1].len(), 3); + blocks[1].iter().for_each(|num| assert_eq!(*num, 42)); + assert_eq!(blocks[2].len(), 3); + blocks[2].iter().for_each(|num| assert_eq!(*num, 42)); + assert_eq!(blocks[3].len(), 1); + blocks[3].iter().for_each(|num| assert_eq!(*num, 42)); + + blocks.clear(); + assert_eq!(blocks.num_blocks(), 0); + } + } + + // Covers resize as a monotonic grow-only operation that preserves existing values. + // Example: resizing 4 groups down to 2 does not truncate [10, 99, 10], [77]. + #[test] + fn test_resize_preserves_values_when_requested_size_shrinks() { + let mut store = BlockedBlockStore::>::new(3); + store.resize(4, 10); + store[0][1] = 99; + store[1][0] = 77; + + store.resize(2, 0); + assert_eq!(store.num_blocks(), 2); + assert_block(&store[0], &[10, 99, 10]); + assert_block(&store[1], &[77]); + + store.resize(8, 5); + assert_eq!(store.num_blocks(), 3); + assert_block(&store[0], &[10, 99, 10]); + assert_block(&store[1], &[77, 5, 5]); + assert_block(&store[2], &[5, 5]); + } + + // Covers resize growing only the active suffix after the pop cursor moves. + // Example: after popping [1, 2], resizing active [3] to 4 groups yields [3, 9], [9, 9]. + #[test] + fn test_resize_grows_active_blocks_after_pop_cursor_moves() { + let mut store = BlockedBlockStore::>::new(2); + store.push_block(vec![1, 2]); + store.push_block(vec![3]); + + assert_eq!(store.pop_block(), Some(vec![1, 2])); + store.resize(4, 9); + + assert_eq!(store.num_blocks(), 2); + assert_block(&store[0], &[3, 9]); + assert_block(&store[1], &[9, 9]); + assert_eq!(store.pop_block(), Some(vec![3, 9])); + assert_eq!(store.pop_block(), Some(vec![9, 9])); + assert_eq!(store.pop_block(), None); + } + + // Covers resize reusing an empty block created by reserve_blocks. + // Example: reserve_blocks with block_size = 4, resize to 3 fills the existing block with [11, 11, 11]. + #[test] + fn test_resize_fills_empty_block_created_by_reserve_blocks() { + let mut store = BlockedBlockStore::>::new(4); + store.reserve_blocks(); + + store.resize(3, 11); + assert_eq!(store.num_blocks(), 1); + assert_block(&store[0], &[11, 11, 11]); + + store.resize(6, 22); + assert_eq!(store.num_blocks(), 2); + assert_block(&store[0], &[11, 11, 11, 22]); + assert_block(&store[1], &[22, 22]); + } + + // ---- clear ---- + + // Covers clear resetting both accumulated blocks and the pop cursor. + // Example: after popping the first of three blocks, clear allows a fresh resize to [9]. + #[test] + fn test_clear_resets_pop_cursor() { + let mut store = BlockedBlockStore::>::new(2); + store.resize(5, 1); + assert_eq!(store.pop_block(), Some(vec![1, 1])); + assert_eq!(store.num_blocks(), 2); + + store.clear(); + assert_eq!(store.num_blocks(), 0); + + store.resize(1, 9); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.pop_block(), Some(vec![9])); + } +} diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/flat.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/flat.rs new file mode 100644 index 0000000000000..8fe8db5de3c89 --- /dev/null +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/flat.rs @@ -0,0 +1,232 @@ +// 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. + +//! Flat [`BlockStore`] implementation backed by a single block. + +use std::ops::{Index, IndexMut}; +use std::{fmt::Debug, mem}; + +use crate::aggregate::groups_accumulator::block_store::{Block, BlockStore}; + +/// A flat [`BlockStore`] implementation backed by a single block. +/// +/// This newtype is intended for flat group state where `block_id` is always 0. +/// The physical layout is exactly one `B`, avoiding the extra `Vec` lookup +/// needed by blocked storage. +#[derive(Debug)] +pub struct FlatBlockStore(B); + +impl FlatBlockStore { + /// Create a new flat store with an empty default block. + pub fn new() -> Self { + Self(B::default()) + } +} + +impl Default for FlatBlockStore { + fn default() -> Self { + Self::new() + } +} + +impl BlockStore for FlatBlockStore { + fn push_block(&mut self, block: B) { + self.0 = block; + } + + fn pop_block(&mut self) -> Option { + let block = mem::take(&mut self.0); + Some(block) + } + + fn reserve_blocks(&mut self) {} + + fn resize(&mut self, total_num_groups: usize, default_value: B::T) { + if total_num_groups == 0 { + return; + } + + if self.0.is_empty() { + self.0 = B::new(0); + } + + let existing_len = self.0.len(); + if existing_len < total_num_groups { + self.0 + .fill_default_value(total_num_groups - existing_len, default_value); + } + } + + fn num_blocks(&self) -> usize { + 1 + } + + fn block_size(&self) -> Option { + None + } + + fn clear(&mut self) { + self.0 = B::default(); + } +} + +impl Index for FlatBlockStore { + type Output = B; + + #[inline] + fn index(&self, index: usize) -> &Self::Output { + assert_eq!(index, 0, "flat block store only has block 0"); + &self.0 + } +} + +impl IndexMut for FlatBlockStore { + #[inline] + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + assert_eq!(index, 0, "flat block store only has block 0"); + &mut self.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + type TestBlock = Vec; + + // ---- push_block ---- + + // Covers push_block replacing the whole single backing block. + // Example: pushing [7, 8, 9] over [1, 1] leaves exactly [7, 8, 9]. + #[test] + fn test_push_block_replaces_inner_flat_block() { + let mut store = FlatBlockStore::::new(); + store.resize(2, 1); + + store.push_block(vec![7, 8, 9]); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store[0], vec![7, 8, 9]); + } + + // ---- pop_block ---- + + // Covers pop_block taking the single backing block from flat storage. + // Example: popping a new flat store returns [], while popping [42, 7, 42] returns those values. + #[test] + fn test_pop_block_takes_single_flat_block() { + let mut store = FlatBlockStore::::new(); + assert_eq!(store.pop_block(), Some(vec![])); + + store.resize(3, 42); + store[0][1] = 7; + + assert_eq!(store.pop_block(), Some(vec![42, 7, 42])); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.pop_block(), Some(vec![])); + + store.resize(1, 5); + assert_eq!(store.pop_block(), Some(vec![5])); + } + + // ---- reserve_blocks ---- + + // Covers reserve_blocks being a no-op for flat storage. + // Example: reserve_blocks on a new flat store still leaves num_blocks() == 1. + #[test] + fn test_reserve_blocks_keeps_flat_store_unchanged() { + let mut store = FlatBlockStore::::new(); + store.reserve_blocks(); + assert_eq!(store.num_blocks(), 1); + + store.resize(1, 42); + store.reserve_blocks(); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store[0], vec![42]); + } + + // ---- resize ---- + + // Covers flat storage growth within its single backing block. + // Example: resize 0 -> 3 -> 5 yields one block [42, 42, 42, 7, 7]. + #[test] + fn test_resize_grows_single_flat_block() { + let mut store = FlatBlockStore::::new(); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + + store.resize(3, 42); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store[0], vec![42, 42, 42]); + + store.resize(5, 7); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store[0], vec![42, 42, 42, 7, 7]); + + store.clear(); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + } + + // Covers resize as a grow-only operation that preserves existing flat values. + // Example: resizing from 3 down to 1 keeps [99, 10, 10], then grows to append [7, 7]. + #[test] + fn test_resize_preserves_flat_values_when_requested_size_shrinks() { + let mut store = FlatBlockStore::::new(); + store.resize(3, 10); + store[0][0] = 99; + + store.resize(1, 0); + assert_eq!(store[0], vec![99, 10, 10]); + + store.resize(5, 7); + assert_eq!(store[0], vec![99, 10, 10, 7, 7]); + } + + // Covers resize(0, _) preserving the empty backing block in flat storage. + // Example: resize to zero keeps num_blocks() == 1 and pop_block returns []. + #[test] + fn test_resize_keeps_backing_block_empty_when_requested_size_is_zero() { + let mut store = FlatBlockStore::::new(); + store.resize(0, 42); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.pop_block(), Some(vec![])); + } + + // ---- index ---- + + // Covers index 0 read/write access to the single backing block. + // Example: writing store[0][1] = 7 changes [42, 42] into [42, 7]. + #[test] + fn test_index_accesses_inner_flat_block() { + let mut store = FlatBlockStore::::new(); + store.resize(2, 42); + + store[0][1] = 7; + assert_eq!(store[0], vec![42, 7]); + } + + // Covers rejecting any index other than 0 for flat storage. + // Example: store[1] panics because flat storage only exposes block 0. + #[test] + #[should_panic(expected = "flat block store only has block 0")] + fn test_index_rejects_non_zero_flat_block_index() { + let store = FlatBlockStore::::new(); + let _ = &store[1]; + } +} diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/mod.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/mod.rs new file mode 100644 index 0000000000000..146ddf9603893 --- /dev/null +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/mod.rs @@ -0,0 +1,109 @@ +// 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. + +//! Storage abstraction for aggregation intermediate result blocks. + +use std::fmt::Debug; +use std::ops::{Index, IndexMut}; + +pub mod blocked; +pub mod flat; +pub mod vec_block_store; + +pub use blocked::BlockedBlockStore; +pub use flat::FlatBlockStore; +pub use vec_block_store::VecBlockStore; + +/// Storage abstraction for aggregation intermediate result blocks. +/// +/// [`BlockStore`] lets flat and blocked group state share the same accumulation +/// flow while using different physical layouts. Implementations should keep +/// block lookup cheap because it is used by per-row accumulator update paths. +pub trait BlockStore: + Debug + Index + IndexMut +{ + /// Append or replace a block in the store. + /// + /// Blocked storage appends `block` to the accumulated block list. Flat + /// storage replaces its single backing block with `block`. + fn push_block(&mut self, block: B); + + /// Remove and return the next block to emit. + /// + /// Returns `None` when there are no active blocks left. Blocked storage + /// pops blocks in insertion order. Flat storage returns its single backing + /// block once, then becomes empty. + fn pop_block(&mut self) -> Option; + + /// Reserve block capacity for pushing one value. + /// + /// Implementations may allocate a new block only when the current storage + /// cannot accept another value without growing. This does not change the + /// logical number of values held by the store. + fn reserve_blocks(&mut self); + + /// Ensure the store contains slots for `total_num_groups` values. + /// + /// Missing slots are appended and filled with `default_value`. Existing + /// values are preserved, and implementations do not shrink when + /// `total_num_groups` is less than or equal to the current logical length. + fn resize(&mut self, total_num_groups: usize, default_value: B::T); + + /// Return the number of active blocks. + /// + /// This counts blocks visible to the current phase. During blocked + /// emission, blocks already returned by [`Self::pop_block`] are excluded. + fn num_blocks(&self) -> usize; + + /// Return the configured block size for blocked storage. + /// + /// Returns `None` for flat storage because it has no configured block size. + fn block_size(&self) -> Option; + + /// Clear all active blocks and reset the store to accumulation mode. + /// + /// Any in-progress emission state is discarded. After `clear`, the store + /// behaves like a newly constructed empty store with the same configuration. + fn clear(&mut self); +} + +/// The abstraction to represent one aggregation intermediate result block +/// in `blocked approach`, multiple blocks compose a [`BlockStore`]. +/// +/// Many types of aggregation intermediate result exist, and we define an interface +/// to abstract the necessary behaviors of various intermediate result types. +pub trait Block: Debug + Default { + type T: Clone; + + /// Create a new empty block with the given capacity hint. + /// + /// `capacity` is `0` for flat storage (no hint) and the configured block + /// size for blocked storage. Implementations should treat `0` the same as + /// `Default::default()`. + fn new(capacity: usize) -> Self; + + /// Fill the block with default value + fn fill_default_value(&mut self, fill_len: usize, default_value: Self::T); + + /// Return the length of the block + fn len(&self) -> usize; + + /// Return true if the block is empty + fn is_empty(&self) -> bool { + self.len() == 0 + } +} diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/vec_block_store.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/vec_block_store.rs new file mode 100644 index 0000000000000..22f653f332fd4 --- /dev/null +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/block_store/vec_block_store.rs @@ -0,0 +1,298 @@ +// 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. + +//! [`BlockStore`] wrapper specialized for stores whose blocks are `Vec`. + +use std::fmt::Debug; +use std::iter; +use std::marker::PhantomData; +use std::ops::{Index, IndexMut}; + +use datafusion_common::utils::split_vec_min_alloc; +use datafusion_common::{Result, internal_datafusion_err, internal_err}; +use datafusion_expr_common::groups_accumulator::EmitTo; + +use crate::aggregate::groups_accumulator::block_store::{Block, BlockStore}; + +/// Thin wrapper around a [`BlockStore>`] that adds vector-specific +/// emit semantics on top of the generic block store API. +/// +/// Emitting `EmitTo::First` requires vector-specific split semantics, so it +/// lives on this wrapper rather than on [`BlockStore`] itself. The wrapper +/// re-exposes every [`BlockStore`] method by delegation, plus an [`emit`] +/// method implemented purely via [`BlockStore::push_block`] / +/// [`BlockStore::pop_block`] so it works uniformly over flat and blocked +/// storage. +/// +/// [`emit`]: VecBlockStore::emit +#[derive(Debug)] +pub struct VecBlockStore +where + T: Clone + Debug, + S: BlockStore>, +{ + inner: S, + _phantom: PhantomData, +} + +impl VecBlockStore +where + T: Clone + Debug, + S: BlockStore>, +{ + /// Wrap an existing block store. + pub fn new(inner: S) -> Self { + Self { + inner, + _phantom: PhantomData, + } + } + + // ---- BlockStore method delegation ---------------------------------- + pub fn reserve_blocks(&mut self) { + self.inner.reserve_blocks(); + } + + pub fn resize(&mut self, total_num_groups: usize, default_value: T) { + self.inner.resize(total_num_groups, default_value); + } + + pub fn num_blocks(&self) -> usize { + self.inner.num_blocks() + } + + pub fn block_size(&self) -> Option { + self.inner.block_size() + } + + pub fn clear(&mut self) { + self.inner.clear(); + } + + // ---- Emit ---------------------------------------------------------- + + /// Emit values according to `emit_to`, expressed only in terms of + /// [`BlockStore::push_block`] and [`BlockStore::pop_block`]. + /// + /// - [`EmitTo::All`]: drains every block via repeated `pop_block` and + /// concatenates the results into a single `Vec`. + /// - [`EmitTo::First`]`(n)`: pops the first block, splits off the first + /// `n` values, and pushes the remainder back. Only meaningful when the + /// first block holds at least `n` values (true for flat storage); the + /// call returns an internal error otherwise. + /// - [`EmitTo::NextBlock`]: pops a single block. + pub fn emit(&mut self, emit_to: EmitTo) -> Result> { + match emit_to { + EmitTo::All => self.inner.pop_block().ok_or_else(|| { + internal_datafusion_err!("cannot emit all: block store is empty") + }), + EmitTo::First(n) => { + let mut first = self.inner.pop_block().ok_or_else(|| { + internal_datafusion_err!( + "cannot emit first {n}: block store is empty" + ) + })?; + if n > first.len() { + return internal_err!( + "EmitTo::First({}) exceeds the first block length {}", + n, + first.len() + ); + } + let first_n = split_vec_min_alloc(&mut first, n); + self.inner.push_block(first); + Ok(first_n) + } + EmitTo::NextBlock => self + .inner + .pop_block() + .ok_or_else(|| internal_datafusion_err!("no more blocks to emit")), + } + } +} + +impl Index for VecBlockStore +where + T: Clone + Debug, + S: BlockStore>, +{ + type Output = Vec; + + #[inline] + fn index(&self, index: usize) -> &Self::Output { + &self.inner[index] + } +} + +impl IndexMut for VecBlockStore +where + T: Clone + Debug, + S: BlockStore>, +{ + #[inline] + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.inner[index] + } +} + +/// Most aggregation intermediate results are naturally represented as `Vec`, +/// so we provide a blanket [`Block`] implementation for it. Specialized layouts +/// (e.g. compact representations for non-trivially-sized values) should define +/// their own block type rather than wrap `Vec`. +impl Block for Vec { + type T = T; + + fn new(capacity: usize) -> Self { + Vec::with_capacity(capacity) + } + + fn fill_default_value(&mut self, fill_len: usize, default_value: Self::T) { + self.extend(iter::repeat_n(default_value, fill_len)); + } + + fn len(&self) -> usize { + Vec::len(self) + } +} + +#[cfg(test)] +mod tests { + use datafusion_expr_common::groups_accumulator::EmitTo; + + use crate::aggregate::groups_accumulator::block_store::{ + BlockStore, BlockedBlockStore, FlatBlockStore, VecBlockStore, + }; + + type FlatTestStore = VecBlockStore>>; + type BlockedTestStore = VecBlockStore>>; + + fn flat_store(values: Vec) -> FlatTestStore { + let mut store = FlatTestStore::new(FlatBlockStore::new()); + store.resize(values.len(), 0); + store[0].clone_from(&values); + store + } + + fn blocked_store(block_size: usize, blocks: &[&[u32]]) -> BlockedTestStore { + let mut inner = BlockedBlockStore::new(block_size); + for block in blocks { + inner.push_block(block.to_vec()); + } + VecBlockStore::new(inner) + } + + // Covers EmitTo::All returning the flat store's single backing block. + // Example: flat block [1, 2, 3] emits [1, 2, 3] and leaves the store empty. + #[test] + fn test_emit_all_returns_flat_block_values() { + let mut store = flat_store(vec![1, 2, 3]); + + assert_eq!(store.emit(EmitTo::All).unwrap(), vec![1, 2, 3]); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + } + + // Covers EmitTo::All returning the next blocked store block. + // Example: blocks [1, 2] and [3] emit [1, 2], leaving one block active. + #[test] + fn test_emit_all_returns_next_blocked_block() { + let mut store = blocked_store(2, &[&[1, 2], &[3]]); + + assert_eq!(store.emit(EmitTo::All).unwrap(), vec![1, 2]); + assert_eq!(store.num_blocks(), 1); + } + + // Covers EmitTo::All returning an error when blocked storage has no blocks. + // Example: emitting all from a new blocked store returns "cannot emit all". + #[test] + fn test_emit_all_returns_error_when_blocked_store_has_no_blocks() { + let mut store = BlockedTestStore::new(BlockedBlockStore::new(2)); + + let error = store.emit(EmitTo::All).unwrap_err().to_string(); + assert!(error.contains("cannot emit all: block store is empty")); + } + + // Covers EmitTo::First splitting a flat block and preserving the remainder. + // Example: first 2 from [1, 2, 3, 4] emits [1, 2], then all emits [3, 4]. + #[test] + fn test_emit_first_splits_flat_block_and_keeps_remainder() { + let mut store = flat_store(vec![1, 2, 3, 4]); + + assert_eq!(store.emit(EmitTo::First(2)).unwrap(), vec![1, 2]); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.emit(EmitTo::All).unwrap(), vec![3, 4]); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + } + + // Covers EmitTo::First(0) pushing the entire flat block back as the remainder. + // Example: first 0 from [1, 2] emits [], then all emits [1, 2]. + #[test] + fn test_emit_first_keeps_all_values_when_count_is_zero() { + let mut store = flat_store(vec![1, 2]); + + assert_eq!(store.emit(EmitTo::First(0)).unwrap(), Vec::::new()); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.emit(EmitTo::All).unwrap(), vec![1, 2]); + } + + // Covers EmitTo::First returning an error when the requested count is too large. + // Example: first 3 from [1, 2] errors because the first block length is 2. + #[test] + fn test_emit_first_returns_error_when_count_exceeds_first_block_len() { + let mut store = flat_store(vec![1, 2]); + + let error = store.emit(EmitTo::First(3)).unwrap_err().to_string(); + assert!(error.contains("EmitTo::First(3) exceeds the first block length 2")); + } + + // Covers EmitTo::First returning an error when blocked storage has no blocks. + // Example: first 1 from a new blocked store returns "cannot emit first 1". + #[test] + fn test_emit_first_returns_error_when_blocked_store_has_no_blocks() { + let mut store = BlockedTestStore::new(BlockedBlockStore::new(2)); + + let error = store.emit(EmitTo::First(1)).unwrap_err().to_string(); + assert!(error.contains("cannot emit first 1: block store is empty")); + } + + // Covers EmitTo::NextBlock draining blocked storage one block at a time. + // Example: blocks [1, 2] and [3, 4] emit [1, 2], then [3, 4], then error. + #[test] + fn test_emit_next_block_drains_blocked_blocks_in_order() { + let mut store = blocked_store(2, &[&[1, 2], &[3, 4]]); + + assert_eq!(store.emit(EmitTo::NextBlock).unwrap(), vec![1, 2]); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.emit(EmitTo::NextBlock).unwrap(), vec![3, 4]); + assert_eq!(store.num_blocks(), 0); + let error = store.emit(EmitTo::NextBlock).unwrap_err().to_string(); + assert!(error.contains("no more blocks to emit")); + } + + // Covers EmitTo::NextBlock returning the current single flat block. + // Example: flat block [9] emits [9], then the next block request emits []. + #[test] + fn test_emit_next_block_returns_current_flat_block() { + let mut store = flat_store(vec![9]); + + assert_eq!(store.emit(EmitTo::NextBlock).unwrap(), vec![9]); + assert_ne!(store.num_blocks(), 0); + assert_eq!(store.num_blocks(), 1); + assert_eq!(store.emit(EmitTo::NextBlock).unwrap(), Vec::::new()); + } +} diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/bool_op.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/bool_op.rs index afb1dec24a484..a6484df24667d 100644 --- a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/bool_op.rs +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/bool_op.rs @@ -20,10 +20,10 @@ use std::sync::Arc; use crate::aggregate::groups_accumulator::nulls::filtered_null_mask; use arrow::array::{ArrayRef, AsArray, BooleanArray, BooleanBufferBuilder}; use arrow::buffer::BooleanBuffer; -use datafusion_common::Result; +use datafusion_common::{Result, internal_err}; use datafusion_expr_common::groups_accumulator::{EmitTo, GroupsAccumulator}; -use super::accumulate::NullState; +use super::accumulate::FlatNullState; /// An accumulator that implements a single operation over a /// [`BooleanArray`] where the accumulated state is also boolean (such @@ -43,7 +43,7 @@ where values: BooleanBufferBuilder, /// Track nulls in the input / filters - null_state: NullState, + null_state: FlatNullState, /// Function that computes the output bool_fn: F, @@ -60,7 +60,7 @@ where pub fn new(bool_fn: F, identity: bool) -> Self { Self { values: BooleanBufferBuilder::new(0), - null_state: NullState::new(), + null_state: FlatNullState::new(), bool_fn, identity, } @@ -94,7 +94,8 @@ where values, opt_filter, total_num_groups, - |group_index, new_value| { + |_, group_index, new_value| { + let group_index = group_index as usize; let current_value = self.values.get_bit(group_index); let value = (self.bool_fn)(current_value, new_value); self.values.set_bit(group_index, value); @@ -117,6 +118,9 @@ where } first_n } + EmitTo::NextBlock => { + return internal_err!("boolean_op does not support blocked groups"); + } }; let nulls = self.null_state.build(emit_to); diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/group_index_operations.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/group_index_operations.rs new file mode 100644 index 0000000000000..a62b21fa1be14 --- /dev/null +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/group_index_operations.rs @@ -0,0 +1,91 @@ +// 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. + +//! Useful tools for operating group index + +use std::fmt::Debug; + +/// Operations about group index parsing +/// +/// There are mainly 2 `group index` needing parsing: `flat` and `blocked`. +/// +/// # Flat group index +/// `flat group index` format is like: +/// +/// ```text +/// | block_offset(64bit) | +/// ``` +/// +/// It is used in `flat GroupValues/GroupAccumulator`, only a single block +/// exists, so its `block_id` is always 0, and use all 64 bits to store the +/// `block offset`. +/// +/// # Blocked group index +/// `blocked group index` format is like: +/// +/// ```text +/// | block_id(32bit) | block_offset(32bit) +/// ``` +/// +/// It is used in `blocked GroupValues/GroupAccumulator`, multiple blocks +/// exist, and we use high 32 bits to store `block_id`, and low 32 bit to +/// store `block_offset`. +/// +/// The `get_block_offset` method requires to return `block_offset` as u64, +/// that is for compatible for `flat group index`'s parsing. +/// +pub trait GroupIndexOperations: Debug { + fn pack_index(block_id: u32, block_offset: u64) -> u64; + + fn get_block_id(packed_index: u64) -> u32; + + fn get_block_offset(packed_index: u64) -> u64; +} + +#[derive(Debug)] +pub struct BlockedGroupIndexOperations; + +impl GroupIndexOperations for BlockedGroupIndexOperations { + fn pack_index(block_id: u32, block_offset: u64) -> u64 { + ((block_id as u64) << 32) | block_offset + } + + fn get_block_id(packed_index: u64) -> u32 { + (packed_index >> 32) as u32 + } + + fn get_block_offset(packed_index: u64) -> u64 { + (packed_index as u32) as u64 + } +} + +#[derive(Debug)] +pub struct FlatGroupIndexOperations; + +impl GroupIndexOperations for FlatGroupIndexOperations { + fn pack_index(_block_id: u32, block_offset: u64) -> u64 { + block_offset + } + + fn get_block_id(_packed_index: u64) -> u32 { + 0 + } + + fn get_block_offset(packed_index: u64) -> u64 { + packed_index + } +} diff --git a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/prim_op.rs b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/prim_op.rs index 474899d8f3c6a..193967feb5573 100644 --- a/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/prim_op.rs +++ b/datafusion/functions-aggregate-common/src/aggregate/groups_accumulator/prim_op.rs @@ -15,7 +15,8 @@ // specific language governing permissions and limitations // under the License. -use std::mem::size_of; +use std::fmt::Debug; +use std::marker::PhantomData; use std::sync::Arc; use arrow::array::{ArrayRef, AsArray, BooleanArray, PrimitiveArray}; @@ -23,10 +24,20 @@ use arrow::buffer::NullBuffer; use arrow::compute; use arrow::datatypes::ArrowPrimitiveType; use arrow::datatypes::DataType; -use datafusion_common::{DataFusionError, Result, internal_datafusion_err}; +use datafusion_common::{ + DataFusionError, Result, internal_datafusion_err, utils::proxy::VecAllocExt, +}; use datafusion_expr_common::groups_accumulator::{EmitTo, GroupsAccumulator}; -use super::accumulate::NullState; +use crate::aggregate::groups_accumulator::accumulate::{ + BlockedNullState, BooleanBlock, FlatNullState, NullState, +}; +use crate::aggregate::groups_accumulator::block_store::{ + BlockStore, BlockedBlockStore, FlatBlockStore, VecBlockStore, +}; +use crate::aggregate::groups_accumulator::group_index_operations::{ + BlockedGroupIndexOperations, FlatGroupIndexOperations, GroupIndexOperations, +}; /// An accumulator that implements a single operation over /// [`ArrowPrimitiveType`] where the accumulated state is the same as @@ -41,10 +52,11 @@ use super::accumulate::NullState; pub struct PrimitiveGroupsAccumulator where T: ArrowPrimitiveType + Send, + T::Native: Debug + Send, F: Fn(&mut T::Native, T::Native) + Send + Sync + 'static, { - /// values per group, stored as the native type - values: Vec, + /// Values and null state per group, stored according to the current group mode. + state: PrimitiveGroupsStateAdapter, /// The output type (needed for Decimal precision and scale) data_type: DataType, @@ -52,9 +64,6 @@ where /// The starting value for new groups starting_value: T::Native, - /// Track nulls in the input / filters - null_state: NullState, - /// Function that computes the primitive result prim_fn: F, } @@ -62,13 +71,13 @@ where impl PrimitiveGroupsAccumulator where T: ArrowPrimitiveType + Send, + T::Native: Debug + Send, F: Fn(&mut T::Native, T::Native) + Send + Sync + 'static, { pub fn new(data_type: &DataType, prim_fn: F) -> Self { Self { - values: vec![], + state: PrimitiveGroupsStateAdapter::new(None), data_type: data_type.clone(), - null_state: NullState::new(), starting_value: T::default_value(), prim_fn, } @@ -81,9 +90,154 @@ where } } +#[derive(Clone, Copy)] +struct UpdateBatchInput<'a, T: ArrowPrimitiveType> { + values: &'a PrimitiveArray, + group_indices: &'a [usize], + opt_filter: Option<&'a BooleanArray>, + total_num_groups: usize, +} + +#[derive(Debug)] +struct PrimitiveGroupsState +where + V: Clone + Debug + Send, + VB: BlockStore> + Send, + O: GroupIndexOperations, + S: BlockStore + Send, +{ + values: VecBlockStore, + null_state: NullState, + _phantom: PhantomData, +} + +impl PrimitiveGroupsState +where + V: Clone + Debug + Send, + VB: BlockStore> + Send, + O: GroupIndexOperations, + S: BlockStore + Send, +{ + fn new(values: VecBlockStore, null_state: NullState) -> Self { + Self { + values, + null_state, + _phantom: PhantomData, + } + } + + fn update_batch( + &mut self, + input: &UpdateBatchInput<'_, T>, + starting_value: V, + prim_fn: &F, + ) where + T: ArrowPrimitiveType + Send, + F: Fn(&mut V, V) + Send + Sync + 'static, + { + // Expand to ensure values are large enough + self.values.resize(input.total_num_groups, starting_value); + + self.null_state.accumulate( + input.group_indices, + input.values, + input.opt_filter, + input.total_num_groups, + |block_id, block_offset, new_value| { + // SAFETY: `block_id` and `block_offset` are guaranteed to be in bounds + let value = unsafe { + self.values[block_id as usize] + .get_unchecked_mut(block_offset as usize) + }; + prim_fn(value, new_value); + }, + ); + } + + fn evaluate(&mut self, emit_to: EmitTo) -> Result<(Vec, Option)> { + Ok((self.values.emit(emit_to)?, self.null_state.build(emit_to))) + } + + fn size(&self) -> usize { + let num_blocks = self.values.num_blocks(); + if num_blocks == 0 { + return self.null_state.size(); + } + + ((num_blocks - 1) * self.values[0].allocated_size()) + + self.values[num_blocks - 1].allocated_size() + + self.null_state.size() + } +} + +type FlatPrimitiveGroupsState = PrimitiveGroupsState< + V, + FlatBlockStore>, + FlatGroupIndexOperations, + FlatBlockStore, +>; + +type BlockedPrimitiveGroupsState = PrimitiveGroupsState< + V, + BlockedBlockStore>, + BlockedGroupIndexOperations, + BlockedBlockStore, +>; + +#[derive(Debug)] +enum PrimitiveGroupsStateAdapter { + Flat(FlatPrimitiveGroupsState), + Blocked(BlockedPrimitiveGroupsState), +} + +impl PrimitiveGroupsStateAdapter { + fn new(block_size: Option) -> Self { + match block_size { + Some(block_size) => Self::Blocked(PrimitiveGroupsState::new( + VecBlockStore::new(BlockedBlockStore::new(block_size)), + BlockedNullState::new(block_size), + )), + None => Self::Flat(PrimitiveGroupsState::new( + VecBlockStore::new(FlatBlockStore::new()), + FlatNullState::new(), + )), + } + } + + fn update_batch( + &mut self, + input: &UpdateBatchInput<'_, T>, + starting_value: V, + prim_fn: &F, + ) where + T: ArrowPrimitiveType + Send, + F: Fn(&mut V, V) + Send + Sync + 'static, + { + match self { + Self::Flat(state) => state.update_batch(input, starting_value, prim_fn), + Self::Blocked(state) => state.update_batch(input, starting_value, prim_fn), + } + } + + fn evaluate(&mut self, emit_to: EmitTo) -> Result<(Vec, Option)> { + match self { + Self::Flat(state) => state.evaluate(emit_to), + Self::Blocked(state) => state.evaluate(emit_to), + } + } + + fn size(&self) -> usize { + match self { + Self::Flat(state) => state.size(), + Self::Blocked(state) => state.size(), + } + } +} + impl GroupsAccumulator for PrimitiveGroupsAccumulator where T: ArrowPrimitiveType + Send, + T::Native: Debug + Send, F: Fn(&mut T::Native, T::Native) + Send + Sync + 'static, { fn update_batch( @@ -94,30 +248,23 @@ where total_num_groups: usize, ) -> Result<()> { assert_eq!(values.len(), 1, "single argument to update_batch"); - let values = values[0].as_primitive::(); - - // update values - self.values.resize(total_num_groups, self.starting_value); - - // NullState dispatches / handles tracking nulls and groups that saw no values - self.null_state.accumulate( - group_indices, - values, - opt_filter, - total_num_groups, - |group_index, new_value| { - // SAFETY: group_index is guaranteed to be in bounds - let value = unsafe { self.values.get_unchecked_mut(group_index) }; - (self.prim_fn)(value, new_value); + let input_values = values[0].as_primitive::(); + self.state.update_batch( + &UpdateBatchInput { + values: input_values, + group_indices, + opt_filter, + total_num_groups, }, + self.starting_value, + &self.prim_fn, ); Ok(()) } fn evaluate(&mut self, emit_to: EmitTo) -> Result { - let values = emit_to.take_needed(&mut self.values); - let nulls = self.null_state.build(emit_to); + let (values, nulls) = self.state.evaluate(emit_to)?; let values = PrimitiveArray::::new(values.into(), nulls) // no copy .with_data_type(self.data_type.clone()); Ok(Arc::new(values)) @@ -195,6 +342,16 @@ where } fn size(&self) -> usize { - self.values.capacity() * size_of::() + self.null_state.size() + self.state.size() + } + + fn supports_blocked_groups(&self) -> bool { + true + } + + fn alter_block_size(&mut self, block_size: Option) -> Result<()> { + self.state = PrimitiveGroupsStateAdapter::new(block_size); + + Ok(()) } } diff --git a/datafusion/functions-aggregate/src/array_agg.rs b/datafusion/functions-aggregate/src/array_agg.rs index 1dd111f9182c9..b3d14c4760937 100644 --- a/datafusion/functions-aggregate/src/array_agg.rs +++ b/datafusion/functions-aggregate/src/array_agg.rs @@ -656,6 +656,9 @@ impl GroupsAccumulator for ArrayAggGroupsAccumulator { let emit_groups = match emit_to { EmitTo::All => self.num_groups, EmitTo::First(n) => n, + EmitTo::NextBlock => { + return internal_err!("array_agg does not support blocked groups"); + } }; // Step 1: Count entries per group. For EmitTo::First(n), only groups @@ -715,6 +718,9 @@ impl GroupsAccumulator for ArrayAggGroupsAccumulator { match emit_to { EmitTo::All => self.clear_state(), EmitTo::First(_) => self.compact_retained_state(emit_groups)?, + EmitTo::NextBlock => { + return internal_err!("array_agg does not support blocked groups"); + } } let offsets = OffsetBuffer::new(ScalarBuffer::from(offsets)); diff --git a/datafusion/functions-aggregate/src/average.rs b/datafusion/functions-aggregate/src/average.rs index 06c76946343dc..e11b8bb94bc44 100644 --- a/datafusion/functions-aggregate/src/average.rs +++ b/datafusion/functions-aggregate/src/average.rs @@ -43,7 +43,8 @@ use datafusion_expr::{ use datafusion_functions_aggregate_common::aggregate::avg_distinct::{ DecimalDistinctAvgAccumulator, Float64DistinctAvgAccumulator, }; -use datafusion_functions_aggregate_common::aggregate::groups_accumulator::accumulate::NullState; + +use datafusion_functions_aggregate_common::aggregate::groups_accumulator::accumulate::FlatNullState; use datafusion_functions_aggregate_common::aggregate::groups_accumulator::nulls::{ filtered_null_mask, set_nulls, }; @@ -784,7 +785,7 @@ where sums: Vec, /// Track nulls in the input / filters - null_state: NullState, + null_state: FlatNullState, /// Function that computes the final average (value / count) avg_fn: F, @@ -806,7 +807,7 @@ where sum_data_type: sum_data_type.clone(), counts: vec![], sums: vec![], - null_state: NullState::new(), + null_state: FlatNullState::new(), avg_fn, } } @@ -830,12 +831,17 @@ where // increment counts, update sums self.counts.resize(total_num_groups, 0); self.sums.resize(total_num_groups, T::default_value()); + + // `block_id` is ignored in `value_fn`, because `AvgGroupsAccumulator` + // still not support blocked groups. + // More details can see `GroupsAccumulator::supports_blocked_groups`. self.null_state.accumulate( group_indices, values, opt_filter, total_num_groups, - |group_index, new_value| { + |_, group_index, new_value| { + let group_index = group_index as usize; // SAFETY: group_index is guaranteed to be in bounds let sum = unsafe { self.sums.get_unchecked_mut(group_index) }; *sum = sum.add_wrapping(new_value); @@ -916,28 +922,36 @@ where let partial_sums = values[1].as_primitive::(); // update counts with partial counts self.counts.resize(total_num_groups, 0); + + // `block_id` is ignored in `value_fn`, because `AvgGroupsAccumulator` + // still not support blocked groups. + // More details can see `GroupsAccumulator::supports_blocked_groups`. self.null_state.accumulate( group_indices, partial_counts, None, total_num_groups, - |group_index, partial_count| { + |_, group_index, partial_count| { // SAFETY: group_index is guaranteed to be in bounds - let count = unsafe { self.counts.get_unchecked_mut(group_index) }; + let count = + unsafe { self.counts.get_unchecked_mut(group_index as usize) }; *count += partial_count; }, ); // update sums self.sums.resize(total_num_groups, T::default_value()); + // `block_id` is ignored in `value_fn`, because `AvgGroupsAccumulator` + // still not support blocked groups. + // More details can see `GroupsAccumulator::supports_blocked_groups`. self.null_state.accumulate( group_indices, partial_sums, None, total_num_groups, - |group_index, new_value: ::Native| { + |_, group_index, new_value: ::Native| { // SAFETY: group_index is guaranteed to be in bounds - let sum = unsafe { self.sums.get_unchecked_mut(group_index) }; + let sum = unsafe { self.sums.get_unchecked_mut(group_index as usize) }; *sum = sum.add_wrapping(new_value); }, ); diff --git a/datafusion/functions-aggregate/src/first_last.rs b/datafusion/functions-aggregate/src/first_last.rs index cecb277cb844a..3b02d2cacd38d 100644 --- a/datafusion/functions-aggregate/src/first_last.rs +++ b/datafusion/functions-aggregate/src/first_last.rs @@ -437,18 +437,21 @@ impl FirstLastGroupsAccumulator { }) } - fn take_orderings(&mut self, emit_to: EmitTo) -> Vec> { + fn take_orderings(&mut self, emit_to: EmitTo) -> Result>> { let result = emit_to.take_needed(&mut self.orderings); match emit_to { EmitTo::All => self.size_of_orderings = 0, EmitTo::First(_) => { self.size_of_orderings -= - result.iter().map(ScalarValue::size_of_vec).sum::() + result.iter().map(ScalarValue::size_of_vec).sum::(); + } + EmitTo::NextBlock => { + return internal_err!("first_last does not support blocked groups"); } } - result + Ok(result) } fn resize_states(&mut self, new_size: usize) { @@ -505,7 +508,7 @@ impl FirstLastGroupsAccumulator { Ok(( self.state.take(emit_to)?, - self.take_orderings(emit_to), + self.take_orderings(emit_to)?, state::take_need(&mut self.is_sets, emit_to), )) } diff --git a/datafusion/functions-aggregate/src/first_last/state.rs b/datafusion/functions-aggregate/src/first_last/state.rs index cd7114bf04f9c..7deb7ea6eed89 100644 --- a/datafusion/functions-aggregate/src/first_last/state.rs +++ b/datafusion/functions-aggregate/src/first_last/state.rs @@ -305,6 +305,9 @@ pub(crate) fn take_need( bool_buf_builder.append_buffer(&bool_buf.slice(n, bool_buf.len() - n)); first_n } + EmitTo::NextBlock => { + unreachable!("first_last does not support blocked groups") + } } } diff --git a/datafusion/functions-aggregate/src/min_max/min_max_bytes.rs b/datafusion/functions-aggregate/src/min_max/min_max_bytes.rs index 7a3c605d82e4d..5cd348ab953e3 100644 --- a/datafusion/functions-aggregate/src/min_max/min_max_bytes.rs +++ b/datafusion/functions-aggregate/src/min_max/min_max_bytes.rs @@ -202,7 +202,7 @@ impl GroupsAccumulator for MinMaxBytesAccumulator { } fn evaluate(&mut self, emit_to: EmitTo) -> Result { - let (data_capacity, min_maxes) = self.inner.emit_to(emit_to); + let (data_capacity, min_maxes) = self.inner.emit_to(emit_to)?; // Convert the Vec of bytes to a vec of Strings (at no cost) fn bytes_to_str( @@ -485,13 +485,13 @@ impl MinMaxBytesState { /// /// - `data_capacity`: the total length of all strings and their contents, /// - `min_maxes`: the actual min/max values for each group - fn emit_to(&mut self, emit_to: EmitTo) -> (usize, Vec>>) { + fn emit_to(&mut self, emit_to: EmitTo) -> Result<(usize, Vec>>)> { match emit_to { EmitTo::All => { - ( + Ok(( std::mem::take(&mut self.total_data_bytes), // reset total bytes and min_max std::mem::take(&mut self.min_max), - ) + )) } EmitTo::First(n) => { let first_min_maxes = split_vec_min_alloc(&mut self.min_max, n); @@ -500,7 +500,10 @@ impl MinMaxBytesState { .map(|opt| opt.as_ref().map(|s| s.len()).unwrap_or(0)) .sum(); self.total_data_bytes -= first_data_capacity; - (first_data_capacity, first_min_maxes) + Ok((first_data_capacity, first_min_maxes)) + } + EmitTo::NextBlock => { + internal_err!("min/max bytes does not support blocked groups") } } } diff --git a/datafusion/functions-aggregate/src/min_max/min_max_struct.rs b/datafusion/functions-aggregate/src/min_max/min_max_struct.rs index 10580ac18d3ec..80f081a27c100 100644 --- a/datafusion/functions-aggregate/src/min_max/min_max_struct.rs +++ b/datafusion/functions-aggregate/src/min_max/min_max_struct.rs @@ -101,7 +101,7 @@ impl GroupsAccumulator for MinMaxStructAccumulator { } fn evaluate(&mut self, emit_to: EmitTo) -> Result { - let (_, min_maxes) = self.inner.emit_to(emit_to); + let (_, min_maxes) = self.inner.emit_to(emit_to)?; let fields = match &self.inner.data_type { DataType::Struct(fields) => fields, _ => return internal_err!("Data type is not a struct"), @@ -274,13 +274,13 @@ impl MinMaxStructState { /// /// - `data_capacity`: the total length of all strings and their contents, /// - `min_maxes`: the actual min/max values for each group - fn emit_to(&mut self, emit_to: EmitTo) -> (usize, Vec>) { + fn emit_to(&mut self, emit_to: EmitTo) -> Result<(usize, Vec>)> { match emit_to { EmitTo::All => { - ( + Ok(( std::mem::take(&mut self.total_data_bytes), // reset total bytes and min_max std::mem::take(&mut self.min_max), - ) + )) } EmitTo::First(n) => { let first_min_maxes = split_vec_min_alloc(&mut self.min_max, n); @@ -289,7 +289,10 @@ impl MinMaxStructState { .map(|opt| opt.as_ref().map(|s| s.len()).unwrap_or(0)) .sum(); self.total_data_bytes -= first_data_capacity; - (first_data_capacity, first_min_maxes) + Ok((first_data_capacity, first_min_maxes)) + } + EmitTo::NextBlock => { + internal_err!("min/max struct does not support blocked groups") } } } diff --git a/datafusion/physical-expr/src/aggregate.rs b/datafusion/physical-expr/src/aggregate.rs index e5d55aba4f51c..d612d094fbdfb 100644 --- a/datafusion/physical-expr/src/aggregate.rs +++ b/datafusion/physical-expr/src/aggregate.rs @@ -18,10 +18,10 @@ pub(crate) mod groups_accumulator { #[expect(unused_imports)] pub(crate) mod accumulate { - pub use datafusion_functions_aggregate_common::aggregate::groups_accumulator::accumulate::NullState; + pub use datafusion_functions_aggregate_common::aggregate::groups_accumulator::accumulate::FlatNullState; } pub use datafusion_functions_aggregate_common::aggregate::groups_accumulator::{ - GroupsAccumulatorAdapter, accumulate::NullState, + GroupsAccumulatorAdapter, accumulate::FlatNullState, block_store::FlatBlockStore, }; } pub(crate) mod stats { diff --git a/datafusion/physical-expr/src/lib.rs b/datafusion/physical-expr/src/lib.rs index b55bd70bdf185..47685be59664e 100644 --- a/datafusion/physical-expr/src/lib.rs +++ b/datafusion/physical-expr/src/lib.rs @@ -56,7 +56,9 @@ pub mod execution_props { pub use datafusion_expr::var_provider::{VarProvider, VarType}; } -pub use aggregate::groups_accumulator::{GroupsAccumulatorAdapter, NullState}; +pub use aggregate::groups_accumulator::{ + FlatBlockStore, FlatNullState, GroupsAccumulatorAdapter, +}; pub use analysis::{AnalysisContext, ExprBoundaries, analyze}; pub use datafusion_common::SplitPoint; pub use equivalence::{ diff --git a/datafusion/physical-plan/src/aggregates/group_values/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/mod.rs index ee253e5d7afdd..c748dca56632d 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/mod.rs @@ -24,7 +24,7 @@ use arrow::array::types::{ }; use arrow::array::{ArrayRef, downcast_primitive}; use arrow::datatypes::{DataType, SchemaRef, TimeUnit}; -use datafusion_common::Result; +use datafusion_common::{DataFusionError, Result}; use datafusion_expr::EmitTo; @@ -113,6 +113,51 @@ pub trait GroupValues: Send { /// Clear the contents and shrink the capacity to the size of the batch (free up memory usage) fn clear_shrink(&mut self, num_rows: usize); + + /// Returns `true` if this accumulator supports blocked groups. + /// + /// Blocked groups(or called blocked management approach) is an optimization + /// to reduce the cost of managing aggregation intermediate states. + /// + /// Here is brief introduction for two states management approaches: + /// - Blocked approach, states are stored and managed in multiple `Vec`s, + /// we call it `Block`s. Organize like this is for avoiding to resize `Vec` + /// and allocate a new `Vec` instead to reduce cost and get better performance. + /// When locating data in `Block`s, we need to use `block_id` to locate the + /// needed `Block` at first, and use `block_offset` to locate the needed + /// data in `Block` after. + /// + /// - Single approach, all states are stored and managed in a single large `Block`. + /// So when locating data, `block_id` will always be 0, and we only need `block_offset` + /// to locate data in the single `Block`. + /// + /// More details can see: + /// + /// + fn supports_blocked_groups(&self) -> bool { + false + } + + /// Alter the block size in the `group values` + /// + /// If the target block size is `None`, it will use a single big + /// block(can think it a `Vec`) to manage the state. + /// + /// If the target block size` is `Some(blk_size)`, it will try to + /// set the block size to `blk_size`, and the try will only success + /// when the `group values` has supported blocked mode. + /// + /// NOTICE: After altering block size, all data in previous will be cleared. + /// + fn alter_block_size(&mut self, block_size: Option) -> Result<()> { + if block_size.is_some() { + return Err(DataFusionError::NotImplemented( + "this group values doesn't support blocked mode yet".to_string(), + )); + } + + Ok(()) + } } /// Return a specialized implementation of [`GroupValues`] for the given schema. diff --git a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs index f275d777c3279..9293920670460 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs @@ -41,7 +41,7 @@ use arrow::datatypes::{ }; use datafusion_common::hash_utils::RandomState; use datafusion_common::hash_utils::create_hashes; -use datafusion_common::{Result, internal_datafusion_err, not_impl_err}; +use datafusion_common::{Result, internal_datafusion_err, internal_err, not_impl_err}; use datafusion_execution::memory_pool::proxy::{HashTableAllocExt, VecAllocExt}; use datafusion_expr::EmitTo; use datafusion_physical_expr::binary_map::OutputType; @@ -1195,6 +1195,11 @@ impl GroupValues for GroupValuesColumn { output } + EmitTo::NextBlock => { + return internal_err!( + "group_values_column does not support blocked groups" + ); + } }; // TODO: Materialize dictionaries in group keys (#7647) diff --git a/datafusion/physical-plan/src/aggregates/group_values/row.rs b/datafusion/physical-plan/src/aggregates/group_values/row.rs index 4976a098ecee5..a237514e351cc 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/row.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/row.rs @@ -23,10 +23,10 @@ use arrow::array::{ use arrow::compute::cast; use arrow::datatypes::{DataType, SchemaRef}; use arrow::row::{RowConverter, Rows, SortField}; -use datafusion_common::Result; use datafusion_common::hash_utils::RandomState; use datafusion_common::hash_utils::create_hashes; use datafusion_common::utils::normalize_float_zero; +use datafusion_common::{Result, internal_err}; use datafusion_execution::memory_pool::proxy::{HashTableAllocExt, VecAllocExt}; use datafusion_expr::EmitTo; use hashbrown::hash_table::HashTable; @@ -241,6 +241,11 @@ impl GroupValues for GroupValuesRows { }); output } + EmitTo::NextBlock => { + return internal_err!( + "group_values_rows does not support blocked groups" + ); + } }; // TODO: Materialize dictionaries in group keys diff --git a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/boolean.rs b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/boolean.rs index e993c0c53d199..1a64d45ee99bf 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/boolean.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/boolean.rs @@ -20,7 +20,7 @@ use crate::aggregates::group_values::GroupValues; use arrow::array::{ ArrayRef, AsArray as _, BooleanArray, BooleanBufferBuilder, NullBufferBuilder, }; -use datafusion_common::Result; +use datafusion_common::{Result, internal_err}; use datafusion_expr::EmitTo; use std::{mem::size_of, sync::Arc}; @@ -103,6 +103,11 @@ impl GroupValues for GroupValuesBoolean { let emit_count = match emit_to { EmitTo::All => len, EmitTo::First(n) => n, + EmitTo::NextBlock => { + return internal_err!( + "group_values_boolean does not support blocked groups" + ); + } }; builder.append_n(emit_count, false); if let Some(idx) = self.true_group.as_mut() { diff --git a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes.rs b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes.rs index b881a51b25474..9aeccb3f38b67 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes.rs @@ -20,7 +20,7 @@ use std::mem::size_of; use crate::aggregates::group_values::GroupValues; use arrow::array::{Array, ArrayRef, OffsetSizeTrait}; -use datafusion_common::Result; +use datafusion_common::{Result, internal_err}; use datafusion_expr::EmitTo; use datafusion_physical_expr_common::binary_map::{ArrowBytesMap, OutputType}; @@ -115,6 +115,11 @@ impl GroupValues for GroupValuesBytes { emit_group_values } + EmitTo::NextBlock => { + return internal_err!( + "group_values_bytes does not support blocked groups" + ); + } }; Ok(vec![group_values]) diff --git a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes_view.rs b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes_view.rs index 7a56f7c52c11a..60cf2c4a578b6 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes_view.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/bytes_view.rs @@ -17,6 +17,7 @@ use crate::aggregates::group_values::GroupValues; use arrow::array::{Array, ArrayRef}; +use datafusion_common::internal_err; use datafusion_expr::EmitTo; use datafusion_physical_expr::binary_map::OutputType; use datafusion_physical_expr_common::binary_view_map::ArrowBytesViewMap; @@ -117,6 +118,11 @@ impl GroupValues for GroupValuesBytesView { emit_group_values } + EmitTo::NextBlock => { + return internal_err!( + "group_values_bytes_view does not support blocked groups" + ); + } }; Ok(vec![group_values]) diff --git a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/primitive.rs b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/primitive.rs index e254aebcfd7ce..3bd8dc4a4167a 100644 --- a/datafusion/physical-plan/src/aggregates/group_values/single_group_by/primitive.rs +++ b/datafusion/physical-plan/src/aggregates/group_values/single_group_by/primitive.rs @@ -24,13 +24,19 @@ use arrow::array::{ use arrow::datatypes::{DataType, i256}; use datafusion_common::Result; use datafusion_common::hash_utils::RandomState; -use datafusion_common::utils::split_vec_min_alloc; use datafusion_execution::memory_pool::proxy::VecAllocExt; use datafusion_expr::EmitTo; +use datafusion_functions_aggregate_common::aggregate::groups_accumulator::block_store::{ + BlockStore, BlockedBlockStore, FlatBlockStore, VecBlockStore, +}; +use datafusion_functions_aggregate_common::aggregate::groups_accumulator::group_index_operations::{ + BlockedGroupIndexOperations, FlatGroupIndexOperations, GroupIndexOperations, +}; use half::f16; use hashbrown::hash_table::HashTable; #[cfg(not(feature = "force_hash_collisions"))] use std::hash::BuildHasher; +use std::marker::PhantomData; use std::mem::size_of; use std::sync::Arc; @@ -109,11 +115,13 @@ pub struct GroupValuesPrimitive { /// is obvious in high cardinality group by situation. /// More details can see: /// - map: HashTable<(usize, u64)>, + map: HashTable<(u64, u64)>, /// The group index of the null value if any - null_group: Option, - /// The values for each group index - values: Vec, + null_group: Option, + + /// The values for each group index, stored according to the current group mode. + state: GroupValuesPrimitiveStateAdapter, + /// The random state used to generate hashes random_state: RandomState, } @@ -121,75 +129,121 @@ pub struct GroupValuesPrimitive { impl GroupValuesPrimitive { pub fn new(data_type: DataType) -> Self { assert!(PrimitiveArray::::is_compatible(&data_type)); + Self { data_type, map: HashTable::with_capacity(128), - values: Vec::with_capacity(128), + state: GroupValuesPrimitiveStateAdapter::new_flat(), null_group: None, random_state: crate::aggregates::AGGREGATION_HASH_SEED, } } } -impl GroupValues for GroupValuesPrimitive +#[derive(Debug)] +struct GroupValuesPrimitiveState where - T::Native: HashValue, + V: Clone + std::fmt::Debug, + VB: BlockStore> + Send, + O: GroupIndexOperations, { - fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec) -> Result<()> { + values: VecBlockStore, + _phantom: PhantomData<(V, O)>, +} + +impl GroupValuesPrimitiveState +where + V: Clone + std::fmt::Debug, + VB: BlockStore> + Send, + O: GroupIndexOperations, +{ + fn new(values: VB) -> Self { + Self { + values: VecBlockStore::new(values), + _phantom: PhantomData, + } + } + + fn intern( + &mut self, + map: &mut HashTable<(u64, u64)>, + null_group: &mut Option, + random_state: &RandomState, + cols: &[ArrayRef], + groups: &mut Vec, + ) -> Result<()> + where + T: ArrowPrimitiveType, + V: ArrowNativeTypeOp + Default + HashValue + Send, + { assert_eq!(cols.len(), 1); groups.clear(); for v in cols[0].as_primitive::() { - let group_id = match v { - None => *self.null_group.get_or_insert_with(|| { - let group_id = self.values.len(); - self.values.push(Default::default()); - group_id - }), + let packed_index = match v { + None => *null_group + .get_or_insert_with(|| self.push_new_group(Default::default())), Some(key) => { // Fold equivalence-class duplicates (e.g. `-0.0` → `+0.0`) // so the bit-equal `is_eq` matches and the stored value is // the canonical representative. let key = key.canonicalize(); - let state = &self.random_state; - let hash = key.hash(state); - let insert = self.map.entry( + let hash = key.hash(random_state); + let insert = map.entry( hash, - |&(g, h)| unsafe { - hash == h && self.values.get_unchecked(g).is_eq(key) + |&(idx, h)| unsafe { + if hash != h { + return false; + } + + let block_id = O::get_block_id(idx); + let block_offset = O::get_block_offset(idx); + self.values[block_id as usize] + .get_unchecked(block_offset as usize) + .is_eq(key) }, |&(_, h)| h, ); match insert { - hashbrown::hash_table::Entry::Occupied(o) => o.get().0, + hashbrown::hash_table::Entry::Occupied(o) => { + let (idx, _) = *o.get(); + idx + } hashbrown::hash_table::Entry::Vacant(v) => { - let g = self.values.len(); - v.insert((g, hash)); - self.values.push(key); - g + let packed_index = self.push_new_group(key); + v.insert((packed_index, hash)); + packed_index } } } }; - groups.push(group_id) + groups.push(packed_index as usize) } Ok(()) } - fn size(&self) -> usize { - self.map.capacity() * size_of::<(usize, u64)>() + self.values.allocated_size() - } + fn push_new_group(&mut self, value: V) -> u64 { + self.values.reserve_blocks(); - fn is_empty(&self) -> bool { - self.values.is_empty() + let block_id = self.values.num_blocks().saturating_sub(1); + let current_block = &mut self.values[block_id]; + let block_offset = current_block.len() as u64; + current_block.push(value); + O::pack_index(block_id as u32, block_offset) } - fn len(&self) -> usize { - self.values.len() - } - - fn emit(&mut self, emit_to: EmitTo) -> Result> { + fn emit( + &mut self, + map: &mut HashTable<(u64, u64)>, + null_group: &mut Option, + data_type: &DataType, + emit_to: EmitTo, + ) -> Result> + where + T: ArrowPrimitiveType, + V: Send, + { fn build_primitive( values: Vec, null_idx: Option, @@ -199,7 +253,6 @@ where buffer.append_n_non_nulls(null_idx); buffer.append_null(); buffer.append_n_non_nulls(values.len() - null_idx - 1); - // NOTE: The inner builder must be constructed as there is at least one null buffer.finish().unwrap() }); PrimitiveArray::::new(values.into(), nulls) @@ -207,55 +260,404 @@ where let array: PrimitiveArray = match emit_to { EmitTo::All => { - self.map.clear(); - build_primitive(std::mem::take(&mut self.values), self.null_group.take()) + map.clear(); + let values = self.values.emit(emit_to)?; + let null_group_opt = null_group.take().map(|packed_index| { + let blk_offset = O::get_block_offset(packed_index); + blk_offset as usize + }); + build_primitive(values, null_group_opt) } EmitTo::First(n) => { - self.map.retain(|entry| { - // Decrement group index by n - let group_idx = entry.0; - match group_idx.checked_sub(n) { - // Group index was >= n, shift value down + let n = n as u64; + map.retain(|entry| { + let packed_index = entry.0; + let blk_offset = O::get_block_offset(packed_index); + match blk_offset.checked_sub(n) { Some(sub) => { - entry.0 = sub; + let packed_index = O::pack_index(0, sub); + entry.0 = packed_index; true } - // Group index was < n, so remove from table None => false, } }); - let null_group = match &mut self.null_group { + + let null_group_opt = match null_group { Some(v) if *v >= n => { - *v -= n; + let mut blk_offset = O::get_block_offset(*v); + blk_offset -= n; + *v = O::pack_index(0, blk_offset); + None + } + Some(_) => null_group.take().map(|packed_index| { + let blk_offset = O::get_block_offset(packed_index); + blk_offset as usize + }), + None => None, + }; + + let split = self.values.emit(emit_to)?; + build_primitive(split, null_group_opt) + } + EmitTo::NextBlock => { + map.clear(); + + let null_block_pair_opt = null_group.map(|packed_index| { + ( + O::get_block_id(packed_index), + O::get_block_offset(packed_index), + ) + }); + let null_idx = match null_block_pair_opt { + Some((blk_id, blk_offset)) if blk_id > 0 => { + let new_blk_id = blk_id - 1; + let new_packed_index = O::pack_index(new_blk_id, blk_offset); + *null_group = Some(new_packed_index); None } - Some(_) => self.null_group.take(), + Some((_, blk_offset)) => { + *null_group = None; + Some(blk_offset as usize) + } None => None, }; - build_primitive(split_vec_min_alloc(&mut self.values, n), null_group) + + let emit_blk = self.values.emit(emit_to)?; + build_primitive(emit_blk, null_idx) } }; - Ok(vec![Arc::new(array.with_data_type(self.data_type.clone()))]) + Ok(vec![Arc::new(array.with_data_type(data_type.clone()))]) + } + + fn size(&self) -> usize { + let num_blocks = self.values.num_blocks(); + if num_blocks == 0 { + return 0; + } + (num_blocks - 1) * self.values[0].allocated_size() + + self.values[num_blocks - 1].allocated_size() + } + + fn len(&self) -> usize { + let num_blocks = self.values.num_blocks(); + if num_blocks == 0 { + return 0; + } + (num_blocks - 1) * self.values.block_size().unwrap_or(0) + + self.values[num_blocks - 1].len() + } +} + +type FlatGroupValuesPrimitiveState = + GroupValuesPrimitiveState>, FlatGroupIndexOperations>; +type BlockedGroupValuesPrimitiveState = + GroupValuesPrimitiveState>, BlockedGroupIndexOperations>; + +#[derive(Debug)] +enum GroupValuesPrimitiveStateAdapter { + Flat(FlatGroupValuesPrimitiveState), + Blocked(BlockedGroupValuesPrimitiveState), +} + +impl GroupValuesPrimitiveStateAdapter { + fn new_flat() -> Self { + Self::Flat(GroupValuesPrimitiveState::new(FlatBlockStore::new())) + } + + fn new_blocked(block_size: usize) -> Self { + Self::Blocked(GroupValuesPrimitiveState::new(BlockedBlockStore::new( + block_size, + ))) + } + + fn size(&self) -> usize { + match self { + Self::Flat(state) => state.size(), + Self::Blocked(state) => state.size(), + } + } + + fn len(&self) -> usize { + match self { + Self::Flat(state) => state.len(), + Self::Blocked(state) => state.len(), + } + } + + fn emit>( + &mut self, + map: &mut HashTable<(u64, u64)>, + null_group: &mut Option, + data_type: &DataType, + emit_to: EmitTo, + ) -> Result> + where + V: Send, + { + match self { + Self::Flat(state) => state.emit::(map, null_group, data_type, emit_to), + Self::Blocked(state) => state.emit::(map, null_group, data_type, emit_to), + } } fn clear_shrink(&mut self, num_rows: usize) { - self.values.clear(); - self.values.shrink_to(num_rows); + if let Self::Flat(state) = self { + let single_block = &mut state.values[0]; + single_block.clear(); + single_block.shrink_to(num_rows); + } + } +} + +impl GroupValues for GroupValuesPrimitive +where + T::Native: HashValue + Send + std::fmt::Debug, +{ + fn intern(&mut self, cols: &[ArrayRef], groups: &mut Vec) -> Result<()> { + match &mut self.state { + GroupValuesPrimitiveStateAdapter::Flat(state) => state.intern::( + &mut self.map, + &mut self.null_group, + &self.random_state, + cols, + groups, + ), + GroupValuesPrimitiveStateAdapter::Blocked(state) => state.intern::( + &mut self.map, + &mut self.null_group, + &self.random_state, + cols, + groups, + ), + } + } + + fn size(&self) -> usize { + self.map.capacity() * size_of::<(usize, u64)>() + self.state.size() + } + + fn is_empty(&self) -> bool { + self.len() == 0 + } + + fn len(&self) -> usize { + self.state.len() + } + + fn emit(&mut self, emit_to: EmitTo) -> Result> { + self.state.emit::( + &mut self.map, + &mut self.null_group, + &self.data_type, + emit_to, + ) + } + + fn clear_shrink(&mut self, num_rows: usize) { + self.state.clear_shrink(num_rows); self.map.clear(); - self.map.shrink_to(num_rows, |_| 0); // hasher does not matter since the map is cleared + self.map.shrink_to(num_rows, |_| 0); + } + + fn supports_blocked_groups(&self) -> bool { + true + } + + fn alter_block_size(&mut self, block_size: Option) -> Result<()> { + self.map.clear(); + self.null_group = None; + self.state = if let Some(block_size) = block_size { + GroupValuesPrimitiveStateAdapter::new_blocked(block_size) + } else { + GroupValuesPrimitiveStateAdapter::new_flat() + }; + + Ok(()) } } #[cfg(test)] mod tests { - use super::*; - use arrow::array::types::Int32Type; - use arrow::array::{ArrayRef, Int32Array}; - use arrow::datatypes::DataType; - use datafusion_expr::EmitTo; + use std::collections::BTreeMap; use std::sync::Arc; + use crate::aggregates::group_values::single_group_by::primitive::GroupValuesPrimitive; + use crate::aggregates::group_values::GroupValues; + use arrow::array::{ArrayRef, AsArray, Int32Array, UInt32Array}; + use arrow::datatypes::{DataType, Int32Type, UInt32Type}; + use datafusion_common::Result; + use datafusion_expr::EmitTo; + use datafusion_functions_aggregate_common::aggregate::groups_accumulator::group_index_operations::{ + BlockedGroupIndexOperations, GroupIndexOperations, + }; + + #[test] + fn test_flat_primitive_group_values() { + // Will cover such insert cases: + // 1.1 Non-null row + distinct + // 1.2 Null row + distinct + // 1.3 Non-null row + non-distinct + // 1.4 Null row + non-distinct + // + // Will cover such emit cases: + // 2.1 Emit first n + // 2.2 Emit all + // 2.3 Insert again + emit + let mut group_values = GroupValuesPrimitive::::new(DataType::UInt32); + let mut group_indices = vec![]; + + let data1 = Arc::new(UInt32Array::from(vec![ + Some(1), + None, + Some(1), + None, + Some(2), + Some(3), + ])); + let data2 = Arc::new(UInt32Array::from(vec![Some(3), None, Some(4), Some(5)])); + + // Insert case 1.1, 1.3, 1.4 + Emit case 2.1 + group_values + .intern(&[Arc::clone(&data1) as _], &mut group_indices) + .unwrap(); + + let mut expected = BTreeMap::new(); + for (&group_index, value) in group_indices.iter().zip(data1.iter()) { + expected.insert(group_index, value); + } + let mut expected = expected.into_iter().collect::>(); + let last_group_index = expected.len() - 1; + let last_value = expected.last().unwrap().1; + expected.pop(); + + let emit_result = group_values.emit(EmitTo::First(3)).unwrap(); + let actual = emit_result[0] + .as_primitive::() + .iter() + .enumerate() + .map(|(group_idx, val)| { + assert!(group_idx < last_group_index); + (group_idx, val) + }) + .collect::>(); + + assert_eq!(expected, actual); + + // Insert case 1.1~1.3 + Emit case 2.2~2.3 + group_values + .intern(&[Arc::clone(&data2) as _], &mut group_indices) + .unwrap(); + + let mut expected = BTreeMap::new(); + for (&group_index, value) in group_indices.iter().zip(data2.iter()) { + if group_index == 0 { + assert_eq!(last_value, value); + } + expected.insert(group_index, value); + } + let expected = expected.into_iter().collect::>(); + + let emit_result = group_values.emit(EmitTo::All).unwrap(); + let actual = emit_result[0] + .as_primitive::() + .iter() + .enumerate() + .collect::>(); + + assert_eq!(expected, actual); + } + + #[test] + fn test_blocked_primitive_group_values() { + // Will cover such insert cases: + // 1.1 Non-null row + distinct + // 1.2 Null row + distinct + // 1.3 Non-null row + non-distinct + // 1.4 Null row + non-distinct + // + // Will cover such emit cases: + // 2.1 Emit block + // 2.2 Insert again + emit block + // + let mut group_values = GroupValuesPrimitive::::new(DataType::UInt32); + let block_size = 2; + group_values.alter_block_size(Some(block_size)).unwrap(); + let mut group_indices = vec![]; + + let data1 = Arc::new(UInt32Array::from(vec![ + Some(1), + None, + Some(1), + None, + Some(2), + Some(3), + ])); + let data2 = Arc::new(UInt32Array::from(vec![Some(3), None, Some(4)])); + + // Insert case 1.1, 1.3, 1.4 + Emit case 2.1 + group_values + .intern(&[Arc::clone(&data1) as _], &mut group_indices) + .unwrap(); + + let mut expected = BTreeMap::new(); + for (&packed_index, value) in group_indices.iter().zip(data1.iter()) { + let block_id = BlockedGroupIndexOperations::get_block_id(packed_index as u64); + let block_offset = + BlockedGroupIndexOperations::get_block_offset(packed_index as u64); + let flatten_index = block_id as usize * block_size + block_offset as usize; + expected.insert(flatten_index, value); + } + let expected = expected.into_iter().collect::>(); + + let emit_result1 = group_values.emit(EmitTo::NextBlock).unwrap(); + assert_eq!(emit_result1[0].len(), block_size); + let emit_result2 = group_values.emit(EmitTo::NextBlock).unwrap(); + assert_eq!(emit_result2[0].len(), block_size); + let iter1 = emit_result1[0].as_primitive::().iter(); + let iter2 = emit_result2[0].as_primitive::().iter(); + let actual = iter1.chain(iter2).enumerate().collect::>(); + + assert_eq!(actual, expected); + + // Insert case 1.1~1.2 + Emit case 2.2 + group_values + .intern(&[Arc::clone(&data2) as _], &mut group_indices) + .unwrap(); + + let mut expected = BTreeMap::new(); + for (&packed_index, value) in group_indices.iter().zip(data2.iter()) { + let block_id = BlockedGroupIndexOperations::get_block_id(packed_index as u64); + let block_offset = + BlockedGroupIndexOperations::get_block_offset(packed_index as u64); + let flatten_index = block_id as usize * block_size + block_offset as usize; + expected.insert(flatten_index, value); + } + let expected = expected.into_iter().collect::>(); + + let emit_result1 = group_values.emit(EmitTo::NextBlock).unwrap(); + assert_eq!(emit_result1[0].len(), block_size); + let emit_result2 = group_values.emit(EmitTo::NextBlock).unwrap(); + assert_eq!(emit_result2[0].len(), 1); + let iter1 = emit_result1[0].as_primitive::().iter(); + let iter2 = emit_result2[0].as_primitive::().iter(); + let actual = iter1.chain(iter2).enumerate().collect::>(); + + assert_eq!(actual, expected); + } + + fn flat_values_capacity(gv: &GroupValuesPrimitive) -> usize { + match &gv.state { + super::GroupValuesPrimitiveStateAdapter::Flat(state) => { + state.values[0].capacity() + } + super::GroupValuesPrimitiveStateAdapter::Blocked(_) => { + panic!("expected flat primitive group values") + } + } + } + /// Mirror of the `EmitTo::take_needed` regression test, applied to the /// concrete `GroupValuesPrimitive` accumulator. /// @@ -274,7 +676,7 @@ mod tests { let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..20i32)); let mut groups = vec![]; gv.intern(&[arr], &mut groups)?; - let capacity_before = gv.values.capacity(); // 128 + let capacity_before = flat_values_capacity(&gv); // 128 // n=4, n*2=8 <= len=20 -> drain branch let emitted = gv.emit(EmitTo::First(4))?; @@ -284,10 +686,10 @@ mod tests { // `self.values` must retain its original large allocation. // Old split_off+swap left it with a fresh small allocation (~16). assert_eq!( - gv.values.capacity(), + flat_values_capacity(&gv), capacity_before, "self.values capacity {} should equal original {} after small First(n) emit", - gv.values.capacity(), + flat_values_capacity(&gv), capacity_before, ); diff --git a/datafusion/physical-plan/src/aggregates/order/mod.rs b/datafusion/physical-plan/src/aggregates/order/mod.rs index 97fbd519c825c..ebfdd4323984c 100644 --- a/datafusion/physical-plan/src/aggregates/order/mod.rs +++ b/datafusion/physical-plan/src/aggregates/order/mod.rs @@ -79,6 +79,7 @@ impl GroupOrdering { self.emit_to().map(|emit_to| match emit_to { EmitTo::First(max) => EmitTo::First(n.min(max)), EmitTo::All => EmitTo::First(n), + EmitTo::NextBlock => EmitTo::NextBlock, }) } } diff --git a/datafusion/physical-plan/src/aggregates/row_hash.rs b/datafusion/physical-plan/src/aggregates/row_hash.rs index d46faf9acc14a..2bfd1f584948d 100644 --- a/datafusion/physical-plan/src/aggregates/row_hash.rs +++ b/datafusion/physical-plan/src/aggregates/row_hash.rs @@ -46,7 +46,7 @@ use datafusion_common::{ }; use datafusion_execution::TaskContext; use datafusion_execution::memory_pool::proxy::VecAllocExt; -use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation}; +use datafusion_execution::memory_pool::{MemoryConsumer, MemoryLimit, MemoryReservation}; use datafusion_expr::{EmitTo, GroupsAccumulator}; use datafusion_physical_expr::aggregate::AggregateFunctionExpr; use datafusion_physical_expr::expressions::Column; @@ -67,6 +67,11 @@ pub(crate) enum ExecutionState { /// When producing output, the remaining rows to output are stored /// here and are sliced off as needed in batch_size chunks ProducingOutput(RecordBatch), + /// Producing output block by block. + /// + /// It is the blocked version `ProducingOutput` and will be used + /// when blocked optimization is enabled. + ProducingBlocks, /// Produce intermediate aggregate state for each input row without /// aggregation. /// @@ -262,6 +267,35 @@ enum OutOfMemoryMode { /// │ 2 │ 2 │ 3.0 │ │ 2 │ 2 │ 3.0 │ └────────────┘ /// └─────────────────┘ └─────────────────┘ /// ``` +/// +/// # Blocked approach for intermediate results +/// +/// An important optimization for [`group_values`] and [`accumulators`] +/// is to manage such intermediate results using the blocked approach. +/// +/// In the original method, intermediate results are managed within a single large block +/// (can think of it as a Vec). As this block grows, it often triggers numerous +/// copies, resulting in poor performance. +/// +/// In contrast, the blocked approach allocates capacity for the block +/// based on a predefined block size firstly. +/// And when the block reaches its limit, we allocate a new block +/// (also with the same predefined block size based capacity) +/// instead of expanding the current one and copying the data. +/// This method eliminates unnecessary copies and significantly improves performance. +/// +/// You can find some implementation details(like how to locate data in such two approaches) +/// in [`GroupsAccumulator::supports_blocked_groups`] and [`GroupValues::supports_blocked_groups`]. +/// +/// And for a really detailed introduction to the design of blocked approach, maybe you can see [#7065]. +/// +/// The conditions that trigger the blocked groups optimization can be found in +/// [`can_enable_blocked_groups`]. +/// +/// [`group_values`]: Self::group_values +/// [`accumulators`]: Self::accumulators +/// [#7065]: +/// pub(crate) struct GroupedHashAggregateStream { // ======================================================================== // PROPERTIES: @@ -347,6 +381,9 @@ pub(crate) struct GroupedHashAggregateStream { /// current stream. skip_aggregation_probe: Option, + /// Have we enabled the blocked optimization for group values and accumulators + enable_blocked_groups: bool, + // ======================================================================== // EXECUTION RESOURCES: // Fields related to managing execution resources and monitoring performance. @@ -408,7 +445,7 @@ impl GroupedHashAggregateStream { }; // Instantiate the accumulators - let accumulators: Vec<_> = aggregate_exprs + let mut accumulators: Vec<_> = aggregate_exprs .iter() .map(create_group_accumulator) .collect::>()?; @@ -480,13 +517,15 @@ impl GroupedHashAggregateStream { .join(", "); let name = format!("GroupedHashAggregateStream[{partition}] ({agg_fn_names})"); let group_ordering = GroupOrdering::try_new(&agg.input_order_mode)?; - let oom_mode = match (agg.mode, &group_ordering) { + let no_memory_limit = + matches!(context.memory_pool().memory_limit(), MemoryLimit::Infinite); + let oom_mode = match (agg.mode, &group_ordering, no_memory_limit) { // In partial aggregation mode, always prefer to emit incomplete results early. - (AggregateMode::Partial, _) => OutOfMemoryMode::EmitEarly, + (AggregateMode::Partial, _, false) => OutOfMemoryMode::EmitEarly, // For non-partial aggregation modes, emitting incomplete results is not an option. // Instead, use disk spilling to store sorted, incomplete results, and merge them // afterwards. - (_, GroupOrdering::None | GroupOrdering::Partial(_)) + (_, GroupOrdering::None | GroupOrdering::Partial(_), false) if context.runtime_env().disk_manager.tmp_files_enabled() => { OutOfMemoryMode::Spill @@ -498,10 +537,11 @@ impl GroupedHashAggregateStream { // Therefore, we fall back to simply reporting the error immediately. // This mode will also be used if the `DiskManager` is not configured to allow spilling // to disk. + // Also if no memory limit in memory pool, but oom happens, it should be an error. _ => OutOfMemoryMode::ReportError, }; - let group_values = new_group_values(group_schema, &group_ordering)?; + let mut group_values = new_group_values(group_schema, &group_ordering)?; let reservation = MemoryConsumer::new(name) // We interpret 'can spill' as 'can handle memory back pressure'. // This value needs to be set to true for the default memory pool implementations @@ -569,6 +609,29 @@ impl GroupedHashAggregateStream { None }; + // Check if we can enable the blocked optimization for `GroupValues` and `GroupsAccumulator`s. + let can_enable_blocked_groups = can_enable_blocked_groups( + &group_ordering, + &oom_mode, + &group_values, + &accumulators, + ); + + let enable_blocked_groups = context + .session_config() + .options() + .execution + .enable_aggregation_blocked_groups + && can_enable_blocked_groups; + + if enable_blocked_groups { + group_values.alter_block_size(Some(batch_size))?; + accumulators + .iter_mut() + .try_for_each(|acc| acc.alter_block_size(Some(batch_size)))?; + } + + // Metrics for aggregation stats let reduction_factor = if agg.mode == AggregateMode::Partial { Some( MetricBuilder::new(&agg.metrics) @@ -601,6 +664,7 @@ impl GroupedHashAggregateStream { spill_state, group_values_soft_limit: agg.limit_options().map(|config| config.limit()), skip_aggregation_probe, + enable_blocked_groups, reduction_factor, }) } @@ -626,6 +690,35 @@ pub(crate) fn create_group_accumulator( } } +/// Check if we can enable the blocked optimization for `GroupValues` and `GroupsAccumulator`s. +/// The blocked optimization can be enabled when: +/// - It is not streaming aggregation(because blocked mode can't support Emit::first(exact n)) +/// - The spilling is disabled(still need to consider more to support it efficiently) +/// - [`GroupValues::supports_blocked_groups`] and all [`GroupsAccumulator::supports_blocked_groups`] are true +/// +/// [`GroupValues::supports_blocked_groups`]: crate::aggregates::group_values::GroupValues::supports_blocked_groups +/// [`GroupsAccumulator::supports_blocked_groups`]: datafusion_expr::GroupsAccumulator::supports_blocked_groups +/// +// TODO: support blocked optimization in streaming, spilling, and maybe empty accumulators case? +#[expect(clippy::borrowed_box)] +fn can_enable_blocked_groups( + group_ordering: &GroupOrdering, + oom_mode: &OutOfMemoryMode, + group_values: &Box, + accumulators: &[Box], +) -> bool { + if !matches!(group_ordering, GroupOrdering::None) + || !matches!(oom_mode, OutOfMemoryMode::ReportError) + { + return false; + } + + let group_values_supports_blocked = group_values.supports_blocked_groups(); + let accumulators_support_blocked = + accumulators.iter().all(|acc| acc.supports_blocked_groups()); + group_values_supports_blocked && accumulators_support_blocked +} + impl Stream for GroupedHashAggregateStream { type Item = Result; @@ -805,6 +898,33 @@ impl Stream for GroupedHashAggregateStream { ))); } + ExecutionState::ProducingBlocks => { + // Try to emit and then: + // - If found `Err`, throw it, end this stream abnormally + // - If found `None`, it means all blocks are polled, end this stream normally + // - If found `Some`, return it and wait next polling + let emit_result = self.emit(EmitTo::NextBlock, false); + let Ok(batch_opt) = emit_result else { + return Poll::Ready(Some(Err(emit_result.unwrap_err()))); + }; + + let Some(batch) = batch_opt else { + self.exec_state = if self.input_done { + ExecutionState::Done + } else if self.should_skip_aggregation() { + ExecutionState::SkippingAggregation + } else { + ExecutionState::ReadingInput + }; + continue; + }; + + debug_assert!(batch.num_rows() > 0); + return Poll::Ready(Some(Ok( + batch.record_output(&self.baseline_metrics) + ))); + } + ExecutionState::Done => { // Sanity check: all groups should have been emitted by now if !self.group_values.is_empty() { @@ -1262,12 +1382,21 @@ impl GroupedHashAggregateStream { self.exec_state = if self.spill_state.spills.is_empty() { // Input has been entirely processed without spilling to disk. self.init_empty_grouping_sets()?; + if !self.enable_blocked_groups { + // Flush any remaining group values. + let batch = self.emit(EmitTo::All, false)?; - // Flush any remaining group values. - let batch = self.emit(EmitTo::All, false)?; - - // If there are none, we're done; otherwise switch to emitting them - batch.map_or(ExecutionState::Done, ExecutionState::ProducingOutput) + // If there are none, we're done; otherwise switch to emitting them + batch.map_or(ExecutionState::Done, ExecutionState::ProducingOutput) + } else { + assert!(can_enable_blocked_groups( + &self.group_ordering, + &self.oom_mode, + &self.group_values, + &self.accumulators + )); + ExecutionState::ProducingBlocks + } } else { // Spill any remaining data to disk. There is some performance overhead in // writing out this last chunk of data and reading it back. The benefit of @@ -1344,10 +1473,21 @@ impl GroupedHashAggregateStream { fn switch_to_skip_aggregation(&mut self) -> Result> { if let Some(probe) = self.skip_aggregation_probe.as_mut() && probe.should_skip() - && let Some(batch) = self.emit(EmitTo::All, false)? { - return Ok(Some(ExecutionState::ProducingOutput(batch))); - }; + if !self.enable_blocked_groups { + if let Some(batch) = self.emit(EmitTo::All, false)? { + return Ok(Some(ExecutionState::ProducingOutput(batch))); + }; + } else { + assert!(can_enable_blocked_groups( + &self.group_ordering, + &self.oom_mode, + &self.group_values, + &self.accumulators + )); + return Ok(Some(ExecutionState::ProducingBlocks)); + } + } Ok(None) } diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index 0932f58a7c03f..54ecd52ffd62a 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -217,6 +217,7 @@ datafusion.catalog.newlines_in_values false datafusion.execution.batch_size 8192 datafusion.execution.coalesce_batches true datafusion.execution.collect_statistics true +datafusion.execution.enable_aggregation_blocked_groups false datafusion.execution.enable_ansi_mode false datafusion.execution.enable_migration_aggregate true datafusion.execution.enable_recursive_ctes true @@ -373,7 +374,8 @@ datafusion.catalog.location NULL Location scanned to load tables for `default` s datafusion.catalog.newlines_in_values false Specifies whether newlines in (quoted) CSV values are supported. This is the default value for `format.newlines_in_values` for `CREATE EXTERNAL TABLE` if not specified explicitly in the statement. Parsing newlines in quoted values may be affected by execution behaviour such as parallel file scanning. Setting this to `true` ensures that newlines in values are parsed successfully, which may reduce performance. datafusion.execution.batch_size 8192 Default batch size while creating new batches, it's especially useful for buffer-in-memory batches since creating tiny batches would result in too much metadata memory consumption datafusion.execution.coalesce_batches true When set to true, record batches will be examined between each operator and small batches will be coalesced into larger batches. This is helpful when there are highly selective filters or joins that could produce tiny output batches. The target batch size is determined by the configuration setting -datafusion.execution.collect_statistics true Should DataFusion collect statistics when first creating a table. Has no effect after the table is created. Defaults to true. +datafusion.execution.collect_statistics true Should DataFusion collect statistics when first creating a table. Has no effect after the table is created. Applies to the default `ListingTableProvider` in DataFusion. Defaults to true. +datafusion.execution.enable_aggregation_blocked_groups false Should DataFusion use a blocked approach to manage grouping state. When enabled, the blocked approach allocates capacity based on a predefined block size firstly. When the block reaches its limit, we allocate a new block (also with the same predefined block size based capacity) instead of expanding the current one and copying the data. If `false`, a single allocation approach is used, where values are managed within a single large memory block. As this block grows, it often triggers numerous copies, resulting in poor performance. datafusion.execution.enable_ansi_mode false Whether to enable ANSI SQL mode. The flag is experimental and relevant only for DataFusion Spark built-in functions When `enable_ansi_mode` is set to `true`, the query engine follows ANSI SQL semantics for expressions, casting, and error handling. This means: - **Strict type coercion rules:** implicit casts between incompatible types are disallowed. - **Standard SQL arithmetic behavior:** operations such as division by zero, numeric overflow, or invalid casts raise runtime errors rather than returning `NULL` or adjusted values. - **Consistent ANSI behavior** for string concatenation, comparisons, and `NULL` handling. When `enable_ansi_mode` is `false` (the default), the engine uses a more permissive, non-ANSI mode designed for user convenience and backward compatibility. In this mode: - Implicit casts between types are allowed (e.g., string to integer when possible). - Arithmetic operations are more lenient — for example, `abs()` on the minimum representable integer value returns the input value instead of raising overflow. - Division by zero or invalid casts may return `NULL` instead of failing. # Default `false` — ANSI SQL mode is disabled by default. datafusion.execution.enable_migration_aggregate true Temporary switch for aggregate stream implementations that are being migrated from `GroupedHashAggregateStream`. When set to true, DataFusion tries the migrated implementations when their preconditions are satisfied. When set to false, grouped aggregation falls back to `GroupedHashAggregateStream`. This option will be removed after the migration is finished. See for details. datafusion.execution.enable_recursive_ctes true Should DataFusion support recursive CTEs diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index f70daef317216..3a272c2ee0af0 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -140,6 +140,7 @@ The following configuration settings are available: | datafusion.execution.use_row_number_estimates_to_optimize_partitioning | false | Should DataFusion use row number estimates at the input to decide whether increasing parallelism is beneficial or not. By default, only exact row numbers (not estimates) are used for this decision. Setting this flag to `true` will likely produce better plans. if the source of statistics is accurate. We plan to make this the default in the future. | | datafusion.execution.enforce_batch_size_in_joins | false | Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. | | datafusion.execution.objectstore_writer_buffer_size | 10485760 | Size (bytes) of data buffer DataFusion uses when writing output files. This affects the size of the data chunks that are uploaded to remote object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being written, it may be necessary to increase this size to avoid errors from the remote end point. | +| datafusion.execution.enable_aggregation_blocked_groups | false | Should DataFusion use a blocked approach to manage grouping state. When enabled, the blocked approach allocates capacity based on a predefined block size firstly. When the block reaches its limit, we allocate a new block (also with the same predefined block size based capacity) instead of expanding the current one and copying the data. If `false`, a single allocation approach is used, where values are managed within a single large memory block. As this block grows, it often triggers numerous copies, resulting in poor performance. | | datafusion.execution.enable_ansi_mode | false | Whether to enable ANSI SQL mode. The flag is experimental and relevant only for DataFusion Spark built-in functions When `enable_ansi_mode` is set to `true`, the query engine follows ANSI SQL semantics for expressions, casting, and error handling. This means: - **Strict type coercion rules:** implicit casts between incompatible types are disallowed. - **Standard SQL arithmetic behavior:** operations such as division by zero, numeric overflow, or invalid casts raise runtime errors rather than returning `NULL` or adjusted values. - **Consistent ANSI behavior** for string concatenation, comparisons, and `NULL` handling. When `enable_ansi_mode` is `false` (the default), the engine uses a more permissive, non-ANSI mode designed for user convenience and backward compatibility. In this mode: - Implicit casts between types are allowed (e.g., string to integer when possible). - Arithmetic operations are more lenient — for example, `abs()` on the minimum representable integer value returns the input value instead of raising overflow. - Division by zero or invalid casts may return `NULL` instead of failing. # Default `false` — ANSI SQL mode is disabled by default. | | datafusion.execution.hash_join_buffering_capacity | 0 | How many bytes to buffer in the probe side of hash joins while the build side is concurrently being built. Without this, hash joins will wait until the full materialization of the build side before polling the probe side. This is useful in scenarios where the query is not completely CPU bounded, allowing to do some early work concurrently and reducing the latency of the query. Note that when hash join buffering is enabled, the probe side will start eagerly polling data, not giving time for the producer side of dynamic filters to produce any meaningful predicate. Queries with dynamic filters might see performance degradation. Disabled by default, set to a number greater than 0 for enabling it. | | datafusion.optimizer.enable_distinct_aggregation_soft_limit | true | When set to true, the optimizer will push a limit operation into grouped aggregations which have no aggregate expressions, as a soft limit, emitting groups once the limit is reached, before all rows in the group are read. | diff --git a/testing b/testing index 7df2b70baf4f0..249079a810cae 160000 --- a/testing +++ b/testing @@ -1 +1 @@ -Subproject commit 7df2b70baf4f081ebf8e0c6bd22745cf3cbfd824 +Subproject commit 249079a810caedda6898464003c7ef8a47efeeae