Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions datafusion/common/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 51 additions & 1 deletion datafusion/core/benches/aggregate_query_sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ impl SessionContextGenerator {
pub fn new(dataset_ref: Arc<Dataset>, 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(),
];

Expand Down Expand Up @@ -106,18 +112,24 @@ 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 =
rng.random_range(0..self.candidate_skip_partial_params.len());
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
Expand Down
16 changes: 0 additions & 16 deletions datafusion/physical-plan/src/aggregates/aggregate_argument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -186,10 +174,6 @@ impl AggregateFilter {
}
}

pub(in crate::aggregates) fn predicate(&self) -> &Arc<dyn PhysicalExpr> {
&self.predicate
}

/// Evaluates the filter predicate for `batch` and returns the rows it
/// selects. A null rejects its row, like `false`.
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -165,11 +163,9 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
.map(|expr| AggregateArgument::try_new(expr, &input_schema))
.collect::<Result<_>>()?;
Ok(HashAggregateAccumulator::new(
Arc::clone(agg_expr),
arguments,
filter,
accumulator,
Arc::clone(submetrics),
))
})
.collect::<Result<_>>()?;
Expand Down Expand Up @@ -513,10 +509,6 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
/// 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<AggregateFunctionExpr>,

/// Arguments to pass to this accumulator.
///
/// Example: `CORR(x, y)` stores two arguments here, while `SUM(x)` stores one.
Expand All @@ -529,9 +521,6 @@ pub(super) struct HashAggregateAccumulator {

/// Accumulator state for all groups for one aggregate expression.
accumulator: Box<dyn GroupsAccumulator>,

/// Optional internal metrics owned by this aggregate expression.
submetrics: Arc<dyn AggregateMetrics>,
}

pub(super) type AggregateAccumulator = HashAggregateAccumulator;
Expand Down Expand Up @@ -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<Option<RecordBatch>> {
Expand All @@ -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()
}
}
Expand Down Expand Up @@ -740,41 +729,18 @@ fn compact_group_indices(

impl HashAggregateAccumulator {
pub(super) fn new(
aggregate_expr: Arc<AggregateFunctionExpr>,
arguments: Vec<AggregateArgument>,
filter: Option<Arc<dyn PhysicalExpr>>,
accumulator: Box<dyn GroupsAccumulator>,
submetrics: Arc<dyn AggregateMetrics>,
) -> 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<Self> {
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`
Expand Down Expand Up @@ -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,
))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,7 @@ impl<AggrMode> ClusteredAggregateTable<AggrMode> {
.into_iter()
.map(|expr| AggregateArgument::try_new(expr, input_schema))
.collect::<Result<_>>()?;
Ok(AggregateAccumulator::new(
Arc::clone(agg_expr),
arguments,
filter,
accumulator,
Arc::clone(submetrics),
))
Ok(AggregateAccumulator::new(arguments, filter, accumulator))
})
.collect::<Result<_>>()?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -56,42 +51,6 @@ impl AggregateHashTable<PartialMarker> {
)
}

/// 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<AggregateHashTable<PartialSkipMarker>> {
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::<Result<Vec<_>>>()?;

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(
Expand All @@ -110,14 +69,15 @@ impl AggregateHashTable<PartialMarker> {
self.start_outputting();
Ok(())
}
}

impl AggregateHashTable<PartialSkipMarker> {
/// 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<RecordBatch> {
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))?;
Expand Down
Loading