Skip to content

refactor(hash-aggr): Support spilling for partial and final mode aggregation - #24061

Merged
alamb merged 3 commits into
apache:mainfrom
2010YOUY01:split-aggr-spill-partial-final
Aug 6, 2026
Merged

refactor(hash-aggr): Support spilling for partial and final mode aggregation#24061
alamb merged 3 commits into
apache:mainfrom
2010YOUY01:split-aggr-spill-partial-final

Conversation

@2010YOUY01

@2010YOUY01 2010YOUY01 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Part of #22710

Rationale for this change

This PR adds existing spilling feature into the new 2-staged (partial and final) aggregation. The high-level implementation idea is the same as the legacy implementation.

For the algorithm description for this feature, see top comment change at datafusion/physical-plan/src/aggregates/hash_stream.rs

What changes are included in this PR?

The key changes to the operator state machine are:
In file datafusion/physical-plan/src/aggregates/hash_stream.rs

  • PartialHashAggregateStream::poll_next()
  • FinalHashAggregateStream::poll_next()

Use this as the starting point, you can navigate to all the related changes, for example adding new states to implement larger-than-memory execution.

This PR also includes small fixes to memory reservation in OrderedFinalAggregateStream. The bugs are caught by existing tests on aggregation spilling that is enabled in this PR.

Are these changes tested?

Existing tests

  • TODO for myself: double check the codecov

Are there any user-facing changes?

No

@2010YOUY01 2010YOUY01 changed the title feat: implement spilling for migrated partial/final hash aggregation refactor(hash-aggr): Support spilling for partial and final mode aggregation Aug 3, 2026
/// into an ordered streaming aggregation, which ensures bounded memory usage and
/// evaluates the final result.
/// - [`OrderedFinalAggregateStream`] is reused for the streaming aggregation.
pub(crate) struct PartialHashAggregateStream {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We could put partial and final stream to two different files, I plan to this after this PR.

| 3 | 1 | 2.0 |
| 3 | 2 | 5.0 |
| 4 | 3 | 11.0 |
| 4 | 1 | 4.0 |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

they're both valid partial aggregation output, due to early emitting under memory limit.

// enlarge memory limit to let the final aggregation finish
new_spill_ctx(2, 2600)
// Enlarge the memory limit enough to replay spilled states.
new_spill_ctx(2, 4640)

@2010YOUY01 2010YOUY01 Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The legacy implementation underestimate the memory usage somehow, so here it relaxes the memory budget


assert_eq!(3, output_rows);
if spill {
// When spilling, the output rows metrics become partial output size + final output size

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This should be a bug in the legacy implementation. Final aggregation should return the same output_rows regardless of the spilling condition.

@codecov-commenter

codecov-commenter commented Aug 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.45808% with 76 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.05%. Comparing base (21ad189) to head (084f633).
⚠️ Report is 40 commits behind head on main.

Files with missing lines Patch % Lines
...fusion/physical-plan/src/aggregates/hash_stream.rs 84.11% 64 Missing and 11 partials ⚠️
datafusion/physical-plan/src/aggregates/mod.rs 80.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #24061      +/-   ##
==========================================
+ Coverage   80.88%   81.05%   +0.17%     
==========================================
  Files        1101     1105       +4     
  Lines      375720   380386    +4666     
  Branches   375720   380386    +4666     
==========================================
+ Hits       303895   308318    +4423     
- Misses      53729    53848     +119     
- Partials    18096    18220     +124     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions Bot added core Core DataFusion crate sqllogictest SQL Logic Tests (.slt) physical-plan Changes to the physical-plan crate labels Aug 4, 2026
@2010YOUY01
2010YOUY01 marked this pull request as ready for review August 4, 2026 08:14
@2010YOUY01
2010YOUY01 requested a review from alamb August 4, 2026 08:14
@alamb

alamb commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

👀

@alamb alamb 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.

Thank you @2010YOUY01

I went through this PR carefully and I (again) found it clear and well written and easy to follow

It is somewhat unfortunate, perhaps, that the state machines for the different spillable hash streams are so similar (we now have I think 3 state machines that have the various spilling / merging states) -- where I think the difference in the streams is largely related to what triggers a spill (vs an emit) and the type of hash table they have

Maybe we can find some way to extract out the state machine into a common structure (with inline functions or something) to capture the differences

let spill_schema = Arc::clone(spill_manager.schema());
// The merge and replay table are two components of the same aggregate
// operator. Keep them under one consumer registration so a fair memory
// pool does not divide this operator's quota between its own phases.

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.

is this a behavior change? Or does it mirror what the old operator does?

(It seems reasonable to me, but I wanted to check)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, it mirrors the existing behavior. It's only get caught by the existing test after this PR, likely because partial/final 2-staged aggregation has better test coverage.

}

if self.hit_soft_group_limit(original_state.hash_table()) {
if self.hit_soft_group_limit(&hash_table) {

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.

Claude code flagged this as a potential bug -- if the limit is set, this code path appears to simply drop the spill_context and any spilled content thus far

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.

Maybe update to

  let spilled = spill_context
      .as_ref()
      .is_some_and(|ctx| ctx.has_spills());
  if self.hit_soft_group_limit(&hash_table) && !spilled {
      // existing early-output path
  }

🤔

But somehow you have to switch to emitting 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated in 084f633

I applied the same logic: if spilled then don't trigger soft limit optimization. Those limits are usually small constants, so they're unlikely to be co-exist with spilling, so I think this extra check would be enough.

BTW I found only good AI models are able to find such tricky bugs effectively, they're really hard to construct tests for. It's quite valuable to let coding agents scan the codebase to find logic inconsistencies.

original_state,
));
// Check memory reservation, and potentially spill.
let timer = elapsed_compute.timer();

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.

a nit here is that you could potentially use the same timer as above rather than making a new one here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It seems not possible, timer.done() would take self.

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.

As in I was thinking that you could avopid timer.done() -- as the destructor also stops the timer I think

&original_state,
PartialHashAggregateState::SkippingAggregation { .. }
));
let PartialHashAggregateState::SkippingAggregation { mut hash_table } =

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.

you could potentially avoid these internal errors by simply passing in hash_table rather than an original_state

The call site already matched on the type of PartialHashAggregateState

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think the benefit of this pattern is, all the logic are implemented within this state function, and the main event loop poll_next() can be kept minimal, the entry-condition check like this one won't get scattered to 2 places.

The downside, as you pointed out, is that it is more verbose. I don’t have a strong preference at this point.

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.

Me neither - this way is fine too

self.input = Box::pin(EmptyRecordBatchStream::new(input_schema));
}

fn break_with_err(error: DataFusionError) -> FinalHashAggregateStateTransition {

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 structure is quite elegant and easy to follow 👍

@2010YOUY01

Copy link
Copy Markdown
Contributor Author

@alamb thank you for the review

@alamb
alamb added this pull request to the merge queue Aug 6, 2026
@alamb

alamb commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Thaks again @2010YOUY01

@alamb

alamb commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

I am keen to get this refactor wrapped up before DF 55 so merging it in

Merged via the queue into apache:main with commit e6b4221 Aug 6, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate 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.

3 participants