comphead commented on code in PR #27466:
URL: https://github.com/apache/datafusion/pull/27466#discussion_r4620293550


##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1095,13 +1121,26 @@ impl PartitionSearcher for SortedSearch {
         // Reorder `partition_columns` such that its ordering matches input 
ordering.
         let partition_columns_ordered =
             get_at_indices(&partition_columns, 
&self.ordered_partition_by_indices)?;
-        let partition_points =
+        let mut partition_points =
             evaluate_partition_ranges(num_rows, &partition_columns_ordered)?;
         let partition_bys = partition_columns
             .into_iter()
             .map(|arr| arr.values)
             .collect::<Vec<ArrayRef>>();
 
+        // Only the first partition, which may continue a buffered one, and the
+        // last, which may continue in the next batch, need to be buffered.
+        let n_partitions = partition_points.len();
+        if self.can_evaluate_complete && n_partitions > 2 {
+            let complete = 1..n_partitions - 1;
+            self.complete_out = compute_window_aggregates(

Review Comment:
   Both rules hold by construction, and they are now stated and checked. The 
stream calls `update_partition_batch` and `compute_aggregates` back to back for 
every batch in `poll_next_inner`, so `calculate_out_columns` takes the results 
of the batch that set them. Every state map ends with the batch's last 
partition, because `evaluate_stateful` inserts a state for each entry of 
`partition_buffers` in order (`aggregate_evaluate_stateful` and 
`StandardWindowExpr::evaluate_stateful` both insert before any skip), and that 
partition is a new key at the end of `partition_buffers`. The doc of 
`complete_out` now says this, and two `debug_assert!`s check it on every batch 
that takes this path.



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1575,23 +1616,23 @@ fn argmin<T: PartialOrd>(data: impl Iterator<Item = T>) 
-> Option<(usize, T)> {
         .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(Ordering::Equal))
 }
 
-/// Calculates the section we can show results for expression
+/// Calculates the section we can show results for expression. `complete`
+/// holds the results of the partitions between the last two buffered ones
+/// (see [`SortedSearch::complete_out`]).
 fn get_aggregate_result_out_column(
     partition_window_agg_states: &PartitionWindowAggStates,
+    complete: Option<&ArrayRef>,
     len_to_show: usize,
 ) -> Result<ArrayRef> {
     let mut result = None;
     let mut running_length = 0;
-    let mut batches_to_concat = 
Vec::with_capacity(partition_window_agg_states.len());
+    let mut batches_to_concat = 
Vec::with_capacity(partition_window_agg_states.len() + 1);
     // We assume that iteration order is according to insertion order
-    for (
-        _,
-        WindowState {
-            state: WindowAggState { out_col, .. },
-            ..
-        },
-    ) in partition_window_agg_states
-    {
+    let mut out_cols = partition_window_agg_states
+        .values()
+        .map(|WindowState { state, .. }| &state.out_col);
+    let last = complete.and_then(|_| out_cols.next_back());

Review Comment:
   Same invariant as in the thread above. `calculate_out_columns` now asserts 
that every state map ends with the last entry of `partition_buffers` before the 
splice.



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1661,12 +1702,25 @@ fn window_lookahead(exprs: &[Arc<dyn WindowExpr>]) -> 
Option<WindowLookahead> {
     Some(lookahead)
 }
 
+fn is_aggregate(expr: &Arc<dyn WindowExpr>) -> bool {
+    expr.as_any().is::<PlainAggregateWindowExpr>()
+        || expr.as_any().is::<SlidingAggregateWindowExpr>()
+}
+
+/// See [`SortedSearch::can_evaluate_complete`]
+fn can_evaluate_complete(expr: &Arc<dyn WindowExpr>) -> bool {

Review Comment:
   The downcast follows `limit_effect` in the same file, which asks the same 
question about the concrete expression types. The flag is checked in both 
places on purpose: the gate runs once per stream, and `evaluate_partitions` has 
to stay correct for any caller, since `WindowAggExec` calls it for every 
expression. A `WindowExpr` capability method would remove the second check, but 
it would add public API to save one line, so I kept this.



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1095,13 +1121,26 @@ impl PartitionSearcher for SortedSearch {
         // Reorder `partition_columns` such that its ordering matches input 
ordering.
         let partition_columns_ordered =
             get_at_indices(&partition_columns, 
&self.ordered_partition_by_indices)?;
-        let partition_points =
+        let mut partition_points =
             evaluate_partition_ranges(num_rows, &partition_columns_ordered)?;
         let partition_bys = partition_columns
             .into_iter()
             .map(|arr| arr.values)
             .collect::<Vec<ArrayRef>>();
 
+        // Only the first partition, which may continue a buffered one, and the
+        // last, which may continue in the next batch, need to be buffered.
+        let n_partitions = partition_points.len();
+        if self.can_evaluate_complete && n_partitions > 2 {

Review Comment:
   Yes, by design. The complete partitions are drained from 
`partition_buffers`, which all expressions of the node share, so every 
expression has to be able to evaluate them directly. A mixed node keeps the 
current path at the same cost: `row_number` next to `last_value(s) IGNORE 
NULLS` on the #27463 reproducer takes 5.3 s both on `main` and with this PR. 
Supporting mixed nodes needs a per-expression buffer, which is a bigger change 
than this PR.



##########
datafusion/physical-expr/src/window/standard.rs:
##########
@@ -134,6 +162,19 @@ impl WindowExpr for StandardWindowExpr {
         }
     }
 
+    fn evaluate_partitions(
+        &self,
+        batch: &RecordBatch,
+        partitions: &[Range<usize>],
+    ) -> Result<Option<ArrayRef>> {
+        let evaluator = self.expr.create_evaluator()?;

Review Comment:
   In `BoundedWindowAggExec` this only runs for expressions that passed the 
gate, so the evaluator is used. In `WindowAggExec`, `compute_window_aggregates` 
now stops asking an expression after its first `None` and evaluates it one 
partition at a time, so a function that does not qualify creates one extra 
evaluator per input.



-- 
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