From a45d62e4d7ba39fb690b97bba341c947ce7b73e9 Mon Sep 17 00:00:00 2001 From: benjibun <226082140+benjibunbun@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:30:08 +1100 Subject: [PATCH 1/2] fix: re-probe partial aggregation after skipping Generated-by: Codex --- datafusion/common/src/config.rs | 10 +- .../core/benches/aggregate_query_sql.rs | 147 +++++- .../src/aggregates/aggregate_argument.rs | 16 - .../aggregates/aggregate_hash_table/common.rs | 36 -- .../aggregate_hash_table/common_clustered.rs | 8 +- .../aggregates/aggregate_hash_table/mod.rs | 4 +- .../aggregate_hash_table/partial_table.rs | 50 +- .../src/aggregates/grouped_hash_stream.rs | 3 + .../src/aggregates/hash_stream.rs | 443 +++++++++++++++--- .../src/aggregates/skip_partial.rs | 106 ++++- .../test_files/aggregate_partial_reprobe.slt | 86 ++++ .../test_files/information_schema.slt | 4 +- docs/source/user-guide/configs.md | 4 +- 13 files changed, 727 insertions(+), 190 deletions(-) create mode 100644 datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index 841d971016b04..cd380e0f1e971 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -1146,12 +1146,16 @@ 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. + /// Skipping initially lasts four times the larger of this threshold and the + /// triggering batch's row count. Consecutive unsuccessful probes increase + /// the multiplier to eight and then sixteen. A useful probe resets it to four. 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 811c9a23ab52e..4a93f8c9f4c13 100644 --- a/datafusion/core/benches/aggregate_query_sql.rs +++ b/datafusion/core/benches/aggregate_query_sql.rs @@ -8,12 +8,14 @@ use arrow::array::{Array, AsArray}; use arrow::datatypes::{ DataType, Int32Type, Int64Type, IntervalUnit, TimeUnit, TimestampNanosecondType, }; -use criterion::{Criterion, criterion_group, criterion_main}; +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use data_utils::create_table_provider; use datafusion::datasource::MemTable; use datafusion::error::Result; use datafusion::execution::context::{SessionConfig, SessionContext}; -use datafusion::physical_plan::{collect, displayable}; +use datafusion::physical_plan::aggregates::order::GroupClusteringMode; +use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode}; +use datafusion::physical_plan::{ExecutionPlan, collect, displayable}; use datafusion_expr::col; use parking_lot::Mutex; use std::hint::black_box; @@ -549,5 +551,144 @@ async fn fully_ordered_context( Ok(Arc::new(Mutex::new(ctx))) } -criterion_group!(benches, criterion_benchmark, fully_ordered); +/// 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"), + 2_000_000, + true, + ), + ( + "unique_long", + 10_000_000, + Some("value * 104729 % 10000000"), + 10_000_000, + true, + ), + ( + "changing", + 2_000_000, + Some("CASE WHEN value <= 400000 THEN value ELSE value % 1000 END"), + 400_001, + true, + ), + ( + "late_change", + 12_000_000, + Some( + "CASE WHEN value <= 8000000 THEN value * 104729 % 8000000 \ + ELSE value % 1000 END", + ), + 8_000_000, + true, + ), + ("repeated", 2_000_000, Some("value % 1000"), 1_000, false), + ("ungrouped", 2_000_000, None, 1, false), + ]; + let rt = Runtime::new().unwrap(); + let mut group = c.benchmark_group("partial_aggregation_reprobe"); + for (implementation, enable_migration) in [("current", true), ("legacy", false)] { + let mut config = SessionConfig::new() + .with_target_partitions(2) + .with_batch_size(8192); + let execution = &mut config.options_mut().execution; + execution.enable_migration_aggregate = enable_migration; + 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, expected_groups, expect_skip) 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})" + ), + }; + let mut checked = false; + group.bench_function(BenchmarkId::new(implementation, name), |b| { + // Criterion applies its filter before invoking this closure. + // Validate only selected cases, outside the timed iterations. + if !checked { + let (partial_rows, skipped_rows) = rt + .block_on(check_partial_reprobe( + &ctx.lock(), + &sql, + input_rows, + expected_groups, + expect_skip, + )) + .unwrap(); + eprintln!( + "{implementation}/{name}: partial_output_rows={partial_rows}, \ + skipped_aggregation_rows={skipped_rows}" + ); + checked = true; + } + b.iter(|| query(ctx.clone(), &rt, &sql)); + }); + } + } + group.finish(); +} + +async fn check_partial_reprobe( + ctx: &SessionContext, + sql: &str, + input_rows: usize, + expected_groups: usize, + expect_skip: bool, +) -> Result<(usize, usize)> { + let plan = ctx.sql(sql).await?.create_physical_plan().await?; + let partial = find_partial_aggregate(&plan).expect("expected partial aggregation"); + assert_eq!(partial.group_clustering_mode(), &GroupClusteringMode::None); + let batches = collect(Arc::clone(&plan), ctx.task_ctx()).await?; + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + expected_groups + ); + let total = batches + .iter() + .map(|batch| { + let sums = batch + .column(batch.num_columns() - 1) + .as_primitive::(); + assert_eq!(sums.null_count(), 0); + sums.values().iter().sum::() + }) + .sum::(); + let input_rows = i64::try_from(input_rows).unwrap(); + assert_eq!(total, input_rows * (input_rows + 1) / 2); + + let metrics = partial.metrics().expect("expected partial metrics"); + let partial_rows = metrics.output_rows().expect("expected partial output rows"); + let skipped_rows = metrics + .sum_by_name("skipped_aggregation_rows") + .map(|value| value.as_usize()) + .unwrap_or(0); + assert_eq!(skipped_rows > 0, expect_skip); + Ok((partial_rows, skipped_rows)) +} + +fn find_partial_aggregate(plan: &Arc) -> Option<&AggregateExec> { + if let Some(aggregate) = plan.downcast_ref::() + && aggregate.mode() == &AggregateMode::Partial + { + return Some(aggregate); + } + plan.children().into_iter().find_map(find_partial_aggregate) +} + +criterion_group!( + benches, + criterion_benchmark, + fully_ordered, + partial_aggregation_reprobe +); criterion_main!(benches); diff --git a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs index 1b462ee071929..e1b9098397277 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_argument.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_argument.rs @@ -63,18 +63,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) } @@ -170,10 +158,6 @@ impl AggregateFilter { } } - pub(in crate::aggregates) fn predicate(&self) -> &Arc { - &self.predicate - } - /// Evaluates the filter predicate for every row of `batch`. pub(in crate::aggregates) fn evaluate( &self, 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 fa7a134733194..64603cc03498d 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/common.rs @@ -40,8 +40,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; @@ -162,11 +160,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::>()?; @@ -510,10 +506,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. @@ -526,9 +518,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; @@ -735,41 +724,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` @@ -1161,11 +1127,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 f15ba3e0fba13..670f34d37e24a 100644 --- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs +++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/mod.rs @@ -85,8 +85,8 @@ impl AggregateTableMetrics { } pub(super) use common::{ - AggregateHashTable, FinalMarker, PartialMarker, PartialReduceMarker, - PartialSkipMarker, SingleMarker, create_group_accumulator, + AggregateHashTable, FinalMarker, PartialMarker, PartialReduceMarker, SingleMarker, + create_group_accumulator, }; 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/grouped_hash_stream.rs b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs index f91fec487c356..bef399ee7fcaf 100644 --- a/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/grouped_hash_stream.rs @@ -758,6 +758,9 @@ impl Stream for GroupedHashAggregateStream { let _timer = elapsed_compute.timer(); if let Some(probe) = self.skip_aggregation_probe.as_mut() { probe.record_skipped(&batch); + if !probe.should_skip() { + self.exec_state = ExecutionState::ReadingInput; + } } let states = self.transform_to_states(&batch)?; return Poll::Ready(Some(Ok( diff --git a/datafusion/physical-plan/src/aggregates/hash_stream.rs b/datafusion/physical-plan/src/aggregates/hash_stream.rs index 4a5993b15864f..d991dae127bcb 100644 --- a/datafusion/physical-plan/src/aggregates/hash_stream.rs +++ b/datafusion/physical-plan/src/aggregates/hash_stream.rs @@ -22,7 +22,6 @@ use futures::stream::{Stream, StreamExt}; use super::AggregateExec; use super::aggregate_hash_table::{ AggregateHashTable, ClusteredAggregateTableMetrics, FinalMarker, PartialMarker, - PartialSkipMarker, }; use super::order::GroupClusteringMode; use super::skip_partial::SkipAggregationProbe; @@ -91,8 +90,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 /// @@ -292,27 +292,36 @@ 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)?; + 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(), @@ -323,25 +332,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(()) }) } @@ -419,7 +414,7 @@ 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, emitter: &mut TryEmitter, @@ -498,34 +493,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 { @@ -1298,17 +1265,348 @@ mod tests { Ok(()) } + #[rstest::rstest] + #[case(true, 0, 32)] + #[case(false, 0, 32)] + #[case(true, 32, 160)] + #[case(false, 32, 160)] + #[case(true, 0, 195)] + #[case(false, 0, 195)] + #[tokio::test] + async fn test_partial_aggregation_reprobes_changing_keys( + #[case] enable_migration_aggregate: bool, + #[case] useful_batches: usize, + #[case] unique_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 = 128; + let total_batches = useful_batches + unique_batches + 256; + let mut expected = BTreeMap::::new(); + let batches = (0..total_batches) + .map(|batch| { + let keys = (0..batch_rows) + .map(|row| { + if (useful_batches..useful_batches + unique_batches) + .contains(&batch) + { + (batch * batch_rows + row) 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; + } + RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from(keys)), + Arc::new(Int64Array::from(values)), + ], + ) + }) + .collect::, _>>()?; + let group_by = PhysicalGroupBy::new_single(vec![( + col("group_col", &schema)?, + "group_col".to_string(), + )]); + let aggr_expr = [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 config = SessionConfig::new() + .with_batch_size(batch_rows) + .set_usize( + "datafusion.execution.skip_partial_aggregation_probe_rows_threshold", + batch_rows, + ) + .set_bool( + "datafusion.execution.enable_migration_aggregate", + enable_migration_aggregate, + ); + let task_ctx = Arc::new(TaskContext::default().with_session_config(config)); + 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, + aggr_expr, + vec![None; 2], + input, + Arc::clone(&schema), + )?; + let output = collect(aggregate_exec.execute(0, task_ctx)?).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); + 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, migration={enable_migration_aggregate}" + ); + let skipped = aggregate_exec + .metrics() + .unwrap() + .sum_by_name("skipped_aggregation_rows") + .unwrap() + .as_usize(); + assert!( + skipped > 20 * batch_rows, + "ineffective reprobes must return to skipping" + ); + Ok(()) + } + + #[rstest::rstest] + #[case(true, true, 0)] + #[case(false, true, 0)] + #[case(true, false, 0)] + #[case(false, false, 0)] + #[case(true, true, 200)] + #[case(false, true, 200)] + #[tokio::test] + async fn test_partial_aggregation_reprobes_memory_pressure( + #[case] enable_migration_aggregate: bool, + #[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 = 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, + ) + .set_bool( + "datafusion.execution.enable_migration_aggregate", + enable_migration_aggregate, + ); + 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 count = + AggregateExprBuilder::new(count_udaf(), vec![col("value_col", &schema)?]) + .schema(Arc::clone(&schema)) + .alias("count_value") + .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" + ); + } 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(()) + } + + #[rstest::rstest] + #[tokio::test] + async fn test_partial_aggregation_reprobe_input_boundaries( + #[values(true, false)] enable_migration_aggregate: bool, + #[values(0, 1, 5, 6)] num_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 = 128; + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![ + Arc::new(Int32Array::from_iter_values(0..batch_rows as i32)), + Arc::new(Int64Array::from(vec![1; batch_rows])), + ], + )?; + let empty = RecordBatch::new_empty(Arc::clone(&schema)); + let mut batches = vec![empty.clone()]; + for _ in 0..num_batches { + batches.extend([batch.clone(), empty.clone()]); + } + let pool: Arc = Arc::new(GreedyMemoryPool::new(1024 * 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", + batch_rows, + ) + .set_bool( + "datafusion.execution.enable_migration_aggregate", + enable_migration_aggregate, + ); + let context = Arc::new( + TaskContext::default() + .with_runtime(runtime) + .with_session_config(config), + ); + let input = TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None)?; + let group_by = PhysicalGroupBy::new_single(vec![( + col("group_col", &schema)?, + "group_col".to_string(), + )]); + let count = + AggregateExprBuilder::new(count_udaf(), vec![col("value_col", &schema)?]) + .schema(Arc::clone(&schema)) + .alias("count_value") + .build()?; + let aggregate = AggregateExec::try_new( + AggregateMode::Partial, + group_by, + vec![Arc::new(count)], + vec![None], + input, + schema, + )?; + let output = collect(aggregate.execute(0, context)?).await?; + let mut counts = BTreeMap::::new(); + for batch in &output { + 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); + } + } + assert_eq!(counts.len(), if num_batches == 0 { 0 } else { batch_rows }); + assert!(counts.values().all(|&count| count == num_batches as i64)); + assert_eq!(pool.reserved(), 0); + Ok(()) + } + /// Builds a partial hash aggregate stream over a single input batch of /// `num_groups` distinct groups, running under `memory_limit` bytes. /// /// 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, @@ -1343,9 +1641,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); @@ -1381,6 +1683,19 @@ mod tests { Ok((stream, input, runtime)) } + #[tokio::test] + async fn test_partial_hash_stream_cancellation_during_skip_flush() -> Result<()> { + let (mut stream, _input, runtime) = + partial_stream_under_memory_limit(1024 * 1024, 128, 4096, 0.8)?; + let first = stream.next().await.transpose()?.expect("skip flush output"); + assert_eq!(first.num_rows(), 128); + assert!(runtime.memory_pool.reserved() > 0); + drop(first); + drop(stream); + 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<()> { @@ -1388,7 +1703,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 @@ -1433,7 +1748,7 @@ mod tests { 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 @@ -1460,7 +1775,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 de88ae95f82a5..c6538d04a93c9 100644 --- a/datafusion/physical-plan/src/aggregates/skip_partial.rs +++ b/datafusion/physical-plan/src/aggregates/skip_partial.rs @@ -6,6 +6,11 @@ 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`]. @@ -38,9 +43,10 @@ pub(super) struct SkipAggregationProbe { /// 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, + /// Rows to bypass before starting a fresh probe window. + rows_until_reprobe: usize, + /// Multiplier for the next skip window; reset after a useful probe. + skip_multiplier: usize, // ======================================================================== // METRICS: @@ -66,7 +72,8 @@ impl SkipAggregationProbe { probe_rows_threshold, probe_ratio_threshold, should_skip: false, - is_locked: false, + rows_until_reprobe: 0, + skip_multiplier: INITIAL_REPROBE_SKIP_MULTIPLIER, skipped_aggregation_rows, } } @@ -75,19 +82,30 @@ impl SkipAggregationProbe { /// - 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 + /// - if `should_skip` is set, waits for the skip window to finish pub(super) fn update_state(&mut self, input_rows: usize, new_groups: usize) { - if self.is_locked { + if self.should_skip { return; } self.input_rows += input_rows; self.num_groups += new_groups; - if self.input_rows >= self.probe_rows_threshold { + if self.input_rows > 0 && 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; + if self.should_skip { + // A long useful phase must not delay recovery after a later skip. + // Account for batches larger than the configured probe window. + self.rows_until_reprobe = 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; + } } } @@ -98,6 +116,17 @@ impl SkipAggregationProbe { /// 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; + } + self.rows_until_reprobe = + self.rows_until_reprobe.saturating_sub(batch.num_rows()); + if self.rows_until_reprobe == 0 { + self.input_rows = 0; + self.num_groups = 0; + self.should_skip = false; + } } } @@ -121,6 +150,63 @@ mod tests { use datafusion_physical_expr::expressions::col; use futures::StreamExt; + 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(0)] + #[case(8)] + fn test_reprobe_backoff_is_bounded(#[case] probe_rows_threshold: 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(8, 8); + assert!(probe.should_skip()); + skip_rows(&mut probe, 8 * 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()); + } + // Migrated to PartialHashAggregateStream coverage in hash_stream.rs; // kept here for the legacy GroupedHashAggregateStream implementation. #[tokio::test] diff --git a/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt b/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt new file mode 100644 index 0000000000000..34589a45ecb6a --- /dev/null +++ b/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: Apache-2.0 +# 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 + +# configMatrix: datafusion.execution.enable_migration_aggregate=true,false + +statement ok +SET datafusion.execution.batch_size = 128; + +statement ok +SET datafusion.execution.target_partitions = 2; + +statement ok +SET datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 128; + +statement ok +CREATE TABLE reprobe_input AS +SELECT CASE WHEN value % 16 = 0 THEN NULL + WHEN value % 2048 < 256 THEN value + ELSE value % 4 END AS k, + CAST(value % 3 AS VARCHAR) AS category, + CASE WHEN value % 7 = 0 THEN NULL ELSE value % 11 END AS v +FROM generate_series(0, 24575); + +statement ok +CREATE VIEW reprobe_result AS +SELECT k, category, COUNT(*) AS n, COUNT(v) AS nv, SUM(v) AS total, + AVG(v) AS mean, MIN(v) AS smallest, MAX(v) AS largest, + SUM(v) FILTER (WHERE v > 2) AS filtered, + COUNT(*) FILTER (WHERE v IS NULL) AS nulls +FROM reprobe_input +GROUP BY k, category; + +statement ok +SET datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 1.0; + +statement ok +CREATE TABLE reprobe_expected AS SELECT * FROM reprobe_result; + +statement ok +SET datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.8; + +# Compare every group and accumulator state across skip/probe transitions, +# including multi-column and null keys and differently filtered accumulators. +query I +SELECT COUNT(*) FROM ( + (SELECT * FROM reprobe_result EXCEPT SELECT * FROM reprobe_expected) + UNION ALL + (SELECT * FROM reprobe_expected EXCEPT SELECT * FROM reprobe_result) +); +---- +0 + +query II +SELECT SUM(n), SUM(nv) FROM reprobe_result; +---- +24576 21065 + +# An empty input must not produce a group when there is no empty grouping set. +query I +SELECT COUNT(*) FROM ( + SELECT k, category, COUNT(*) FROM reprobe_input WHERE false GROUP BY k, category +); +---- +0 + +statement ok +DROP VIEW reprobe_result; + +statement ok +DROP TABLE reprobe_input; + +statement ok +DROP TABLE reprobe_expected; + +statement ok +RESET datafusion.execution.batch_size; + +statement ok +SET datafusion.execution.target_partitions = 4; + +statement ok +RESET datafusion.execution.skip_partial_aggregation_probe_rows_threshold; + +statement ok +RESET datafusion.execution.skip_partial_aggregation_probe_ratio_threshold; diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index 000055472bbc0..1bd7bfcc03244 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -443,8 +443,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. Skipping initially lasts four times the larger of this threshold and the triggering batch's row count. Consecutive unsuccessful probes increase the multiplier to eight and then sixteen. A useful probe resets it to four. 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 19c4fc1971090..4c0fc2720e669 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. Skipping initially lasts four times the larger of this threshold and the triggering batch's row count. Consecutive unsuccessful probes increase the multiplier to eight and then sixteen. A useful probe resets it to four. | | 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. | From ce1b5542766df6aaaa468c3d1160451257844f55 Mon Sep 17 00:00:00 2001 From: benjibun <226082140+benjibunbun@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:48:44 +1100 Subject: [PATCH 2/2] test: compare partial aggregation results without EXCEPT Use signed row counts over materialized results to preserve null equality through unparser round trips and catch duplicate rows. Generated-by: Codex --- .../test_files/aggregate_partial_reprobe.slt | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt b/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt index 34589a45ecb6a..c6366300bd2de 100644 --- a/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt +++ b/datafusion/sqllogictest/test_files/aggregate_partial_reprobe.slt @@ -40,13 +40,22 @@ CREATE TABLE reprobe_expected AS SELECT * FROM reprobe_result; statement ok SET datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.8; +statement ok +CREATE TABLE reprobe_actual AS SELECT * FROM reprobe_result; + # Compare every group and accumulator state across skip/probe transitions, # including multi-column and null keys and differently filtered accumulators. +# Signed row counts preserve null equality and also catch duplicate rows. query I SELECT COUNT(*) FROM ( - (SELECT * FROM reprobe_result EXCEPT SELECT * FROM reprobe_expected) - UNION ALL - (SELECT * FROM reprobe_expected EXCEPT SELECT * FROM reprobe_result) + SELECT k, category, n, nv, total, mean, smallest, largest, filtered, nulls + FROM ( + SELECT *, 1 AS delta FROM reprobe_actual + UNION ALL + SELECT *, -1 AS delta FROM reprobe_expected + ) + GROUP BY k, category, n, nv, total, mean, smallest, largest, filtered, nulls + HAVING SUM(delta) <> 0 ); ---- 0 @@ -73,6 +82,9 @@ DROP TABLE reprobe_input; statement ok DROP TABLE reprobe_expected; +statement ok +DROP TABLE reprobe_actual; + statement ok RESET datafusion.execution.batch_size;