@@ -248,8 +248,18 @@ pub struct GroupValuesColumn<const STREAMING: bool> {
248248 /// reused buffer to store hashes
249249 hashes_buffer : Vec < u64 > ,
250250
251+ /// Reused buffer for boundary detection in streaming mode
252+ boundaries_buffer : Vec < bool > ,
253+
251254 /// Random state for creating hashes
252255 random_state : RandomState ,
256+
257+ /// The group index assigned to the last row of the previous batch.
258+ /// Used in streaming (sorted) mode to compare the first row of a new
259+ /// batch with the current group, avoiding hash computation for rows
260+ /// that belong to the same group as the previous row.
261+ /// Set to `usize::MAX` when there is no previous group.
262+ last_group_idx : usize ,
253263}
254264
255265/// Buffers to store intermediate results in `vectorized_append`
@@ -301,7 +311,9 @@ impl<const STREAMING: bool> GroupValuesColumn<STREAMING> {
301311 map_size : 0 ,
302312 group_values : vec ! [ ] ,
303313 hashes_buffer : Default :: default ( ) ,
314+ boundaries_buffer : Default :: default ( ) ,
304315 random_state : crate :: aggregates:: AGGREGATION_HASH_SEED ,
316+ last_group_idx : usize:: MAX ,
305317 } )
306318 }
307319
@@ -358,39 +370,76 @@ impl<const STREAMING: bool> GroupValuesColumn<STREAMING> {
358370 // tracks to which group each of the input rows belongs
359371 groups. clear ( ) ;
360372
361- // 1.1 Calculate the group keys for the group values
362- let batch_hashes = & mut self . hashes_buffer ;
363- batch_hashes. clear ( ) ;
364- batch_hashes. resize ( n_rows, 0 ) ;
365- create_hashes ( cols, & self . random_state , batch_hashes) ?;
373+ if n_rows == 0 {
374+ return Ok ( ( ) ) ;
375+ }
376+
377+ // Optimization for sorted/streaming aggregation:
378+ // Since data arrives sorted, most consecutive rows belong to the same group.
379+ // Instead of hashing ALL rows upfront (expensive for 150M+ rows),
380+ // we detect group boundaries in batch (column-wise, vectorizable),
381+ // then only hash+lookup the ~5% of rows that are boundary rows.
382+
383+ // Pass 1: Detect group boundaries by comparing adjacent rows.
384+ // Each GroupColumn processes its entire column in a tight inner loop
385+ // (one virtual call per column, NOT per row).
386+ let boundaries = & mut self . boundaries_buffer ;
387+ boundaries. clear ( ) ;
388+ boundaries. resize ( n_rows, false ) ;
389+
390+ // Row 0: compare with stored group values from previous batch
391+ if self . last_group_idx == usize:: MAX
392+ || !self
393+ . group_values
394+ . iter ( )
395+ . enumerate ( )
396+ . all ( |( i, gv) | gv. equal_to ( self . last_group_idx , & cols[ i] , 0 ) )
397+ {
398+ boundaries[ 0 ] = true ;
399+ }
400+
401+ // Rows 1..n: compare adjacent rows within the batch (column-wise)
402+ for ( i, gv) in self . group_values . iter ( ) . enumerate ( ) {
403+ gv. compute_boundaries ( & cols[ i] , boundaries) ;
404+ }
405+
406+ // Pass 2: Process boundary rows (hash + map lookup).
407+ // Non-boundary rows get the same group index as their predecessor.
408+ let mut current_group_idx = self . last_group_idx ;
409+
410+ for row in 0 ..n_rows {
411+ if !boundaries[ row] {
412+ // Not a boundary - same group as previous row
413+ groups. push ( current_group_idx) ;
414+ continue ;
415+ }
416+
417+ // Group boundary - compute hash for this single row
418+ let target_hash = {
419+ let mut h = 0u64 ;
420+ for ( i, gv) in self . group_values . iter ( ) . enumerate ( ) {
421+ h = gv. hash_input_row (
422+ & cols[ i] ,
423+ row,
424+ & self . random_state ,
425+ i > 0 ,
426+ h,
427+ ) ;
428+ }
429+ h
430+ } ;
366431
367- for ( row, & target_hash) in batch_hashes. iter ( ) . enumerate ( ) {
368432 let entry = self
369433 . map
370434 . find_mut ( target_hash, |( exist_hash, group_idx_view) | {
371- // It is ensured to be inlined in `scalarized_intern`
372435 debug_assert ! ( !group_idx_view. is_non_inlined( ) ) ;
373436
374- // Somewhat surprisingly, this closure can be called even if the
375- // hash doesn't match, so check the hash first with an integer
376- // comparison first avoid the more expensive comparison with
377- // group value. https://github.com/apache/datafusion/pull/11718
378437 if target_hash != * exist_hash {
379438 return false ;
380439 }
381440
382- fn check_row_equal (
383- array_row : & dyn GroupColumn ,
384- lhs_row : usize ,
385- array : & ArrayRef ,
386- rhs_row : usize ,
387- ) -> bool {
388- array_row. equal_to ( lhs_row, array, rhs_row)
389- }
390-
391441 for ( i, group_val) in self . group_values . iter ( ) . enumerate ( ) {
392- if !check_row_equal (
393- group_val. as_ref ( ) ,
442+ if !group_val. equal_to (
394443 group_idx_view. value ( ) as usize ,
395444 & cols[ i] ,
396445 row,
@@ -402,18 +451,13 @@ impl<const STREAMING: bool> GroupValuesColumn<STREAMING> {
402451 true
403452 } ) ;
404453
405- let group_idx = match entry {
406- // Existing group_index for this group value
454+ current_group_idx = match entry {
407455 Some ( ( _hash, group_idx_view) ) => group_idx_view. value ( ) as usize ,
408- // 1.2 Need to create new entry for the group
409456 None => {
410- // Add new entry to aggr_state and save newly created index
411- // let group_idx = group_values.num_rows();
412- // group_values.push(group_rows.row(row));
413-
414457 let mut checklen = 0 ;
415458 let group_idx = self . group_values [ 0 ] . len ( ) ;
416- for ( i, group_value) in self . group_values . iter_mut ( ) . enumerate ( ) {
459+ for ( i, group_value) in self . group_values . iter_mut ( ) . enumerate ( )
460+ {
417461 group_value. append_val ( & cols[ i] , row) ?;
418462 let len = group_value. len ( ) ;
419463 if i == 0 {
@@ -423,18 +467,21 @@ impl<const STREAMING: bool> GroupValuesColumn<STREAMING> {
423467 }
424468 }
425469
426- // for hasher function, use precomputed hash value
427470 self . map . insert_accounted (
428- ( target_hash, GroupIndexView :: new_inlined ( group_idx as u64 ) ) ,
471+ (
472+ target_hash,
473+ GroupIndexView :: new_inlined ( group_idx as u64 ) ,
474+ ) ,
429475 |( hash, _group_index) | * hash,
430476 & mut self . map_size ,
431477 ) ;
432478 group_idx
433479 }
434480 } ;
435- groups. push ( group_idx ) ;
481+ groups. push ( current_group_idx ) ;
436482 }
437483
484+ self . last_group_idx = current_group_idx;
438485 Ok ( ( ) )
439486 }
440487
@@ -1106,7 +1153,7 @@ impl<const STREAMING: bool> GroupValues for GroupValuesColumn<STREAMING> {
11061153
11071154 fn size ( & self ) -> usize {
11081155 let group_values_size: usize = self . group_values . iter ( ) . map ( |v| v. size ( ) ) . sum ( ) ;
1109- group_values_size + self . map_size + self . hashes_buffer . allocated_size ( )
1156+ group_values_size + self . map_size + self . hashes_buffer . allocated_size ( ) + self . boundaries_buffer . allocated_size ( )
11101157 }
11111158
11121159 fn is_empty ( & self ) -> bool {
@@ -1122,6 +1169,19 @@ impl<const STREAMING: bool> GroupValues for GroupValuesColumn<STREAMING> {
11221169 }
11231170
11241171 fn emit ( & mut self , emit_to : EmitTo ) -> Result < Vec < ArrayRef > > {
1172+ // Update last_group_idx for streaming mode
1173+ match emit_to {
1174+ EmitTo :: All => {
1175+ self . last_group_idx = usize:: MAX ;
1176+ }
1177+ EmitTo :: First ( n) => {
1178+ if self . last_group_idx != usize:: MAX {
1179+ self . last_group_idx =
1180+ self . last_group_idx . checked_sub ( n) . unwrap_or ( usize:: MAX ) ;
1181+ }
1182+ }
1183+ }
1184+
11251185 let mut output = match emit_to {
11261186 EmitTo :: All => {
11271187 let group_values = mem:: take ( & mut self . group_values ) ;
@@ -1226,10 +1286,13 @@ impl<const STREAMING: bool> GroupValues for GroupValuesColumn<STREAMING> {
12261286 fn clear_shrink ( & mut self , num_rows : usize ) {
12271287 self . group_values . clear ( ) ;
12281288 self . map . clear ( ) ;
1289+ self . last_group_idx = usize:: MAX ;
12291290 self . map . shrink_to ( num_rows, |_| 0 ) ; // hasher does not matter since the map is cleared
12301291 self . map_size = self . map . capacity ( ) * size_of :: < ( u64 , usize ) > ( ) ;
12311292 self . hashes_buffer . clear ( ) ;
12321293 self . hashes_buffer . shrink_to ( num_rows) ;
1294+ self . boundaries_buffer . clear ( ) ;
1295+ self . boundaries_buffer . shrink_to ( num_rows) ;
12331296
12341297 // Such structures are only used in `non-streaming` case
12351298 if !STREAMING {
0 commit comments