2010YOUY01 commented on code in PR #23657:
URL: https://github.com/apache/datafusion/pull/23657#discussion_r3638083928


##########
datafusion/physical-plan/src/aggregates/ordered_final_stream.rs:
##########
@@ -180,36 +497,183 @@ impl OrderedFinalAggregateStream {
                             next_state,
                         ))
                     }
+                    // Can't do early emit, continue aggregating.
                     Ok(None) => {
-                        // Ordered variant doesn't support memory-limited
-                        // execution, so it errors when memory reservation 
fails.
-                        if let Err(e) = 
self.reservation.try_resize(table.memory_size()) {
-                            return ControlFlow::Break((
-                                Poll::Ready(Some(Err(e))),
-                                OrderedFinalAggregateState::ReadingInput { 
table },
-                            ));
-                        }
-
-                        // Can't do early emit, continue aggregating.
                         
ControlFlow::Continue(OrderedFinalAggregateState::ReadingInput {
                             table,
+                            spill_context,
                         })
                     }
                     Err(e) => ControlFlow::Break((
                         Poll::Ready(Some(Err(e))),
-                        OrderedFinalAggregateState::ReadingInput { table },
+                        OrderedFinalAggregateState::ReadingInput {
+                            table,
+                            spill_context,
+                        },
                     )),
                 }
             }
             Poll::Ready(Some(Err(e))) => ControlFlow::Break((
                 Poll::Ready(Some(Err(e))),
-                OrderedFinalAggregateState::ReadingInput { table },
+                OrderedFinalAggregateState::ReadingInput {
+                    table,
+                    spill_context,
+                },
             )),
             Poll::Ready(None) => {
                 self.close_input();
-                table.input_done();
-                
ControlFlow::Continue(OrderedFinalAggregateState::DrainingFinal { table })
+                match spill_context {
+                    Some(spill_context) if spill_context.has_spills() => {
+                        ControlFlow::Continue(
+                            OrderedFinalAggregateState::PreparingMergeInput {
+                                table,
+                                spill_context,
+                            },
+                        )
+                    }
+                    _ => {
+                        table.input_done();
+                        ControlFlow::Continue(
+                            OrderedFinalAggregateState::ProducingOutput { 
table },
+                        )
+                    }
+                }
+            }
+        }
+    }
+
+    /// Sorts and spills one complete in-memory state run, then resumes input.
+    ///
+    /// See comments at `poll_next()` for details.
+    ///
+    /// Returns the next operator state with control flow decision.
+    fn handle_spilling(
+        &mut self,
+        original_state: OrderedFinalAggregateState,
+    ) -> OrderedFinalAggregateStateTransition {
+        let OrderedFinalAggregateState::Spilling {
+            mut table,
+            mut spill_context,
+        } = original_state
+        else {
+            unreachable!("expected spilling state")
+        };
+
+        let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
+        let timer = elapsed_compute.timer();
+        let mut result = spill_context.spill_table(&mut table);
+
+        // Spilling shrinks the aggregate table and releases its accumulated
+        // memory. Update the reservation accordingly.
+        if self.reservation.try_resize(table.memory_size()).is_err() {
+            // Fold spill error and reservation error into one
+            result = internal_err!("Reservation after spilling should succeed")
+        }
+
+        timer.done();
+
+        match result {
+            // Finished spilling the aggregate table, continue aggregating 
from input
+            Ok(true) => 
ControlFlow::Continue(OrderedFinalAggregateState::ReadingInput {
+                table,
+                spill_context: Some(spill_context),
+            }),
+            Ok(false) => ControlFlow::Break((
+                Poll::Ready(Some(internal_err!(
+                    "Ordered final aggregation entered Spilling with an empty 
table"
+                ))),
+                OrderedFinalAggregateState::Done,
+            )),
+            Err(e) => ControlFlow::Break((
+                Poll::Ready(Some(Err(e))),
+                OrderedFinalAggregateState::Done,
+            )),
+        }
+    }
+
+    /// 1. Spills the last in-memory run.
+    /// 2. Constructs a globally ordered input stream by applying a 
sort-preserving
+    ///    merge to all spills.
+    /// 3. Constructs a replay stream: an ordered aggregate stream over the 
fully
+    ///    ordered input constructed from the spills.
+    ///
+    /// See comments at `poll_next()` for details.
+    ///
+    /// Returns the next operator state with control flow decision.
+    fn handle_preparing_merge_input(
+        &mut self,
+        original_state: OrderedFinalAggregateState,
+    ) -> OrderedFinalAggregateStateTransition {
+        let OrderedFinalAggregateState::PreparingMergeInput {
+            mut table,
+            mut spill_context,
+        } = original_state
+        else {
+            unreachable!("expected preparing merge input state")

Review Comment:
   
[7f8e4be](https://github.com/apache/datafusion/pull/23657/commits/7f8e4be4d0da987badb10237e51e974e5f9f4238)



##########
datafusion/physical-plan/src/aggregates/ordered_final_stream.rs:
##########
@@ -180,36 +497,183 @@ impl OrderedFinalAggregateStream {
                             next_state,
                         ))
                     }
+                    // Can't do early emit, continue aggregating.
                     Ok(None) => {
-                        // Ordered variant doesn't support memory-limited
-                        // execution, so it errors when memory reservation 
fails.
-                        if let Err(e) = 
self.reservation.try_resize(table.memory_size()) {
-                            return ControlFlow::Break((
-                                Poll::Ready(Some(Err(e))),
-                                OrderedFinalAggregateState::ReadingInput { 
table },
-                            ));
-                        }
-
-                        // Can't do early emit, continue aggregating.
                         
ControlFlow::Continue(OrderedFinalAggregateState::ReadingInput {
                             table,
+                            spill_context,
                         })
                     }
                     Err(e) => ControlFlow::Break((
                         Poll::Ready(Some(Err(e))),
-                        OrderedFinalAggregateState::ReadingInput { table },
+                        OrderedFinalAggregateState::ReadingInput {
+                            table,
+                            spill_context,
+                        },
                     )),
                 }
             }
             Poll::Ready(Some(Err(e))) => ControlFlow::Break((
                 Poll::Ready(Some(Err(e))),
-                OrderedFinalAggregateState::ReadingInput { table },
+                OrderedFinalAggregateState::ReadingInput {
+                    table,
+                    spill_context,
+                },
             )),
             Poll::Ready(None) => {
                 self.close_input();
-                table.input_done();
-                
ControlFlow::Continue(OrderedFinalAggregateState::DrainingFinal { table })
+                match spill_context {
+                    Some(spill_context) if spill_context.has_spills() => {
+                        ControlFlow::Continue(
+                            OrderedFinalAggregateState::PreparingMergeInput {
+                                table,
+                                spill_context,
+                            },
+                        )
+                    }
+                    _ => {
+                        table.input_done();
+                        ControlFlow::Continue(
+                            OrderedFinalAggregateState::ProducingOutput { 
table },
+                        )
+                    }
+                }
+            }
+        }
+    }
+
+    /// Sorts and spills one complete in-memory state run, then resumes input.
+    ///
+    /// See comments at `poll_next()` for details.
+    ///
+    /// Returns the next operator state with control flow decision.
+    fn handle_spilling(
+        &mut self,
+        original_state: OrderedFinalAggregateState,
+    ) -> OrderedFinalAggregateStateTransition {
+        let OrderedFinalAggregateState::Spilling {
+            mut table,
+            mut spill_context,
+        } = original_state
+        else {
+            unreachable!("expected spilling state")
+        };
+
+        let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
+        let timer = elapsed_compute.timer();
+        let mut result = spill_context.spill_table(&mut table);
+
+        // Spilling shrinks the aggregate table and releases its accumulated
+        // memory. Update the reservation accordingly.
+        if self.reservation.try_resize(table.memory_size()).is_err() {
+            // Fold spill error and reservation error into one
+            result = internal_err!("Reservation after spilling should succeed")
+        }
+
+        timer.done();
+
+        match result {
+            // Finished spilling the aggregate table, continue aggregating 
from input
+            Ok(true) => 
ControlFlow::Continue(OrderedFinalAggregateState::ReadingInput {
+                table,
+                spill_context: Some(spill_context),
+            }),
+            Ok(false) => ControlFlow::Break((
+                Poll::Ready(Some(internal_err!(
+                    "Ordered final aggregation entered Spilling with an empty 
table"
+                ))),
+                OrderedFinalAggregateState::Done,
+            )),
+            Err(e) => ControlFlow::Break((
+                Poll::Ready(Some(Err(e))),
+                OrderedFinalAggregateState::Done,
+            )),
+        }
+    }
+
+    /// 1. Spills the last in-memory run.
+    /// 2. Constructs a globally ordered input stream by applying a 
sort-preserving
+    ///    merge to all spills.
+    /// 3. Constructs a replay stream: an ordered aggregate stream over the 
fully
+    ///    ordered input constructed from the spills.
+    ///
+    /// See comments at `poll_next()` for details.
+    ///
+    /// Returns the next operator state with control flow decision.
+    fn handle_preparing_merge_input(
+        &mut self,
+        original_state: OrderedFinalAggregateState,
+    ) -> OrderedFinalAggregateStateTransition {
+        let OrderedFinalAggregateState::PreparingMergeInput {
+            mut table,
+            mut spill_context,
+        } = original_state
+        else {
+            unreachable!("expected preparing merge input state")
+        };
+
+        let elapsed_compute = self.baseline_metrics.elapsed_compute().clone();
+        let timer = elapsed_compute.timer();
+        let replay = match spill_context.spill_table(&mut table) {
+            Ok(_) => {
+                let group_by_metrics = table.group_by_metrics();
+                drop(table);
+                match self.reservation.try_resize(0) {
+                    Ok(()) => (*spill_context).into_replay_stream(
+                        &self.baseline_metrics,
+                        group_by_metrics,
+                        self.reservation.new_empty(),
+                    ),
+                    Err(e) => Err(e),
+                }
+            }
+            Err(e) => Err(e),
+        };
+        timer.done();
+
+        match replay {
+            Ok(stream) => {
+                
ControlFlow::Continue(OrderedFinalAggregateState::MergingSpills {
+                    stream,
+                })
             }
+            Err(e) => ControlFlow::Break((
+                Poll::Ready(Some(Err(e))),
+                OrderedFinalAggregateState::Done,
+            )),
+        }
+    }
+
+    /// Forwards output from the fully ordered stream that consumes the merged
+    /// spill runs.
+    ///
+    /// See comments at `poll_next()` for details.
+    ///
+    /// Returns the next operator state with control flow decision.
+    fn handle_merging_spills(
+        &mut self,
+        cx: &mut Context<'_>,
+        original_state: OrderedFinalAggregateState,
+    ) -> OrderedFinalAggregateStateTransition {
+        let OrderedFinalAggregateState::MergingSpills { mut stream } = 
original_state
+        else {
+            unreachable!("expected merging spills state")

Review Comment:
   
[7f8e4be](https://github.com/apache/datafusion/pull/23657/commits/7f8e4be4d0da987badb10237e51e974e5f9f4238)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to