Skip to content

fix: re-probe partial aggregation after skipping - #27677

Open
benjibunbun wants to merge 5 commits into
apache:mainfrom
benjibunbun:issue-27591-partial-aggregation-reprobe
Open

benjibunbun wants to merge 5 commits into
apache:mainfrom
benjibunbun:issue-27591-partial-aggregation-reprobe

Conversation

@benjibunbun

@benjibunbun benjibunbun commented Nov 23, 2026 •

Copy link
Copy Markdown

Which issue does this PR close?

Rationale for this change

Partial aggregation currently skips for the rest of a query once its probe decides to stop. It can't recover when keys become repetitive or temporary memory pressure clears, so every remaining row is sent downstream as partial state.

What changes are included in this PR?

  • Re-probe with fresh counters and an empty table in both partial aggregation implementations. The current stream retains its building table; the separate conversion-only table is removed.
  • Start with a bypass interval of four times the larger of the probe-row threshold and triggering batch. Repeated ineffective probes increase that to eight, then sixteen; a useful decision resets it to four. This policy still needs the overhead comparison requested in review.
  • Preserve existing grouping/limit behavior and threshold opt-outs. No new setting or public API.

State model for review

For the eligible unordered grouped partial path, the model separates input processing from draining output:

State Event Transition
Aggregating More input; no skip or early emit needed Aggregate once, update probe counters, stay here
Aggregating Probe decides aggregation is ineffective Drain all groups, then enter Skipping
Aggregating Memory pressure requires early emission Drain selected groups, then resume Aggregating
Aggregating EOF Drain remaining groups, then Done
Skipping More input Convert the whole batch to partial state; decrease the skip budget
Skipping Budget reaches zero Finish converting that batch; the next input starts Aggregating with an empty table and fresh counters
Skipping EOF Done; the table is already empty

Draining reads no input and carries its destination: Aggregating, Skipping or Done. Memory-driven emission keeps the probe counters; newly created groups continue to count across emissions. It need not empty the legacy table. A skip flush must empty the table before conversion begins.

After an aggregated batch, the probe decision comes before the memory-reservation check. If it chooses skipping, there is one flush toward Skipping. Otherwise, memory pressure may cause an early emit back to Aggregating. Neither path reprocesses the input batch. Unrecoverable errors propagate; cancellation drops held state and reservations.

In the current revision, useful decisions keep cumulative counters. Closing every useful window would be a separate behavior change. A ratio <= 0 keeps skipping permanent; a ratio >= 1 disables skipping.

The probe now uses explicit Probing and Skipping states. Partial flushes share MaterializedAggregateOutput::next_batch, preserving dictionary compaction and batch limits. The aggregated input batch is released before the flush yields output.

What is the testing strategy for this PR?

Native regressions cover exact results, changing keys, temporary and persistent memory pressure, empty/EOF boundaries, dictionary compaction, and cancellation/reservation release. The aggregation fuzzer now exercises retries with a positive ratio. Coverage for both implementations, including AVG, filters and NULLs, is consolidated in the existing native tests and aggregate_skip_partial.slt.

Local verification passes on cc52c770: the full lint suite, 13,669 workspace tests, all 310 SQL files, CLI tests, core doctests, unparser and Substrait checks. Hosted CI passed on the earlier published ce1b554; results for this update are pending.

The timing-only aggregate_query_sql group covers changing, late-changing, unique and repeated keys, plus an ungrouped control. The Criterion, H2O q10 and external_aggr comparisons use matching optimized builds against pinned main e5da002d, with both aggregation implementations. Background activity affected the runs throughout, so these are not the clean comparisons requested. Current short-unique was 5.2% and 8.9% slower in paired runs; legacy long-unique was 1.9%-9.3% slower. Earlier revisions also produced larger adverse timings, up to 63%, under contention.

The requested <=1% worst-case bound remains unestablished. Increasing only the maximum cap leaves the first retries unchanged. A quiet short-unique/control comparison is the next diagnostic; the full requested set still needs clean measurements. No distributed speedup is claimed.

Are there any user-facing changes?

Partial aggregation can resume when input or available memory changes. The capped backoff trades recovery delay against repeated work when aggregation remains ineffective.

Assisted by Codex.

@github-actions github-actions Bot added documentation Improvements or additions to documentation core Core DataFusion crate sqllogictest SQL Logic Tests (.slt) common Related to common crate physical-plan Changes to the physical-plan crate labels Nov 23, 2026
Use signed row counts over materialized results to preserve null equality
through unparser round trips and catch duplicate rows.

Generated-by: Codex

@comphead comphead left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking up #27591. Keeping one table and removing PartialSkipMarker, partial_skip_table and the empty_like helpers is a nice simplification.

Before merging a default-on change I'd like to see the cost settled. #22405 lists re-probing as point 3, and point 4 asks that it add at most 1% in the worst case. On persistently unique input with the default window, this PR re-aggregates the windows starting at 0, 5, 14, 31, 48, ... times probe_rows_threshold. That is 20% of the rows of a 1M-row partition and 10% of a 5M-row one, compared to 10% and 2% on main, and it approaches 1/17. The PR description reports 13% to 63% slower unique and late-change runs. Could you share clean runs against main for the new criterion group, H2O groupby q10 (six keys, near unique, so it measures failed re-probes) and external_aggr (memory limits, where each failed re-probe repeats the early-emit probe)? That would also show which cap meets the bound.

The inline comments cover the skip flush, the test strategy, the probe window and the docs.

Nit:

  • should_skip duplicates rows_until_reprobe > 0. An enum such as Probing { input_rows, num_groups } and Skipping { rows_left } would drop the flag.

}
timer.done();
self.emit_on_memory_pressure(
self.emit_partial_state(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On main the switch to skip drained through produce_output, whose MaterializedAggregateOutput::next_batch compacts dictionaries (#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.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

// Account for batches larger than the configured probe window.
self.rows_until_reprobe = self
.probe_rows_threshold
.max(input_rows)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread datafusion/common/src/config.rs Outdated
/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

group.finish();
}

async fn check_partial_reprobe(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@2010YOUY01

Copy link
Copy Markdown
Member

What would the conceptual state machine for partial aggregation look like?

I feel it a bit hard to understand: at certain points, aggregation need to handle memory pressure and update probing statistics simultaneously.

As a next step, I'd suggest first clearly defining the states and their transitions in the PR description before proceeding further with the implementation. And later we can make the implementation closely reflect this state model.

@benjibunbun

Copy link
Copy Markdown
Author

Added the state model to the description. The key distinction is where draining resumes: memory pressure returns to aggregation with the probe counters intact; an ineffective probe drains the table before skipping. The batch that exhausts the skip budget is still converted once, and the next batch starts the fresh probe.

The implementation changes from review are still pending. The requested performance bound is also unproven; the existing timings don't establish it. Does this state model capture the separation you had in mind?

Reuse the materialized-output slicer for partial flushes and release consumed
input before yielding output. Represent probing and skipping explicitly,
consolidate retry coverage, and simplify the config docs and benchmark.

Integrate main e5da002 for verification against a common baseline.

Generated-by: Codex
@benjibunbun

Copy link
Copy Markdown
Author

The partial flush now uses MaterializedAggregateOutput::next_batch, so dictionary compaction and batch limits apply there too. The aggregated input batch is released before the flush yields output. The probe uses the explicit states from the description, and the docs and benchmark cleanup are included.

Kept the zero-ratio opt-out and added the positive-ratio fuzzer case, with retry coverage consolidated into the existing tests. Useful-side counters stay cumulative here; resetting those windows would change the repeated-to-unique behavior, so that's left for a follow-up as suggested.

The cost question is still open. The local comparisons remain too contended to establish the 1% bound, and raising only the cap doesn't change the first retry. Would you be able to help run the requested comparisons on a quieter machine? The cadence is unchanged for now.

Integrate main ad20f7b and remove the legacy test and benchmark variants
after the grouped aggregation fallback was removed. Preserve the shared
output slicer, re-probe coverage, and upstream state-memory accounting.

Generated-by: Codex
@benjibunbun

Copy link
Copy Markdown
Author

Sorry for the late update. Repeated comparisons point to roughly 6% overhead on short unique input with this cadence. There's still background activity, so I can't claim the 1% bound. A bitmap-screening prototype also caused a low-memory query to fail where main succeeds, so that approach is out.

@yashdotrv

Copy link
Copy Markdown
Contributor

@benjibunbun can you take care the merge conflict!

Integrate upstream 9dfd461 while preserving the re-probing changes
and the current aggregation implementation.

Generated-by: Codex
@benjibunbun

Copy link
Copy Markdown
Author

Ofc 🫡 conflicts are resolved and updated with main

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

common Related to common crate core Core DataFusion crate documentation Improvements or additions to documentation physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Partial aggregation never re-probes after it starts skipping

4 participants