Skip to content

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

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

benjibunbun wants to merge 6 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

Once partial aggregation decides to skip, it currently stays that way for the rest of the query. It can't recover when keys become repetitive or temporary memory pressure clears, so the remaining rows are sent downstream as partial state.

What changes are included in this PR?

  • Retry with fresh probe counters and an empty table. The stream retains its building table, removing the separate conversion-only table.
  • Skip four times the larger of the probe threshold and triggering batch. Repeated failed probes increase that multiplier to eight, then sixteen. A useful decision resets it to four.
  • Preserve grouping, limits and threshold opt-outs. No new setting or public API.

State model for review

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

Draining reads no new input. The probe decision comes before the memory-reservation check, so each input batch is processed once and takes one flush path. Partial flushes reuse MaterializedAggregateOutput for batch limits and dictionary compaction. The aggregated input batch is released before output is yielded.

Useful-side counters remain cumulative, including across memory-driven emissions. Changing that behavior is outside this PR's scope. A ratio <= 0 keeps skipping permanent, while a ratio >= 1 disables skipping.

What is the testing strategy for this PR?

Native tests and aggregate_skip_partial.slt cover retry boundaries, changing keys, temporary and persistent memory pressure, exact results, AVG, filters, NULLs, dictionaries, EOF and cancellation. The aggregation fuzzer also exercises repeated retries. The oversized-batch case checks that the skip budget uses the triggering batch when it exceeds the configured threshold.

The published revision 5eee1fa includes main c75bc57. It passed the full local lint suite, 13,725 Rust tests and all 310 SQL files. Eight Rust tests are ignored by the suite. Hosted CI for this revision needs maintainer approval.

The timing-only benchmark covers short and long unique input, changing and late-changing keys, repeated keys and an ungrouped control. Matched untimed diagnostics against c75bc57 passed all 15 cases, including H2O Q10 and external_aggr under memory limits. Partial output fell from 2,000,000 to 1,017,808 rows for changing keys and from 12,000,000 to 9,684,944 for late-changing keys. Short unique input still puts 10.65% of rows through a failed retry. The cap reduces later retry work but leaves the first retry unchanged.

The latest timing attempt stopped at its noise check before any comparisons ran. Earlier runs indicated roughly 6% overhead on short unique input, with background activity limiting precision. Clean runtime medians and the requested <=1% overhead bound remain unestablished. No distributed speedup is claimed. Current local checks and diagnostics use pinned main c75bc57, so they don't cover later changes on main.

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

@yashdotrv

Copy link
Copy Markdown
Contributor

@benjibunbun thanks for working through this, I ran the state transitions and the updated tests, and the overall approach is fine. The main concern for me is the cost of making this behavior default-on... on persistently high-cardinality input, the retry windows still perform grouping work even when the probe is expected to fail. This PR currently reports approximately 6% overhead on short unique input, while the related design discussion mentioned a target close to 1% in the worst case. Before merging, could we get one clean paired comparison against main using the same optimized build and pinned input for:

  • short and long unique-key input; and H2O Q10 or another near-unique grouped workload;
  • external_aggr under memory pressure, changing-key and late-changing-key input, and repeated-key input as the positive-control case.

It would be useful to report the median over several runs, with the same partition count, batch size, memory configuration, and threshold settings on both sides. Also, I would like to understand:

  • the percentage of rows re-aggregated by failed probes, the number of retries per partition, and the resulting partial-output rows and shuffle volume.
  • whether the 4/8/16 backoff materially improves the worst case, and the recovery benefit on changing distributions outweighs the overhead on permanently unique input.

@yashdotrv

Copy link
Copy Markdown
Contributor

Also @comphead @2010YOUY01, if the measurements confirm a persistent regression above the project’s acceptable bound, should we adjust the retry cadence, make the behavior opt-in initially, or explicitly document the accepted trade-off? I am not proposing a particular alternative yet; I would mainly like the default behavior to be supported by a clear cost/recovery measurement.

One smaller design question: the useful-side probe counters remain cumulative. That preserves the current repeated-to-unique behavior, but it also means a later shift from repetitive keys to unique keys can remain diluted by the earlier history. Is that intentionally outside the scope of this PR? If so, it may be worth recording as a follow-up issue so the probe’s window semantics are explicit.

self.state = ProbeState::Skipping {
rows_left: 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.

could we add a focused test for the case where input_rows > probe_rows_threshold; given this is important to the retry cadence... using only probe_rows_threshold make an immediate re-probe even though the current skipped batch already exceeded the configured window. An assertion that the retry budget is based on input_rows skip_multiplier would make this invariant explicit.

cc @2010YOUY01 @comphead

@comphead

comphead commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Thanks @benjibunbun please resolve the conflicts

Integrate upstream c75bc57 while preserving scalar FILTER handling
and the nested-state benchmark. Extend the bounded-backoff test to
cover a triggering batch larger than the probe threshold.

Generated-by: Codex
@benjibunbun

Copy link
Copy Markdown
Author

I've added a case for oversized batches (input_rows > probe_rows_threshold) to the existing backoff test using a batch of 32 with a threshold of 8. It checks that the skip budget keeps using the larger batch size as the backoff goes through 4/8/16.

The branch includes main c75bc57 with the merge conflicts resolved. The measurements below use that same base.

The counters show that aggregation does recover with 49.1% fewer partial rows for changing keys and 19.3% fewer for late-changing keys. Short unique input still sends 10.65% of its rows through a failed retry though. The cap doesn't help with that first retry.

Also tried another timing run with the busiest background process paused. That brought the load down but my mac still failed the quiet-host check, so I didn't get any new timings. The earlier roughly 6% slowdown on short unique input is still unresolved. I can't back up the 1% bound yet or say that the recovery benefit makes up for the cost of enabling this by default.

Could someone pls help with the paired main/PR timings on a quieter machine? The matching build commands and input details are ready to share. That'd be much appreciated 🙏

On the useful-side counters: yes, keeping them cumulative is intentional here. A long repetitive prefix can still hide a later shift to unique keys. This PR handles recovery after skipping, and I'm leaving changes to how useful windows close for the separate follow-up we discussed. I've drafted the issue but haven't filed it yet.

Retry and output counts against main c75bc57

Both sides used the same inputs and settings:

  • Probe threshold: 100,000 rows
  • Ratio: 0.8
  • Batch size: 8192
  • Partitions: 2 for the SQL cases and 4 for external_aggr
  • Memory pool: fair for external_aggr

Retries exclude the initial probe. The failed-retry percentage is the share of all input rows processed in retries that ended in a failed decision.

The last two columns show main → candidate at 5eee1fa.

Workload Retries per partition Input in failed retries Partial output rows IPC estimate (MiB)
Short unique (2M) 1 10.65% 2,000,000 → 2,000,000 30.64 → 30.64
Long unique (10M) 4 8.52% 10,000,000 → 10,000,000 153.19 → 153.19
Changing (2M) 1 0% 2,000,000 → 1,017,808 30.65 → 15.60
Late-changing (12M) 4 5.32% 12,000,000 → 9,684,944 183.92 → 148.44
Repeated (2M) 0 0% 2,000 → 2,000 0.03 → 0.03
H2O Q10 (10M) 4 8.52% 10,000,000 → 10,000,000 2039.33 → 1936.44
External Q1 (64/32/16 MiB) 0 0% Unchanged at each limit* ~11.52 → ~11.52
External Q2 (512/256/128/64/32 MiB) 2 8.75% 6,001,136 → 6,000,982 ~91.85 → ~91.85

*Q1 emits 1,500,007 / 1,500,021 / 1,500,040 partial rows at the respective limits on both sides.

All 15 untimed diagnostic cases passed. That includes the ungrouped control. Native final row counts and external scalar results matched. Main performed no retries.

Q2 also grouped 167,558 rows in retry windows that reached EOF without a decision. Those rows aren't counted as failed retries. Including them brings total retry work to 11.54% of input.

The IPC figures estimate output size using a separate uncompressed Arrow stream for each batch. They include framing and dictionary/layout effects. They aren't measured network traffic or peak memory. H2O has a smaller IPC estimate but the same number of output rows. That doesn't show fewer rows being shuffled.

I also compared the cadence by replaying the observed batch sizes. Keeping the multiplier at 4 predicts 19.17% failed-retry work for long unique/H2O. The observed result with 4/8/16 is 8.52%. Short unique stays at 10.65% either way.

That comparison is about rows processed. No fixed-four implementation was timed.

Assisted by Codex 🤞

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