diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index cdcecfe6196b4..528bdc2d35c8a 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -1088,12 +1088,13 @@ config_namespace! { /// Aggregation ratio (number of groups the partial aggregation creates / /// number of input rows) threshold for skipping partial aggregation. A key /// that returns after an early emit under memory pressure counts again. - /// If the value is greater then partial aggregation will skip aggregation - /// for further input + /// If the ratio exceeds this threshold, partial aggregation bypasses grouping + /// temporarily, then probes again with an empty table. Values at or above 1.0 + /// disable skipping; non-positive values keep skipping once it starts. pub skip_partial_aggregation_probe_ratio_threshold: f64, default = 0.8 /// Number of input rows partial aggregation partition should process, before - /// aggregation ratio check and trying to switch to skipping aggregation mode + /// aggregation ratio check and trying to switch to skipping aggregation mode. pub skip_partial_aggregation_probe_rows_threshold: usize, default = 100_000 /// Should DataFusion use row number estimates at the input to decide diff --git a/datafusion/core/benches/aggregate_query_sql.rs b/datafusion/core/benches/aggregate_query_sql.rs index 4d95e3067614b..9239fb406fd25 100644 --- a/datafusion/core/benches/aggregate_query_sql.rs +++ b/datafusion/core/benches/aggregate_query_sql.rs @@ -577,10 +577,60 @@ fn first_last_nested_view(c: &mut Criterion) { group.finish(); } +/// Measure complete SQL queries whose partial aggregates can cross the probe +/// threshold. The smaller fixtures above do not exercise skipping or re-probing. +fn partial_aggregation_reprobe(c: &mut Criterion) { + let cases = [ + ("unique_short", 2_000_000, Some("value * 104729 % 2000000")), + ("unique_long", 10_000_000, Some("value * 104729 % 10000000")), + ( + "changing", + 2_000_000, + Some("CASE WHEN value <= 400000 THEN value ELSE value % 1000 END"), + ), + ( + "late_change", + 12_000_000, + Some( + "CASE WHEN value <= 8000000 THEN value * 104729 % 8000000 \ + ELSE value % 1000 END", + ), + ), + ("repeated", 2_000_000, Some("value % 1000")), + ("ungrouped", 2_000_000, None), + ]; + let rt = Runtime::new().unwrap(); + let mut group = c.benchmark_group("partial_aggregation_reprobe"); + let mut config = SessionConfig::new() + .with_target_partitions(2) + .with_batch_size(8192); + let execution = &mut config.options_mut().execution; + execution.skip_partial_aggregation_probe_rows_threshold = 100_000; + execution.skip_partial_aggregation_probe_ratio_threshold = 0.8; + let ctx = Arc::new(Mutex::new(SessionContext::new_with_config(config))); + + for (name, input_rows, key) in cases { + let sql = match key { + Some(key) => format!( + "SELECT {key} AS k, SUM(value) AS total \ + FROM generate_series(1, {input_rows}) GROUP BY k" + ), + None => format!( + "SELECT SUM(value) AS total FROM generate_series(1, {input_rows})" + ), + }; + group.bench_function(name, |b| { + b.iter(|| query(ctx.clone(), &rt, &sql)); + }); + } + group.finish(); +} + criterion_group!( benches, criterion_benchmark, fully_ordered, - first_last_nested_view + first_last_nested_view, + partial_aggregation_reprobe ); criterion_main!(benches); 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 bbabadb0ef33a..5b54534416381 100644 --- a/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/context_generator.rs +++ b/datafusion/core/tests/fuzz_cases/aggregation_fuzzer/context_generator.rs @@ -55,6 +55,12 @@ impl SessionContextGenerator { pub fn new(dataset_ref: Arc, table_name: &str) -> Self { let candidate_skip_partial_params = vec![ SkipPartialParams::ensure_trigger(), + SkipPartialParams { + // Exercise repeated aggregate/flush/convert cycles as well as + // permanent skipping and aggregation without skipping. + ratio_threshold: f64::MIN_POSITIVE, + rows_threshold: 0, + }, SkipPartialParams::ensure_not_trigger(), ]; @@ -106,11 +112,9 @@ impl SessionContextGenerator { // We will randomly generate following options: // - `batch_size`, from range: [1, `total_rows_num`] // - `target_partitions`, from range: [1, cpu_num] - // - `skip_partial`, trigger or not trigger currently for simplicity + // - `skip_partial`, permanent skipping, re-probing, or disabled // - `sorted`, if found a sorted dataset, will or will not push down this information // - `spilling`(TODO) - let batch_size = rng.random_range(1..=self.max_batch_size); - let target_partitions = rng.random_range(1..=self.max_target_partitions); let skip_partial_params_idx = @@ -118,6 +122,14 @@ impl SessionContextGenerator { let skip_partial_params = self.candidate_skip_partial_params[skip_partial_params_idx]; + // Small batches let the re-probing candidate reach multiple skip windows. + let max_batch_size = if skip_partial_params.ratio_threshold == f64::MIN_POSITIVE { + self.max_batch_size.min(16) + } else { + self.max_batch_size + }; + let batch_size = rng.random_range(1..=max_batch_size); + let (provider, sort_hint) = if rng.random_bool(0.5) && !self.dataset.sort_keys.is_empty() { // Sort keys exist and random to push down diff --git a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs index bec4c1db0d043..e1290b7c0a863 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs @@ -65,18 +65,6 @@ impl AggregateArgument { }) } - /// Keeps the expression and its type without retaining a literal array. - pub(in crate::aggregates) fn empty_like(&self) -> Self { - Self { - expr: Arc::clone(&self.expr), - data_type: self.data_type.clone(), - literal: self - .literal - .as_ref() - .map(|literal| LiteralArray::new(literal.value.clone())), - } - } - pub(in crate::aggregates) fn null_array(&self, num_rows: usize) -> ArrayRef { new_null_array(&self.data_type, num_rows) } @@ -186,10 +174,6 @@ impl AggregateFilter { } } - pub(in crate::aggregates) fn predicate(&self) -> &Arc { - &self.predicate - } - /// Evaluates the filter predicate for `batch` and returns the rows it /// selects. A null rejects its row, like `false`. /// diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs index 79e1e0035966f..dd858665d997d 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs @@ -43,8 +43,6 @@ pub(in crate::aggregates) struct PartialMarker; pub(in crate::aggregates) struct SingleMarker; /// Marker for partial state -> partial state aggregation. pub(in crate::aggregates) struct PartialReduceMarker; -/// Marker for raw rows -> partial state conversion without aggregation. -pub(in crate::aggregates) struct PartialSkipMarker; /// Marker for partial state -> final value aggregation. pub(in crate::aggregates) struct FinalMarker; @@ -165,11 +163,9 @@ impl AggregateHashTable { .map(|expr| AggregateArgument::try_new(expr, &input_schema)) .collect::>()?; Ok(HashAggregateAccumulator::new( - Arc::clone(agg_expr), arguments, filter, accumulator, - Arc::clone(submetrics), )) }) .collect::>()?; @@ -513,10 +509,6 @@ impl AggregateHashTable { /// For example, for `SELECT COUNT(x), SUM(y WHERE z > 10) ...` there would be two /// `HashAggregateAccumulator`, one each for `COUNT(x)` and `SUM(y WHERE z > 10)` pub(super) struct HashAggregateAccumulator { - /// Aggregate expression used to create a fresh accumulator for related - /// hash tables, such as the partial-skip table. - aggregate_expr: Arc, - /// Arguments to pass to this accumulator. /// /// Example: `CORR(x, y)` stores two arguments here, while `SUM(x)` stores one. @@ -529,9 +521,6 @@ pub(super) struct HashAggregateAccumulator { /// Accumulator state for all groups for one aggregate expression. accumulator: Box, - - /// Optional internal metrics owned by this aggregate expression. - submetrics: Arc, } pub(super) type AggregateAccumulator = HashAggregateAccumulator; @@ -638,17 +627,17 @@ pub(super) enum AggregateHashTableState { /// Final aggregate evaluation consumes accumulator state, and partial terminal /// output should not repeatedly renumber group values with `EmitTo::First`. /// Materialize once and then slice to honor `batch_size` across output polls. -pub(super) struct MaterializedAggregateOutput { +pub(in crate::aggregates) struct MaterializedAggregateOutput { batch: RecordBatch, offset: usize, } impl MaterializedAggregateOutput { - pub(super) fn new(batch: RecordBatch) -> Self { + pub(in crate::aggregates) fn new(batch: RecordBatch) -> Self { Self { batch, offset: 0 } } - pub(super) fn next_batch( + pub(in crate::aggregates) fn next_batch( &mut self, batch_size: usize, ) -> Result> { @@ -663,11 +652,11 @@ impl MaterializedAggregateOutput { compact_dictionaries(batch).map(Some) } - pub(super) fn is_exhausted(&self) -> bool { + pub(in crate::aggregates) fn is_exhausted(&self) -> bool { self.offset >= self.batch.num_rows() } - pub(super) fn memory_size(&self) -> usize { + pub(in crate::aggregates) fn memory_size(&self) -> usize { self.batch.get_array_memory_size() } } @@ -740,41 +729,18 @@ fn compact_group_indices( impl HashAggregateAccumulator { pub(super) fn new( - aggregate_expr: Arc, arguments: Vec, filter: Option>, accumulator: Box, - submetrics: Arc, ) -> Self { let filter = filter.map(|predicate| AggregateFilter::new(predicate, &arguments)); Self { - aggregate_expr, arguments, filter, accumulator, - submetrics, } } - /// Construct a new accumulator with the same definition, but with empty internal - /// state buffers (empty [`GroupsAccumulator`]). - pub(super) fn empty_like(&self) -> Result { - let accumulator = - create_group_accumulator(&self.aggregate_expr, Arc::clone(&self.submetrics))?; - Ok(Self::new( - Arc::clone(&self.aggregate_expr), - self.arguments - .iter() - .map(AggregateArgument::empty_like) - .collect(), - self.filter - .as_ref() - .map(|filter| Arc::clone(filter.predicate())), - accumulator, - Arc::clone(&self.submetrics), - )) - } - /// Evaluate aggregate arguments and filter for one input batch. /// /// For example, `AVG(2 / x) FILTER (WHERE x > 0)` evaluates `x > 0` @@ -1283,11 +1249,9 @@ mod tests { let accumulator = create_group_accumulator(&aggregate_expr, Arc::clone(&submetrics))?; Ok(HashAggregateAccumulator::new( - aggregate_expr, vec![AggregateArgument::try_new(argument, schema)?], Some(Arc::new(Column::new(filter_name, filter_index))), accumulator, - submetrics, )) } diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs index 52ac5f7c761f7..8374dd12dd15c 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common_clustered.rs @@ -196,13 +196,7 @@ impl ClusteredAggregateTable { .into_iter() .map(|expr| AggregateArgument::try_new(expr, input_schema)) .collect::>()?; - Ok(AggregateAccumulator::new( - Arc::clone(agg_expr), - arguments, - filter, - accumulator, - Arc::clone(submetrics), - )) + Ok(AggregateAccumulator::new(arguments, filter, accumulator)) }) .collect::>()?; diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs index 1fd7fed226c0d..d5fa12c5ad591 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs @@ -151,8 +151,8 @@ impl AggregateTableMetrics { } pub(super) use common::{ - AggregateHashTable, FinalMarker, PartialMarker, PartialReduceMarker, - PartialSkipMarker, SingleMarker, + AggregateHashTable, FinalMarker, MaterializedAggregateOutput, PartialMarker, + PartialReduceMarker, SingleMarker, }; pub(super) use common_clustered::{ ClusteredAggregateTable, ClusteredAggregateTableMetrics, diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs index 9f716e775aeab..ac38f06c6ebd9 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/partial_table.rs @@ -2,20 +2,15 @@ // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements -use std::marker::PhantomData; use std::sync::Arc; -use crate::aggregates::group_values::{AccumulatorPhase, new_group_values}; -use crate::aggregates::order::GroupClustering; +use crate::aggregates::group_values::AccumulatorPhase; use crate::aggregates::{AggregateExec, evaluate_group_by}; use arrow::datatypes::SchemaRef; use arrow::record_batch::RecordBatch; use datafusion_common::{Result, assert_eq_or_internal_err}; -use super::common::{ - AggregateHashTable, AggregateHashTableBuffer, AggregateHashTableState, - HashAggregateAccumulator, PartialMarker, PartialSkipMarker, -}; +use super::common::{AggregateHashTable, HashAggregateAccumulator, PartialMarker}; /// Implementation specific to partial aggregation, where the table stores /// partial aggregate states and the input rows are raw rows. @@ -56,42 +51,6 @@ impl AggregateHashTable { ) } - /// In skip-partial-aggregation optimization, when a decision has been made to skip - /// partial stage, build a typed hash table only for aggregation state conversion - /// row-by-row. - pub(in crate::aggregates) fn partial_skip_table( - &self, - ) -> Result> { - let state = self.state.building(); - let group_schema = state.group_by.group_schema(&self.input_schema)?; - let group_values = new_group_values(group_schema, &GroupClustering::None)?; - let accumulators = state - .accumulators - .iter() - .map(HashAggregateAccumulator::empty_like) - .collect::>>()?; - - Ok(AggregateHashTable { - group_by_metrics: self.group_by_metrics.clone(), - aggregate_argument_metrics: self.aggregate_argument_metrics.clone(), - aggregate_accumulator_metrics: Arc::clone( - &self.aggregate_accumulator_metrics, - ), - aggregate_submetrics: self.aggregate_submetrics.clone(), - input_schema: Arc::clone(&self.input_schema), - output_schema: Arc::clone(&self.output_schema), - state_schema: Arc::clone(&self.state_schema), - batch_size: self.batch_size, - state: AggregateHashTableState::Building(AggregateHashTableBuffer { - group_by: Arc::clone(&state.group_by), - group_values, - batch_group_indices: Default::default(), - accumulators, - }), - _mode: PhantomData, - }) - } - /// Partial aggregation consumes raw input rows and updates the table's /// partial-state accumulators. pub(in crate::aggregates) fn aggregate_batch( @@ -110,14 +69,15 @@ impl AggregateHashTable { self.start_outputting(); Ok(()) } -} -impl AggregateHashTable { + /// Converts raw rows to partial states without inserting them into the table. + /// All accumulated groups must have been emitted before bypassing aggregation. pub(in crate::aggregates) fn convert_batch_to_state( &mut self, batch: &RecordBatch, ) -> Result { let state = self.state.building_mut(); + debug_assert!(state.group_values.is_empty()); let grouping_set_args = self .group_by_metrics .time_group_key_preparation(|| evaluate_group_by(&state.group_by, batch))?; diff --git a/datafusion/physical-plan/src/aggregates/hash_stream.rs b/datafusion/physical-plan/src/aggregates/hash_stream.rs index e3ee8fb28a547..df5199cc6a2df 100644 --- a/datafusion/physical-plan/src/aggregates/hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/hash_stream.rs @@ -18,8 +18,8 @@ use datafusion_execution::{TaskContext, TryEmitter, async_try_stream}; use futures::stream::{Stream, StreamExt}; use super::aggregate_hash_table::{ - AggregateHashTable, ClusteredAggregateTableMetrics, FinalMarker, PartialMarker, - PartialSkipMarker, + AggregateHashTable, ClusteredAggregateTableMetrics, FinalMarker, + MaterializedAggregateOutput, PartialMarker, }; use super::order::GroupClusteringMode; use super::skip_partial::SkipAggregationProbe; @@ -89,8 +89,9 @@ use crate::{SendableRecordBatchStream, metrics}; /// crosses the configured threshold and all aggregate accumulators can convert /// raw inputs directly to partial state, the stream emits any already /// accumulated groups, then switches to a skip state. In that state, each -/// remaining input batch is converted directly to partial aggregate state rows -/// without inserting the rows into the grouped hash table. +/// input batch is converted directly to partial aggregate state rows without +/// inserting rows into the grouped hash table. Periodically the stream resumes +/// aggregation with an empty table to probe whether grouping is useful again. /// /// # Feature: Grouping Sets /// @@ -289,27 +290,37 @@ impl PartialHashAggregateStream { debug_assert!(hash_table.is_building()); let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); - let mut last_state = HandleInputResult::ProcessNext; while let Some(batch) = self.input.next().await.transpose()? { let timer = elapsed_compute.timer(); - last_state = self.handle_input_batch(&batch, &mut hash_table)?; + if self.should_skip_aggregation() { + if let Some(probe) = self.skip_aggregation_probe.as_mut() { + probe.record_skipped(&batch); + } + let output = hash_table.convert_batch_to_state(&batch)?; + timer.done(); + emitter + .emit(output.record_output(&self.baseline_metrics)) + .await; + continue; + } - match last_state { + let state = self.handle_input_batch(&batch, &mut hash_table)?; + drop(batch); + match state { HandleInputResult::ProcessNext => {} - HandleInputResult::ReachedLimit + HandleInputResult::ReachedLimit => break, + HandleInputResult::OOM | HandleInputResult::SwitchToSkipAggregation => { - break; - } - HandleInputResult::OOM => { let materialized_group_states = hash_table.take_state_batch()?.ok_or_else(|| { internal_datafusion_err!( - "Partial hash aggregate ran out of memory with no aggregated groups" + "Partial hash aggregate flushed with no aggregated groups" ) })?; - - self.early_emit_count.add(1); + if state == HandleInputResult::OOM { + self.early_emit_count.add(1); + } timer.done(); - self.emit_on_memory_pressure( + self.emit_partial_state( materialized_group_states, &mut emitter, hash_table.memory_size(), @@ -320,25 +331,11 @@ impl PartialHashAggregateStream { } let timer = elapsed_compute.timer(); - - let skip_hash_table = - if last_state == HandleInputResult::SwitchToSkipAggregation { - Some(hash_table.partial_skip_table()?) - } else { - self.close_input(); - - None - }; + self.close_input(); hash_table.start_output()?; - timer.done(); - self.produce_output(hash_table, &mut emitter).await?; - if let Some(hash_table) = skip_hash_table { - self.skip_rest_of_aggregation(hash_table, emitter).await?; - } - Ok(()) }) } @@ -416,47 +413,44 @@ impl PartialHashAggregateStream { } /// Emit a materialized partial-state batch in `batch_size` slices. - async fn emit_on_memory_pressure( + async fn emit_partial_state( &mut self, - mut remaining_groups: RecordBatch, + remaining_groups: RecordBatch, emitter: &mut TryEmitter, hash_table_mem_size: usize, ) -> Result<()> { - let remaining_groups_memory = remaining_groups.get_array_memory_size(); - - match self - .reservation - .try_resize(hash_table_mem_size + remaining_groups_memory) - { - Ok(()) => {} - Err(DataFusionError::ResourcesExhausted(_)) => { - self.reservation.try_resize(hash_table_mem_size)?; - self.reduction_factor.add_part(remaining_groups.num_rows()); - emitter - .emit(remaining_groups.record_output(&self.baseline_metrics)) - .await; - return Ok(()); + let mut output = MaterializedAggregateOutput::new(remaining_groups); + let last_batch = loop { + let Some(batch) = output.next_batch(self.batch_size)? else { + break None; + }; + if output.is_exhausted() { + break Some(batch); } - Err(error) => return Err(error), - } + match self + .reservation + .try_resize(hash_table_mem_size + output.memory_size()) + { + Ok(()) => {} + // As in terminal output, retain the previous reservation if this + // already-materialized output cannot fit, so draining can proceed. + Err(DataFusionError::ResourcesExhausted(_)) => {} + Err(error) => return Err(error), + } + self.reduction_factor.add_part(batch.num_rows()); + emitter + .emit(batch.record_output(&self.baseline_metrics)) + .await; + }; - while remaining_groups.num_rows() > self.batch_size { - let output = remaining_groups.slice(0, self.batch_size); - remaining_groups = remaining_groups.slice( - self.batch_size, - remaining_groups.num_rows() - self.batch_size, - ); - self.reduction_factor.add_part(output.num_rows()); + drop(output); + self.reservation.try_resize(hash_table_mem_size)?; + if let Some(batch) = last_batch { + self.reduction_factor.add_part(batch.num_rows()); emitter - .emit(output.record_output(&self.baseline_metrics)) + .emit(batch.record_output(&self.baseline_metrics)) .await; } - - self.reduction_factor.add_part(remaining_groups.num_rows()); - self.reservation.try_shrink(remaining_groups_memory)?; - emitter - .emit(remaining_groups.record_output(&self.baseline_metrics)) - .await; Ok(()) } @@ -495,34 +489,6 @@ impl PartialHashAggregateStream { timer = elapsed_compute.timer(); } } - - /// convert raw input directly to partial states. - async fn skip_rest_of_aggregation( - &mut self, - mut hash_table: AggregateHashTable, - mut emitter: TryEmitter, - ) -> Result<()> { - let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); - - while let Some(batch) = self.input.next().await.transpose()? { - if let Some(probe) = self.skip_aggregation_probe.as_mut() { - probe.record_skipped(&batch); - } - - let result = { - let _timer = elapsed_compute.timer(); - hash_table.convert_batch_to_state(&batch)? - }; - - emitter - .emit(result.record_output(&self.baseline_metrics)) - .await; - } - - self.close_input(); - - Ok(()) - } } impl FinalHashAggregateStream { @@ -897,7 +863,8 @@ mod tests { use crate::test::exec::BarrierExec; use arrow::array::{ - ArrayRef, AsArray, Int32Array, Int64Array, StringArray, StringViewArray, + Array, ArrayRef, AsArray, DictionaryArray, Int32Array, Int64Array, StringArray, + StringViewArray, }; use arrow::datatypes::{DataType, Field, Int32Type, Int64Type, Schema}; use datafusion_common::Result; @@ -1201,95 +1168,264 @@ mod tests { Ok(()) } - /// Under a memory limit that forces early emits before the probe threshold, - /// partial aggregation must skip unique keys but keep aggregating keys - /// that the table still reduces. + #[rstest::rstest] + #[case::unique((0, 40, 0), 1, 16, Some(64 * 1024), Some(24))] + #[case::repeated((0, 40, 0), 2, 16, Some(64 * 1024), Some(0))] + #[case::changing((0, 32, 256), 1, 1, None, None)] + #[case::late_changing((32, 160, 256), 1, 1, None, None)] + #[case::capped_retry((0, 195, 256), 1, 1, None, None)] + #[case::empty((0, 0, 0), 1, 1, None, Some(0))] + #[case::eof_after_probe((0, 1, 0), 1, 1, None, Some(0))] + #[case::eof_after_skip((0, 5, 0), 1, 1, None, Some(4))] + #[case::eof_after_reprobe((0, 6, 0), 1, 1, None, Some(4))] #[tokio::test] - async fn test_partial_aggregation_skip_probe_after_early_emits() -> Result<()> { + async fn test_partial_aggregation_skip_probe( + #[case] phases: (usize, usize, usize), + #[case] key_repeats: usize, + #[case] probe_batches: usize, + #[case] memory_limit: Option, + #[case] expected_skipped_batches: Option, + ) -> Result<()> { + let (useful_prefix, unique_batches, useful_suffix) = phases; + let total_batches = useful_prefix + unique_batches + useful_suffix; + let batch_rows = 128; + let schema = Arc::new(Schema::new(vec![ + Field::new("group_col", DataType::Int32, false), + Field::new("value_col", DataType::Int64, false), + ])); + let empty = RecordBatch::new_empty(Arc::clone(&schema)); + let mut batches = vec![empty.clone()]; + let mut expected = BTreeMap::::new(); + for batch in 0..total_batches { + let keys = (0..batch_rows) + .map(|row| { + if (useful_prefix..useful_prefix + unique_batches).contains(&batch) { + ((batch * batch_rows + row) / key_repeats) as i32 + } else { + (row % 8) as i32 + } + }) + .collect::>(); + let values = (0..batch_rows) + .map(|row| (batch * batch_rows + row) as i64) + .collect::>(); + for (&key, &value) in keys.iter().zip(&values) { + let entry = expected.entry(key).or_default(); + entry.0 += 1; + entry.1 += value; + } + batches.push(RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from(keys)), + Arc::new(Int64Array::from(values)), + ], + )?); + batches.push(empty.clone()); + } + let group_by = PhysicalGroupBy::new_single(vec![( + col("group_col", &schema)?, + "group_col".into(), + )]); + let expressions = [count_udaf(), sum_udaf()] + .into_iter() + .map(|udaf| { + AggregateExprBuilder::new( + Arc::clone(&udaf), + vec![col("value_col", &schema)?], + ) + .schema(Arc::clone(&schema)) + .alias(udaf.name()) + .build() + .map(Arc::new) + }) + .collect::>>()?; + let pool: Arc = match memory_limit { + Some(limit) => Arc::new(GreedyMemoryPool::new(limit)), + None => Arc::new(UnboundedMemoryPool::default()), + }; + let config = SessionConfig::new().with_batch_size(batch_rows).set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + probe_batches * batch_rows, + ); + let context = Arc::new( + TaskContext::default() + .with_runtime( + RuntimeEnvBuilder::default() + .with_memory_pool(Arc::clone(&pool)) + .build_arc()?, + ) + .with_session_config(config), + ); + let input = TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None)?; + let aggregate = AggregateExec::try_new( + AggregateMode::Partial, + group_by, + expressions, + vec![None; 2], + input, + schema, + )?; + let stream = aggregate.execute_typed(0, &context)?; + let output = collect(stream.into()).await?; + let mut actual = BTreeMap::::new(); + for batch in &output { + let keys = batch.column(0).as_primitive::(); + let counts = batch.column(1).as_primitive::(); + let sums = batch.column(2).as_primitive::(); + for row in 0..batch.num_rows() { + let entry = actual.entry(keys.value(row)).or_default(); + entry.0 += counts.value(row); + entry.1 += sums.value(row); + } + } + assert_eq!(actual, expected); + assert_eq!(pool.reserved(), 0); + let metrics = aggregate.metrics().unwrap(); + let metric = |name| { + metrics + .sum_by_name(name) + .map_or(0, |value| value.as_usize()) + }; + if memory_limit.is_some() { + assert!(metric("early_emit_count") > 0, "expected early emission"); + } + let skipped = metric("skipped_aggregation_rows"); + if let Some(expected) = expected_skipped_batches { + assert_eq!(skipped, expected * batch_rows); + } else { + let output_rows: usize = output.iter().map(RecordBatch::num_rows).sum(); + assert!( + output_rows < total_batches * batch_rows / 2, + "repeated keys should be reduced after skipping: {output_rows} output rows" + ); + assert!( + skipped > 20 * batch_rows, + "ineffective probes must return to skipping" + ); + } + Ok(()) + } + + #[rstest::rstest] + #[case(true, 0)] + #[case(false, 0)] + #[case(true, 200)] + #[tokio::test] + async fn test_partial_aggregation_reprobes_memory_pressure( + #[case] release_pressure: bool, + #[case] release_after_skipped_batches: usize, + ) -> Result<()> { let schema = Arc::new(Schema::new(vec![ Field::new("group_col", DataType::Int32, false), Field::new("value_col", DataType::Int64, false), ])); let batch_rows = 256; - let num_batches = 40; - let probe_batches = 16; + let num_batches = if release_after_skipped_batches == 0 { + 400 + } else { + 1200 + }; + let num_groups = 2048; + let batches = (0..num_batches) + .map(|batch| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from_iter_values((0..batch_rows).map( + |row| ((batch * batch_rows + row) % num_groups) as i32, + ))), + Arc::new(Int64Array::from(vec![1; batch_rows])), + ], + ) + }) + .collect::, _>>()?; + let pool: Arc = Arc::new(GreedyMemoryPool::new(512 * 1024)); + let pressure = MemoryConsumer::new("other operator").register(&pool); + pressure.try_grow(496 * 1024)?; + let runtime = RuntimeEnvBuilder::default() + .with_memory_pool(Arc::clone(&pool)) + .build_arc()?; + let config = SessionConfig::new().with_batch_size(batch_rows).set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + 16 * batch_rows, + ); + let task_ctx = Arc::new( + TaskContext::default() + .with_runtime(runtime) + .with_session_config(config), + ); + let input = TestMemoryExec::try_new_exec( + std::slice::from_ref(&batches), + Arc::clone(&schema), + None, + )?; let group_by = PhysicalGroupBy::new_single(vec![( col("group_col", &schema)?, "group_col".to_string(), )]); - let aggr_expr = vec![Arc::new( + let count = AggregateExprBuilder::new(count_udaf(), vec![col("value_col", &schema)?]) .schema(Arc::clone(&schema)) .alias("count_value") - .build()?, - )]; - - // Each batch has new keys, each repeated `key_repeats` times. - let ones: ArrayRef = Arc::new(Int64Array::from(vec![1; batch_rows])); - let skipped_unique = (num_batches - probe_batches) * batch_rows; - for (key_repeats, expected_skipped) in [(1, skipped_unique), (2, 0)] { - let batches = (0..num_batches) - .map(|i| { - let start = (i * batch_rows / key_repeats) as i32; - RecordBatch::try_new( - Arc::clone(&schema), - vec![ - Arc::new(Int32Array::from_iter_values( - (0..batch_rows).map(|r| start + (r / key_repeats) as i32), - )), - Arc::clone(&ones), - ], - ) - }) - .collect::, _>>()?; - - let session_config = - SessionConfig::new().with_batch_size(batch_rows).set_usize( - "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", - probe_batches * batch_rows, - ); - let runtime = RuntimeEnvBuilder::default() - .with_memory_limit(64 * 1024, 1.0) - .build_arc()?; - let task_ctx = Arc::new( - TaskContext::default() - .with_runtime(runtime) - .with_session_config(session_config), + .build()?; + let aggregate_exec = AggregateExec::try_new( + AggregateMode::Partial, + group_by, + vec![Arc::new(count)], + vec![None], + input, + schema, + )?; + let mut stream = aggregate_exec.execute(0, task_ctx)?; + let metrics = aggregate_exec.metrics().unwrap(); + let mut counts = BTreeMap::::new(); + let mut output_rows = 0; + while let Some(batch) = stream.next().await.transpose()? { + let keys = batch.column(0).as_primitive::(); + let values = batch.column(1).as_primitive::(); + for row in 0..batch.num_rows() { + *counts.entry(keys.value(row)).or_default() += values.value(row); + } + output_rows += batch.num_rows(); + if release_pressure + && metrics + .sum_by_name("skipped_aggregation_rows") + .is_some_and(|m| { + m.as_usize() > release_after_skipped_batches * batch_rows + }) + { + pressure.free(); + } + } + assert_eq!(counts.len(), num_groups); + assert!( + counts + .values() + .all(|&count| count == (num_batches * batch_rows / num_groups) as i64) + ); + let skipped = metrics + .sum_by_name("skipped_aggregation_rows") + .unwrap() + .as_usize(); + assert!( + skipped > 0, + "memory pressure must initially trigger skipping" + ); + if release_pressure { + assert!( + output_rows < num_batches * batch_rows * 3 / 4, + "aggregation should recover after memory is released: {output_rows} output rows" ); - let input = TestMemoryExec::try_new_exec( - std::slice::from_ref(&batches), - Arc::clone(&schema), - None, - )?; - let aggregate_exec = AggregateExec::try_new( - AggregateMode::Partial, - group_by.clone(), - aggr_expr.clone(), - vec![None], - input, - Arc::clone(&schema), - )?; - - let stream = aggregate_exec.execute_typed(0, &task_ctx)?; - let output = collect(stream.into()).await?; - // Every input row is counted once, whether skipped or aggregated. - let counted: i64 = output - .iter() - .filter_map(|b| { - arrow::compute::sum(b.column(1).as_primitive::()) - }) - .sum(); - assert_eq!(counted, (num_batches * batch_rows) as i64); - - let metrics = aggregate_exec.metrics().unwrap(); - let metric = |name| metrics.sum_by_name(name).map_or(0, |m| m.as_usize()); - assert!(metric("early_emit_count") > 0, "expected early emits"); - assert_eq!( - metric("skipped_aggregation_rows"), - expected_skipped, - "key_repeats={key_repeats}" + } else { + assert!( + output_rows > num_batches * batch_rows * 3 / 4, + "persistent pressure must still prevent effective reduction: {output_rows} output rows" ); } + drop(stream); + pressure.free(); + assert_eq!(pool.reserved(), 0); Ok(()) } @@ -1298,12 +1434,13 @@ mod tests { /// /// The input does not signal end-of-stream until `wait_finish` is called /// on the returned [`BarrierExec`], so any output produced before that can - /// only come from the memory pressure emission path (normal output waits - /// for all input). Skip partial aggregation is disabled for the same reason. + /// only come from early emission or switching to skip mode (normal output + /// waits for all input). fn partial_stream_under_memory_limit( memory_limit: usize, batch_size: usize, num_groups: usize, + skip_ratio_threshold: f64, ) -> Result<( SendableRecordBatchStream, Arc, @@ -1324,8 +1461,21 @@ mod tests { Arc::new(Int64Array::from(values)), ], )?; - let input_partitions = vec![vec![batch]]; + partial_stream_from_batch(memory_limit, batch_size, batch, skip_ratio_threshold) + } + fn partial_stream_from_batch( + memory_limit: usize, + batch_size: usize, + batch: RecordBatch, + skip_ratio_threshold: f64, + ) -> Result<( + SendableRecordBatchStream, + Arc, + Arc, + )> { + let schema = batch.schema(); + let input_partitions = vec![vec![batch]]; let runtime = RuntimeEnvBuilder::default() .with_memory_limit(memory_limit, 1.0) .build_arc()?; @@ -1338,9 +1488,13 @@ mod tests { "datafusion.execution.batch_size", &datafusion_common::ScalarValue::UInt64(Some(batch_size as u64)), ) + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + batch_size, + ) .set( "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", - &datafusion_common::ScalarValue::Float64(Some(1.0)), + &datafusion_common::ScalarValue::Float64(Some(skip_ratio_threshold)), ); task_ctx = task_ctx.with_session_config(session_config); let task_ctx = Arc::new(task_ctx); @@ -1376,6 +1530,238 @@ mod tests { Ok((stream, input, runtime)) } + #[rstest::rstest] + #[tokio::test] + async fn test_partial_flush_releases_input_batch( + #[values(0.8, 1.0)] skip_ratio: f64, + ) -> Result<()> { + let schema = Arc::new(Schema::new(vec![ + Field::new("group_col", DataType::Int32, false), + Field::new("value_col", DataType::Int64, false), + ])); + let values = Arc::new(Int64Array::from(vec![1; 4096])); + let input_values = Arc::downgrade(&values); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int32Array::from_iter_values(0..4096)), values], + )?; + let input = TestMemoryExec::try_new_exec(&[vec![]], Arc::clone(&schema), None)?; + let aggregate = AggregateExec::try_new( + AggregateMode::Partial, + PhysicalGroupBy::new_single(vec![( + col("group_col", &schema)?, + "group_col".into(), + )]), + vec![Arc::new( + AggregateExprBuilder::new(count_udaf(), vec![col("value_col", &schema)?]) + .schema(Arc::clone(&schema)) + .alias("count_value") + .build()?, + )], + vec![None], + input, + Arc::clone(&schema), + )?; + let config = SessionConfig::new() + .with_batch_size(128) + .set( + "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", + &datafusion_common::ScalarValue::Float64(Some(skip_ratio)), + ) + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + 128, + ); + let runtime = RuntimeEnvBuilder::default() + .with_memory_limit(32 * 1024, 1.0) + .build_arc()?; + let context = Arc::new( + TaskContext::default() + .with_runtime(Arc::clone(&runtime)) + .with_session_config(config), + ); + let mut partial = PartialHashAggregateStream::new(&aggregate, &context, 0)?; + // Move the batch into the stream so no source plan keeps another copy. + partial.input = Box::pin(RecordBatchStreamAdapter::new( + schema, + futures::stream::iter(vec![Ok(batch)]), + )); + let mut stream = partial.into_stream(); + assert!(input_values.upgrade().is_some()); + let first = stream.next().await.unwrap()?; + assert_eq!(first.num_rows(), 128); + assert!(input_values.upgrade().is_none()); + drop(stream); + assert_eq!(runtime.memory_pool.reserved(), 0); + Ok(()) + } + + #[rstest::rstest] + #[case::skip(0.8, 1_048_576, false)] + #[case::skip_tight_pool(0.8, 32_768, false)] + #[case::early_emit(1.0, 100_000, false)] + #[case::early_emit_tight_pool(1.0, 32_768, false)] + #[case::eof(1.0, 1_048_576, true)] + #[tokio::test] + async fn test_partial_flush_compacts_dictionary_keys( + #[case] skip_ratio: f64, + #[case] memory_limit: usize, + #[case] finish_input: bool, + #[values(false, true)] cancel_after_first: bool, + ) -> Result<()> { + let num_groups = 4096; + let batch_size = 128; + let keys = DictionaryArray::::try_new( + Int32Array::from_iter( + (0..num_groups).map(|i| (i + 1 < num_groups).then_some(i as i32)), + ), + Arc::new(StringArray::from_iter_values( + (0..num_groups).map(|i| format!("key_{i:04}")), + )), + )?; + let schema = Arc::new(Schema::new(vec![ + Field::new("group_col", keys.data_type().clone(), true), + Field::new("value_col", DataType::Int64, false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(keys), + Arc::new(Int64Array::from(vec![1; num_groups])), + ], + )?; + let (mut stream, input, runtime) = + partial_stream_from_batch(memory_limit, batch_size, batch, skip_ratio)?; + if finish_input { + input.wait_finish().await; + } + let first = tokio::time::timeout(Duration::from_secs(5), stream.next()) + .await + .expect("partial output should be available") + .expect("partial output")?; + if cancel_after_first { + if memory_limit == 1_048_576 { + assert!(runtime.memory_pool.reserved() > 0); + } + drop(first); + drop(stream); + assert_eq!(runtime.memory_pool.reserved(), 0); + return Ok(()); + } + if !finish_input { + input.wait_finish().await; + } + let mut batches = vec![first]; + batches.extend(collect(stream).await?); + let mut counts = BTreeMap::new(); + for batch in batches { + assert!(batch.num_rows() <= batch_size); + let keys = batch.column(0).as_dictionary::(); + assert!(keys.values().len() <= batch_size); + let decoded = arrow::compute::cast(keys, &DataType::Utf8)?; + let decoded = decoded.as_string::(); + let values = batch.column(1).as_primitive::(); + for row in 0..batch.num_rows() { + let key = (!decoded.is_null(row)).then(|| decoded.value(row).to_owned()); + *counts.entry(key).or_insert(0) += values.value(row); + } + } + assert_eq!(counts.len(), num_groups); + assert_eq!(counts.get(&None), Some(&1)); + for i in 0..num_groups - 1 { + assert_eq!(counts.get(&Some(format!("key_{i:04}"))), Some(&1)); + } + assert_eq!(runtime.memory_pool.reserved(), 0); + Ok(()) + } + + #[rstest::rstest] + #[tokio::test] + async fn test_partial_flush_allows_downstream_progress( + #[values(0.8, 1.0)] skip_ratio: f64, + ) -> Result<()> { + use crate::filter::FilterExec; + use datafusion_execution::disk_manager::{DiskManagerBuilder, DiskManagerMode}; + use datafusion_expr::Operator; + use datafusion_physical_expr::expressions::{BinaryExpr, lit}; + + let schema = Arc::new(Schema::new(vec![ + Field::new("group_col", DataType::Int32, false), + Field::new("value_col", DataType::Int64, false), + ])); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from_iter_values(0..4096)), + Arc::new(Int64Array::from(vec![1; 4096])), + ], + )?; + let input = + TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?; + let groups = PhysicalGroupBy::new_single(vec![( + col("group_col", &schema)?, + "group_col".into(), + )]); + let expressions = vec![Arc::new( + AggregateExprBuilder::new(count_udaf(), vec![col("value_col", &schema)?]) + .schema(Arc::clone(&schema)) + .alias("count_value") + .build()?, + )]; + let partial = Arc::new(AggregateExec::try_new( + AggregateMode::Partial, + groups.clone(), + expressions.clone(), + vec![None], + input, + Arc::clone(&schema), + )?); + let predicate = Arc::new(BinaryExpr::new( + col("group_col", &partial.schema())?, + Operator::Eq, + lit(0i32), + )); + // Keep this filter above Partial and emit immediately, so Final must + // allocate while Partial still holds the remainder of its flush. + let filtered = + Arc::new(FilterExec::try_new(predicate, partial)?.with_batch_size(1)?); + let final_aggregate = AggregateExec::try_new( + AggregateMode::Final, + groups.as_final(), + expressions, + vec![None], + filtered, + schema, + )?; + let runtime = RuntimeEnvBuilder::default() + .with_memory_limit(32 * 1024, 1.0) + .with_disk_manager_builder( + DiskManagerBuilder::default().with_mode(DiskManagerMode::Disabled), + ) + .build_arc()?; + let config = SessionConfig::new() + .with_batch_size(128) + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + 128, + ) + .set( + "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold", + &datafusion_common::ScalarValue::Float64(Some(skip_ratio)), + ); + let context = Arc::new( + TaskContext::default() + .with_runtime(Arc::clone(&runtime)) + .with_session_config(config), + ); + let output = collect(final_aggregate.execute(0, context)?).await?; + assert_eq!(output.iter().map(RecordBatch::num_rows).sum::(), 1); + assert_eq!(output[0].column(0).as_primitive::().value(0), 0); + assert_eq!(output[0].column(1).as_primitive::().value(0), 1); + assert_eq!(runtime.memory_pool.reserved(), 0); + Ok(()) + } + #[tokio::test] async fn test_partial_hash_stream_accounts_held_batch_on_memory_pressure_while_slicing() -> Result<()> { @@ -1383,7 +1769,7 @@ mod tests { let num_groups = 4 * batch_size; let memory_limit = 100 * 1024; let (mut stream, input, runtime) = - partial_stream_under_memory_limit(memory_limit, batch_size, num_groups)?; + partial_stream_under_memory_limit(memory_limit, batch_size, num_groups, 1.0)?; let first = tokio::time::timeout(Duration::from_secs(5), stream.next()) .await @@ -1422,28 +1808,31 @@ mod tests { } #[tokio::test] - async fn test_partial_hash_stream_emits_whole_batch_when_held_batch_does_not_fit() - -> Result<()> { + async fn test_partial_hash_stream_slices_when_held_batch_does_not_fit() -> Result<()> + { let batch_size = 1024; let num_groups = 4 * batch_size; let memory_limit = 32 * 1024; let (mut stream, input, runtime) = - partial_stream_under_memory_limit(memory_limit, batch_size, num_groups)?; + partial_stream_under_memory_limit(memory_limit, batch_size, num_groups, 1.0)?; let first = tokio::time::timeout(Duration::from_secs(5), stream.next()) .await .expect("early emit should occur") .expect("stream ended early")?; - assert_eq!(first.num_rows(), num_groups); + assert_eq!(first.num_rows(), batch_size); assert!(first.get_array_memory_size() > memory_limit); assert!(runtime.memory_pool.reserved() < first.get_array_memory_size()); input.wait_finish().await; let mut total_rows = first.num_rows(); while let Some(batch) = stream.next().await { - total_rows += batch?.num_rows(); + let batch = batch?; + assert!(batch.num_rows() <= batch_size); + total_rows += batch.num_rows(); } assert_eq!(total_rows, num_groups); + assert_eq!(runtime.memory_pool.reserved(), 0); Ok(()) } @@ -1455,7 +1844,7 @@ mod tests { let num_groups = num_slices * batch_size; let memory_limit = 100 * 1024; let (mut stream, input, runtime) = - partial_stream_under_memory_limit(memory_limit, batch_size, num_groups)?; + partial_stream_under_memory_limit(memory_limit, batch_size, num_groups, 1.0)?; let mut held_size = 0; for slice_idx in 0..num_slices { diff --git a/datafusion/physical-plan/src/aggregates/skip_partial.rs b/datafusion/physical-plan/src/aggregates/skip_partial.rs index a9d56e9b1db79..f7f6288ade413 100644 --- a/datafusion/physical-plan/src/aggregates/skip_partial.rs +++ b/datafusion/physical-plan/src/aggregates/skip_partial.rs @@ -6,9 +6,18 @@ use arrow::record_batch::RecordBatch; use crate::metrics; +// Retry promptly at first, then limit repeated work on ineffective aggregation +// without allowing an indefinitely growing delay before conditions are checked. +const INITIAL_REPROBE_SKIP_MULTIPLIER: usize = 4; +const MAX_REPROBE_SKIP_MULTIPLIER: usize = 16; + /// Tracks if the aggregate should skip partial aggregations /// -/// Used by [`crate::aggregates::hash_stream::PartialHashAggregateStream`]. +/// After an ineffective probe, skip four times the larger of the row threshold +/// and the triggering batch. Consecutive ineffective probes double this interval +/// up to sixteen times; a useful decision resets the multiplier to four. +/// Probe counters include groups recreated after early emission and remain +/// cumulative until a skip interval ends. pub(super) struct SkipAggregationProbe { // ======================================================================== // PROPERTIES: @@ -28,19 +37,9 @@ pub(super) struct SkipAggregationProbe { // Fields changes during execution. Can be buffer, or state flags that // influence the execution in the parent aggregate stream // ======================================================================== - /// Number of processed input rows (updated during probing) - input_rows: usize, - /// Number of groups created for `input_rows` (updated during probing). - /// A key that returns after an early emit is counted again, so this is the - /// number of rows the stream outputs for `input_rows`. - num_groups: usize, - - /// Flag indicating further data aggregation may be skipped (decision made - /// when probing complete) - should_skip: bool, - /// Flag indicating further updates of `SkipAggregationProbe` state won't - /// make any effect (set either while probing or on probing completion) - is_locked: bool, + state: ProbeState, + /// Multiplier for the next skip window; reset after a useful probe. + skip_multiplier: usize, // ======================================================================== // METRICS: @@ -54,6 +53,16 @@ pub(super) struct SkipAggregationProbe { skipped_aggregation_rows: metrics::Count, } +enum ProbeState { + Probing { + input_rows: usize, + num_groups: usize, + }, + Skipping { + rows_left: usize, + }, +} + impl SkipAggregationProbe { pub(super) fn new( probe_rows_threshold: usize, @@ -61,43 +70,69 @@ impl SkipAggregationProbe { skipped_aggregation_rows: metrics::Count, ) -> Self { Self { - input_rows: 0, - num_groups: 0, probe_rows_threshold, probe_ratio_threshold, - should_skip: false, - is_locked: false, + state: ProbeState::Probing { + input_rows: 0, + num_groups: 0, + }, + skip_multiplier: INITIAL_REPROBE_SKIP_MULTIPLIER, skipped_aggregation_rows, } } - /// Updates `SkipAggregationProbe` state: - /// - adds the input rows of a batch and the groups it created - /// - on `probe_rows_threshold` exceeded calculates - /// aggregation ratio and sets `should_skip` flag - /// - if `should_skip` is set, locks further state updates + /// Adds a batch's input rows and newly created groups to the active probe. pub(super) fn update_state(&mut self, input_rows: usize, new_groups: usize) { - if self.is_locked { + let ProbeState::Probing { + input_rows: total_rows, + num_groups, + } = &mut self.state + else { return; - } - self.input_rows += input_rows; - self.num_groups += new_groups; - if self.input_rows >= self.probe_rows_threshold { - self.should_skip = self.num_groups as f64 / self.input_rows as f64 - > self.probe_ratio_threshold; - // Set is_locked to true only if we have decided to skip, otherwise we can try to skip - // during processing the next record_batch. - self.is_locked = self.should_skip; + }; + *total_rows += input_rows; + *num_groups += new_groups; + if *total_rows > 0 && *total_rows >= self.probe_rows_threshold { + if *num_groups as f64 / *total_rows as f64 > self.probe_ratio_threshold { + // A long useful phase must not delay recovery after a later skip. + // Account for batches larger than the configured probe window. + self.state = ProbeState::Skipping { + rows_left: self + .probe_rows_threshold + .max(input_rows) + .saturating_mul(self.skip_multiplier), + }; + self.skip_multiplier = self + .skip_multiplier + .saturating_mul(2) + .min(MAX_REPROBE_SKIP_MULTIPLIER); + } else { + self.skip_multiplier = INITIAL_REPROBE_SKIP_MULTIPLIER; + } } } pub(super) fn should_skip(&self) -> bool { - self.should_skip + matches!(self.state, ProbeState::Skipping { .. }) } /// Record the number of rows that were output directly without aggregation pub(super) fn record_skipped(&mut self, batch: &RecordBatch) { self.skipped_aggregation_rows.add(batch.num_rows()); + // No non-empty probe can satisfy a non-positive ratio threshold. + if self.probe_ratio_threshold <= 0.0 { + return; + } + let ProbeState::Skipping { rows_left } = &mut self.state else { + return; + }; + *rows_left = rows_left.saturating_sub(batch.num_rows()); + if *rows_left == 0 { + self.state = ProbeState::Probing { + input_rows: 0, + num_groups: 0, + }; + } } } @@ -105,6 +140,72 @@ impl SkipAggregationProbe { mod tests { use super::*; + use std::sync::Arc; + + use arrow::array::Int32Array; + use arrow::datatypes::{DataType, Field, Schema}; + + fn skip_rows(probe: &mut SkipAggregationProbe, rows: usize) { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("key", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![0; rows]))], + ) + .unwrap(); + probe.record_skipped(&batch); + } + + #[rstest::rstest] + #[case::zero_threshold(0, 8)] + #[case::exact_window(8, 8)] + #[case::oversized_batch(8, 32)] + fn test_reprobe_backoff_is_bounded( + #[case] probe_rows_threshold: usize, + #[case] batch_rows: usize, + ) { + let mut probe = + SkipAggregationProbe::new(probe_rows_threshold, 0.8, metrics::Count::new()); + for multiplier in [4, 8, 16, 16, 16] { + probe.update_state(batch_rows, batch_rows); + assert!(probe.should_skip()); + skip_rows(&mut probe, batch_rows * multiplier - 1); + assert!(probe.should_skip()); + skip_rows(&mut probe, 0); + assert!(probe.should_skip()); + skip_rows(&mut probe, 1); + assert!(!probe.should_skip()); + probe.update_state(0, 0); + assert!(!probe.should_skip()); + } + } + + #[test] + fn test_reprobe_backoff_resets_after_useful_window() { + let mut probe = SkipAggregationProbe::new(8, 0.8, metrics::Count::new()); + for multiplier in [4, 8, 16] { + probe.update_state(8, 8); + skip_rows(&mut probe, 8 * multiplier); + assert!(!probe.should_skip()); + } + + // A short useful prefix does not establish that the probe is useful. + probe.update_state(4, 2); + probe.update_state(12, 12); + assert!(probe.should_skip()); + skip_rows(&mut probe, 16 * 12 - 1); + assert!(probe.should_skip()); + skip_rows(&mut probe, 1); + assert!(!probe.should_skip()); + + probe.update_state(8, 4); + assert!(!probe.should_skip()); + probe.update_state(32, 32); + assert!(probe.should_skip()); + skip_rows(&mut probe, 4 * 32 - 1); + assert!(probe.should_skip()); + skip_rows(&mut probe, 1); + assert!(!probe.should_skip()); + } + #[test] fn test_skip_aggregation_probe_equality_does_not_skip() { // When num_groups / input_rows == probe_ratio_threshold, the `>` boundary diff --git a/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt b/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt index 09ed518a22603..f2590d21de6fb 100644 --- a/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt +++ b/datafusion/sqllogictest/test_files/aggregate_skip_partial.slt @@ -43,12 +43,13 @@ SELECT CASE WHEN c1='a' OR c1='b' THEN TRUE WHEN c1='c' OR c1='d' THEN FALSE ELSE NULL END as v3 FROM aggregate_test_100; -# Prepare settings to skip partial aggregation from the beginning +# A small positive ratio forces skipping and re-probing on these fixtures. +# Ratio-zero permanent skipping is covered by the other aggregate/filter suites. statement ok set datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 0; statement ok -set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.0; +set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.000000001; statement ok set datafusion.execution.target_partitions = 2; @@ -218,12 +219,12 @@ reset datafusion.execution.skip_partial_aggregation_probe_ratio_threshold; statement ok reset datafusion.execution.skip_partial_aggregation_probe_rows_threshold; -# Prepare settings to always skip aggregation after couple of batches +# Re-probe within each partition, including AVG and filtered accumulators below. statement ok -set datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 10; +set datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 0; statement ok -set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.0; +set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.000000001; statement ok set datafusion.execution.target_partitions = 2; @@ -756,7 +757,7 @@ statement ok set datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 0; statement ok -set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.0; +set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.000000001; statement ok set datafusion.execution.target_partitions = 1; @@ -817,7 +818,7 @@ statement ok set datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 0; statement ok -set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.0; +set datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.000000001; statement ok set datafusion.execution.target_partitions = 2; diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index e761260a82c5a..7eee031433415 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -442,8 +442,8 @@ datafusion.execution.parquet.writer_version 1.0 (writing) Sets parquet writer ve datafusion.execution.perfect_hash_join_min_key_density 0.15 The minimum required density of join keys on the build side to consider a perfect hash join (see `HashJoinExec` for more details). Density is calculated as: `(number of rows) / (max_key - min_key + 1)`. A perfect hash join may be used if the actual key density > this value. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future. datafusion.execution.perfect_hash_join_small_build_threshold 1024 A perfect hash join (see `HashJoinExec` for more details) will be considered if the range of keys (max - min) on the build side is < this threshold. This provides a fast path for joins with very small key ranges, bypassing the density check. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future. datafusion.execution.planning_concurrency 13 Fan-out during initial physical planning. This is mostly use to plan `UNION` children in parallel. Defaults to the number of CPU cores on the system -datafusion.execution.skip_partial_aggregation_probe_ratio_threshold 0.8 Aggregation ratio (number of groups the partial aggregation creates / number of input rows) threshold for skipping partial aggregation. A key that returns after an early emit under memory pressure counts again. If the value is greater then partial aggregation will skip aggregation for further input -datafusion.execution.skip_partial_aggregation_probe_rows_threshold 100000 Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode +datafusion.execution.skip_partial_aggregation_probe_ratio_threshold 0.8 Aggregation ratio (number of groups the partial aggregation creates / number of input rows) threshold for skipping partial aggregation. A key that returns after an early emit under memory pressure counts again. If the ratio exceeds this threshold, partial aggregation bypasses grouping temporarily, then probes again with an empty table. Values at or above 1.0 disable skipping; non-positive values keep skipping once it starts. +datafusion.execution.skip_partial_aggregation_probe_rows_threshold 100000 Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode. datafusion.execution.skip_physical_aggregate_schema_check false When set to true, skips verifying that the schema produced by planning the input of `LogicalPlan::Aggregate` exactly matches the schema of the input plan. When set to false, if the schema does not match exactly (including nullability and metadata), a planning error will be raised. This is used to workaround bugs in the planner that are now caught by the new schema verification step. datafusion.execution.soft_max_bytes_per_output_file 4294967295 Target encoded size in bytes of output files when writing multiple. Writers asynchronously report the cumulative encoded size as they process RecordBatches. The final file size may exceed this limit due to batches buffered before the limit is observed, the size of a batch, and file metadata written when the file is finalized. datafusion.execution.soft_max_rows_per_output_file 50000000 Target number of rows in output files when writing multiple. This is a soft max, so it can be exceeded slightly. There also will be one file smaller than the limit if the total number of rows written is not roughly divisible by the soft max diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index 47c196b21b250..2bb9e12fc2a27 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -133,8 +133,8 @@ The following configuration settings are available: | datafusion.execution.split_file_groups_by_statistics | false | Attempt to eliminate sorts by packing & sorting files with non-overlapping statistics into the same file groups. Currently experimental | | datafusion.execution.keep_partition_by_columns | false | Should DataFusion keep the columns used for partition_by in the output RecordBatches | | datafusion.execution.enable_file_stream_work_stealing | true | When `true` (the default), DataFusion's built-in file scans dynamically rebalance files across partitions at query execution time: a partition that goes idle reads files (or byte-range morsels) originally assigned to a sibling partition, which keeps all partitions busy in a single process. Executors that depend on the plan-time partition assignment — such as Ballista and datafusion-distributed, which run each partition as an isolated task and never poll the siblings — should set this to `false` so each partition reads only its own file group and no runtime reassignment occurs. | -| datafusion.execution.skip_partial_aggregation_probe_ratio_threshold | 0.8 | Aggregation ratio (number of groups the partial aggregation creates / number of input rows) threshold for skipping partial aggregation. A key that returns after an early emit under memory pressure counts again. If the value is greater then partial aggregation will skip aggregation for further input | -| datafusion.execution.skip_partial_aggregation_probe_rows_threshold | 100000 | Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode | +| datafusion.execution.skip_partial_aggregation_probe_ratio_threshold | 0.8 | Aggregation ratio (number of groups the partial aggregation creates / number of input rows) threshold for skipping partial aggregation. A key that returns after an early emit under memory pressure counts again. If the ratio exceeds this threshold, partial aggregation bypasses grouping temporarily, then probes again with an empty table. Values at or above 1.0 disable skipping; non-positive values keep skipping once it starts. | +| datafusion.execution.skip_partial_aggregation_probe_rows_threshold | 100000 | Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode. | | 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. Note: this option currently only applies to the symmetric hash join. | | 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. |