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


##########
datafusion/physical-expr/src/window/window_expr.rs:
##########
@@ -211,6 +224,79 @@ pub trait AggregateWindowExpr: WindowExpr {
         )
     }
 
+    /// Evaluates the window function on `partitions` in one call (see
+    /// [`WindowExpr::evaluate_partitions`]). The arguments, FILTER and ORDER 
BY
+    /// are evaluated once for all partitions.
+    fn aggregate_evaluate_partitions(
+        &self,
+        batch: &RecordBatch,
+        partitions: &[Range<usize>],
+    ) -> Result<ArrayRef> {
+        // A single partition can be larger than a batch, so its frames are
+        // not collected
+        if let [partition] = partitions {
+            return self
+                .aggregate_evaluate(&batch.slice(partition.start, 
partition.len()));
+        }
+        let offset = partitions.first().map_or(0, |p| p.start);
+        let num_rows = partitions.last().map_or(0, |p| p.end) - offset;
+        let batch = batch.slice(offset, num_rows);
+        let values = self.evaluate_args(&batch)?;
+        let filter_mask_arr = self
+            .filter_expr()
+            .map(|expr| expr.evaluate(&batch)?.into_array(num_rows))
+            .transpose()?;
+        let filter_mask = filter_mask_arr
+            .as_deref()
+            .map(as_boolean_array)
+            .transpose()?;
+        // A constant result is evaluated once, on the whole partition
+        let is_constant = self.is_constant_in_partition();
+        let frames = if is_constant {
+            partitions
+                .iter()
+                .map(|p| p.start - offset..p.end - offset)
+                .collect()
+        } else {
+            let order_bys = get_orderby_values(self.order_by_columns(&batch)?);
+            calculate_frames(
+                self.get_window_frame(),
+                self.order_by(),
+                &order_bys,
+                partitions,
+            )?
+        };
+        let mut results = Vec::with_capacity(frames.len());
+        let mut frames = frames.into_iter();
+        for partition in partitions {
+            let start = partition.start - offset;
+            let mut accumulator = self.get_accumulator()?;
+            let mut last_range = start..start;
+            let n_frames = if is_constant { 1 } else { partition.len() };
+            for frame in frames.by_ref().take(n_frames) {
+                results.push(self.get_aggregate_result_inside_range(
+                    &last_range,
+                    &frame,
+                    &values,
+                    &mut accumulator,
+                    filter_mask,
+                )?);
+                last_range = frame;
+            }
+        }
+        if !is_constant {
+            return ScalarValue::iter_to_array(results);
+        }
+        // Repeat the result of each partition for its rows
+        let indices = UInt32Array::from_iter_values(
+            partitions
+                .iter()
+                .enumerate()
+                .flat_map(|(idx, p)| std::iter::repeat_n(idx as u32, p.len())),
+        );
+        Ok(take(&ScalarValue::iter_to_array(results)?, &indices, None)?)

Review Comment:
   The `take` here makes constant aggregates in `WindowAggExec` slower than 
`main` once partitions hold a few hundred rows or more. On 4M rows, `sum(v) 
OVER (PARTITION BY k)` with 2000-row partitions goes from 11.0 ms to 12.4 ms, 
and `max(s)` on strings from 26.6 ms to 37.4 ms (window `elapsed_compute`, 
median of 9 to 15 runs). `window_query_sql` misses it because its partitions 
are either one row or about 100k rows. Filling each partition, as `main` does, 
brings these back to 11.5 ms and 27.6 ms, and one-row partitions stay 2x faster 
than `main` (461 ms against 913 ms):
   
   ```suggestion
           // Filling each partition is cheaper than a gather with one index per
           // row once partitions hold more than a few rows
           let arrays = results
               .iter()
               .zip(partitions)
               .map(|(value, p)| value.to_array_of_size(p.len()))
               .collect::<Result<Vec<_>>>()?;
           let arrays = arrays.iter().map(|a| a.as_ref()).collect::<Vec<_>>();
           Ok(arrow::compute::concat(&arrays)?)
   ```
   
   The imports then need:
   
   ```diff
   -use arrow::array::{Array, ArrayRef, UInt32Array, make_comparator, 
new_empty_array};
   +use arrow::array::{Array, ArrayRef, make_comparator, new_empty_array};
    use arrow::compute::SortOptions;
    use arrow::compute::filter as arrow_filter;
    use arrow::compute::kernels::sort::SortColumn;
   -use arrow::compute::take;
   ```
   
   <details><summary>Measurements: main / PR / with the suggestion (4M rows, 
target_partitions = 1, datafusion-cli release-nonlto)</summary>
   
   | `OVER (PARTITION BY k)`, rows per partition | main | PR | suggestion |
   |---|---:|---:|---:|
   | `sum(v)`, 1 | 913 ms | 351 ms | 461 ms |
   | `sum(v)`, 4 | 235 ms | 95 ms | 124 ms |
   | `sum(v)`, 100 | 20.8 ms | 16.4 ms | 16.7 ms |
   | `sum(v)`, 2000 | 11.0 ms | 12.4 ms | 11.5 ms |
   | `sum(v)`, 4000 | 10.9 ms | 12.3 ms | 10.9 ms |
   | `max(s)`, 4 | 321 ms | 138 ms | 173 ms |
   | `max(s)`, 2000 | 26.6 ms | 37.4 ms | 27.6 ms |
   
   The suggestion gives the same results as `main` on 70 runs of constant 
aggregates (int, string, dictionary, decimal, FILTER, DISTINCT) at batch sizes 
1 to 8192.
   </details>
   



##########
datafusion/core/tests/user_defined/user_defined_window_functions.rs:
##########
@@ -210,6 +213,22 @@ async fn test_udwf_bounded_window() {
     // Evaluate is called for each input rows
     assert_eq!(test_state.evaluate_called(), 10);
     assert_eq!(test_state.evaluate_all_called(), 0);
+    // Without `evaluates_frames_independently`, each call sees one partition,
+    // and x = 2 has 7 of the 10 rows
+    assert_eq!(test_state.max_values_len(), 7);
+
+    // With it, one call sees both partitions, with the same results
+    let test_state = TestState {
+        evaluates_frames_independently: true,
+        ..TestState::new().with_uses_window_frame()
+    };
+    let TestContext { ctx, test_state } = TestContext::new(test_state);
+    execute(&ctx, "SET datafusion.execution.target_partitions = 1")
+        .await
+        .unwrap();
+    let independent = execute(&ctx, BOUNDED_WINDOW_QUERY).await.unwrap();
+    assert_eq!(batches_to_string(&independent), batches_to_string(&actual));
+    assert_eq!(test_state.max_values_len(), 10);

Review Comment:
   No test fails if `compute_window_aggregates` drops the `batch_size` limit on 
its runs (`partition_runs(partitions, usize::MAX)`), so the memory fix from the 
last round could come undone without notice. This passes on the PR and fails 
with 10 instead of 7 when the limit is removed:
   
   ```suggestion
       assert_eq!(test_state.max_values_len(), 10);
   
       // A call gets at most `batch_size` rows, or one larger partition, so 
that
       // the frames of `WindowAggExec` stay batch-sized
       let test_state = TestState {
           evaluates_frames_independently: true,
           ..TestState::new().with_uses_window_frame()
       };
       let TestContext { ctx, test_state } = TestContext::new(test_state);
       execute(&ctx, "SET datafusion.execution.target_partitions = 1")
           .await
           .unwrap();
       execute(&ctx, "SET datafusion.execution.batch_size = 4")
           .await
           .unwrap();
       let bounded = execute(&ctx, BOUNDED_WINDOW_QUERY).await.unwrap();
       assert_eq!(batches_to_string(&bounded), batches_to_string(&actual));
       assert_eq!(test_state.max_values_len(), 7);
   ```
   



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