Repository navigation
fix: re-probe partial aggregation after skipping - #27677
benjibunbun wants to merge 6 commits into
Conversation
Generated-by: Codex
Use signed row counts over materialized results to preserve null equality through unparser round trips and catch duplicate rows. Generated-by: Codex
comphead
left a comment
There was a problem hiding this comment.
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_skipduplicatesrows_until_reprobe > 0. An enum such asProbing { input_rows, num_groups }andSkipping { rows_left }would drop the flag.
| } | ||
| timer.done(); | ||
| self.emit_on_memory_pressure( | ||
| self.emit_partial_state( |
There was a problem hiding this comment.
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 { |
There was a problem hiding this 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.
| // Account for batches larger than the configured probe window. | ||
| self.rows_until_reprobe = self | ||
| .probe_rows_threshold | ||
| .max(input_rows) |
There was a problem hiding this 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.
| /// 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 |
There was a problem hiding this 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?
| group.finish(); | ||
| } | ||
|
|
||
| async fn check_partial_reprobe( |
There was a problem hiding this 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?
|
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. |
|
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
|
The partial flush now uses 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
|
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. |
|
@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
|
Ofc 🫡 conflicts are resolved and updated with main |
|
@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:
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:
|
|
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) |
There was a problem hiding this comment.
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.
|
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
|
I've added a case for oversized batches ( The branch includes main 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 c75bc57Both sides used the same inputs and settings:
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
*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 🤞 |
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?
State model for review
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
MaterializedAggregateOutputfor 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.sltcover 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
5eee1faincludes mainc75bc57. 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
c75bc57passed all 15 cases, including H2O Q10 andexternal_aggrunder 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.