comphead commented on code in PR #27677:
URL: https://github.com/apache/datafusion/pull/27677#discussion_r4676556376
##########
datafusion/physical-plan/src/aggregates/skip_partial.rs:
##########
@@ -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)
Review Comment:
This guard and the comment above exist because the probe stays cumulative
after a useful decision, so `self.input_rows` can be far larger than one
window. What about closing the window after every decision, skip or not? Each
decision then uses about `probe_rows_threshold` rows, the skip length can be
`self.input_rows * self.skip_multiplier` with no guard, and the reset to four
happens once per useful window.
The same rule would also catch a shift from repeated to unique keys after a
long useful phase, which stays diluted today. For example 10M rows over 1K keys
followed by 10M unique keys keep the cumulative ratio near 0.5 in a partition,
so it never skips. That changes behavior on the useful side, so a follow-up
issue is fine too.
##########
datafusion/physical-plan/src/aggregates/skip_partial.rs:
##########
@@ -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 {
Review Comment:
Every existing test that forces skipping uses a ratio of 0.0:
`aggregate_skip_partial.slt`, `aggregate_filter_selection.slt`,
`aggregate_filter_columns.slt`, `first_last_primitive_key.slt`,
`aggregate.slt`, and the aggregation fuzzer's
`SkipPartialParams::ensure_trigger()`. With this early return none of them
re-enter aggregation after a skip, so the transition this PR adds is covered
only by the new hand-written tests.
Could we drop this opt-out? A re-probe at 0.0 always fails, but it runs the
aggregate, flush, convert, aggregate cycle on every accumulator, filter and key
type those suites already cover, with no new expected output. If the opt-out
stays, the fuzzer needs a candidate with a positive ratio, for example
`ratio_threshold: f64::MIN_POSITIVE` with `rows_threshold: 0`, which re-probes
after 4, 8 and 16 batches. Either way `aggregate_partial_reprobe.slt`,
`test_partial_aggregation_reprobe_input_boundaries` and
`test_partial_hash_stream_cancellation_during_skip_flush` become redundant, and
the changing-keys case fits as one more row in
`test_partial_aggregation_skip_probe_after_early_emits`.
##########
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
Review Comment:
These sentences land in `configs.md` and `information_schema.slt`, so the
4/8/16 constants and the batch rule become user-facing. Could the user doc say
only that partial aggregation probes again with an empty table after skipping,
with the constants documented on `SkipAggregationProbe`?
##########
datafusion/core/benches/aggregate_query_sql.rs:
##########
@@ -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(
Review Comment:
The rest of this file only times queries. These checks repeat what the unit
tests assert and tie the bench to plan internals (`GroupClusteringMode` and the
plan walk in `find_partial_aggregate`). Could the group keep its case table and
just time the queries?
##########
datafusion/physical-plan/src/aggregates/hash_stream.rs:
##########
@@ -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(
Review Comment:
On `main` the switch to skip drained through `produce_output`, whose
`MaterializedAggregateOutput::next_batch` compacts dictionaries
(https://github.com/apache/datafusion/pull/26703). `emit_partial_state` only
calls `RecordBatch::slice`, so each slice of this flush keeps every dictionary
value of the window's groups. Downstream hashing, coalescing and the final
aggregate then do work per slice that grows with the group count.
High-cardinality dictionary keys are the inputs that skip, and re-probing
repeats this flush on every failed probe. Under memory pressure this emitter
also sends the whole flush as one batch, which the switch path did not do
before.
Could `emit_partial_state` slice through
`MaterializedAggregateOutput::next_batch` instead? Then the early emit, the
skip flush and the end-of-input output share one slicer, and the early-emit
path gets compaction as well.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]