@@ -372,6 +372,27 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
372372 /// spilling without finalizing the same group more than once.
373373 pub ( in crate :: aggregates) fn take_state_batch (
374374 & mut self ,
375+ ) -> Result < Option < RecordBatch > > {
376+ self . take_state_batch_with_capacity ( 0 )
377+ }
378+
379+ /// Reserves fixed row capacity without changing the number of groups.
380+ pub ( in crate :: aggregates) fn reserve_groups ( & mut self , capacity : usize ) {
381+ let state = self . state . building_mut ( ) ;
382+ state. group_values . reserve_groups ( capacity) ;
383+ state
384+ . batch_group_indices
385+ . reserve_exact ( capacity. saturating_sub ( state. batch_group_indices . len ( ) ) ) ;
386+ for acc in & mut state. accumulators {
387+ acc. accumulator . reserve_groups ( capacity) ;
388+ }
389+ }
390+
391+ /// Emits all states and optionally reserves a fixed capacity for the next table.
392+ /// A zero capacity uses the normal memory-releasing path.
393+ pub ( in crate :: aggregates) fn take_state_batch_with_capacity (
394+ & mut self ,
395+ capacity : usize ,
375396 ) -> Result < Option < RecordBatch > > {
376397 let state_schema = Arc :: clone ( & self . state_schema ) ;
377398 let accumulator_metrics = Arc :: clone ( & self . aggregate_accumulator_metrics ) ;
@@ -382,7 +403,11 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
382403 }
383404
384405 let output = group_by_metrics. time_emitting ( || {
385- let mut output = state. group_values . emit ( EmitTo :: All ) ?;
406+ let mut output = if capacity > 0 {
407+ state. group_values . emit_with_capacity ( capacity) ?
408+ } else {
409+ state. group_values . emit ( EmitTo :: All ) ?
410+ } ;
386411 for ( idx, acc) in state. accumulators . iter_mut ( ) . enumerate ( ) {
387412 output. extend ( accumulator_metrics. time (
388413 idx,
@@ -399,9 +424,15 @@ impl<AggrMode> AggregateHashTable<AggrMode> {
399424 // `emit(EmitTo::All)` resets accumulator state. Explicitly shrink the
400425 // key/index buffers too so the memory reservation can be released
401426 // before the batch is sorted for spilling.
402- state. group_values . clear_shrink ( 0 ) ;
403427 state. batch_group_indices . clear ( ) ;
404- state. batch_group_indices . shrink_to_fit ( ) ;
428+ if capacity == 0 {
429+ state. group_values . clear_shrink ( 0 ) ;
430+ state. batch_group_indices . shrink_to_fit ( ) ;
431+ } else {
432+ for acc in & mut state. accumulators {
433+ acc. accumulator . reserve_groups ( capacity) ;
434+ }
435+ }
405436
406437 Ok ( Some ( batch) )
407438 }
0 commit comments