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


##########
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()?;
+        if !(evaluator.uses_window_frame() && 
evaluator.evaluates_frames_independently())

Review Comment:
   @comphead thanks for this! No test fails if this check drops 
`evaluates_frames_independently()`: a user-defined function that uses the 
window frame without the flag would then get one `evaluate_ranges` call over 
all partitions of a `WindowAggExec` input, and all 
`user_defined_window_functions` tests and `window*.slt` still pass. Could you 
add a test that pins one partition per call? This one gives 7 on the PR and 10 
with the flag check removed:
   
   <details><summary>Test (passes on the PR, fails with the flag check 
removed)</summary>
   
   ```diff
   @@ struct TestState {
        evaluate_all_with_rank_called: AtomicUsize,
   +    /// The most rows that `evaluate` saw in `values`
   +    max_values_len: AtomicUsize,
   @@ impl PartitionEvaluator for OddCounter {
            self.test_state.inc_evaluate_called();
   +        self.test_state
   +            .max_values_len
   +            .fetch_max(values[0].len(), Ordering::SeqCst);
   @@
   +/// A function that uses the window frame without
   +/// `evaluates_frames_independently` sees one partition per call
   +#[tokio::test]
   +async fn test_udwf_window_frame_one_partition_per_call() {
   +    let test_state = 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 sql = "SELECT x, y, val, \
   +         odd_counter(val) OVER (PARTITION BY x ORDER BY y \
   +         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) \
   +         from t ORDER BY x, y";
   +    execute(&ctx, sql).await.unwrap();
   +
   +    // x = 2 has 7 of the 10 rows
   +    assert_eq!(test_state.max_values_len.load(Ordering::SeqCst), 7);
   +}
   ```
   
   </details>



##########
datafusion/physical-expr/src/window/standard.rs:
##########
@@ -70,6 +71,54 @@ impl StandardWindowExpr {
         }
         Ok(())
     }
+
+    /// Evaluates `evaluator`, which uses the window frame, on the frame of 
every
+    /// row of `partitions`, consecutive ranges of whole partitions in `batch`,
+    /// in one call
+    fn evaluate_frames(
+        &self,
+        mut evaluator: Box<dyn PartitionEvaluator>,
+        batch: &RecordBatch,
+        partitions: &[Range<usize>],
+    ) -> Result<ArrayRef> {
+        // Rows outside `partitions` are not evaluated
+        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 mut values = self.evaluate_args(&batch)?;
+        let order_bys = get_orderby_values(self.order_by_columns(&batch)?);
+        let sort_options = self.order_by.iter().map(|o| o.options).collect();
+        let mut window_frame_ctx =
+            WindowFrameContext::new(Arc::clone(&self.window_frame), 
sort_options);
+        let mut partition_order_bys = Vec::with_capacity(order_bys.len());
+        let mut ranges = Vec::with_capacity(num_rows);
+        for partition in partitions {

Review Comment:
   Agree with @kumarUjjawal, and I measured it: on 8M rows with an `INT` 
argument and 1000-row partitions, `first_value(v) OVER (PARTITION BY k ORDER BY 
i ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)` peaks at 1006 MB 
RSS on the PR against 845 MB on `main`. That is about 20 bytes per row of frame 
ranges and `take` indices, and `WindowAggExec` reserves none of it (#26707). 
Evaluating runs of partitions of at most `batch_size` rows per 
`evaluate_partitions` call would keep this batch-sized. Fine as a follow-up, 
since an input without PARTITION BY already allocates ranges for every row on 
`main`.



##########
datafusion/physical-expr/src/window/standard.rs:
##########
@@ -70,6 +71,54 @@ impl StandardWindowExpr {
         }
         Ok(())
     }
+
+    /// Evaluates `evaluator`, which uses the window frame, on the frame of 
every
+    /// row of `partitions`, consecutive ranges of whole partitions in `batch`,
+    /// in one call
+    fn evaluate_frames(
+        &self,
+        mut evaluator: Box<dyn PartitionEvaluator>,
+        batch: &RecordBatch,
+        partitions: &[Range<usize>],
+    ) -> Result<ArrayRef> {
+        // Rows outside `partitions` are not evaluated
+        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 mut values = self.evaluate_args(&batch)?;
+        let order_bys = get_orderby_values(self.order_by_columns(&batch)?);
+        let sort_options = self.order_by.iter().map(|o| o.options).collect();
+        let mut window_frame_ctx =
+            WindowFrameContext::new(Arc::clone(&self.window_frame), 
sort_options);
+        let mut partition_order_bys = Vec::with_capacity(order_bys.len());
+        let mut ranges = Vec::with_capacity(num_rows);
+        for partition in partitions {
+            let start = partition.start - offset;
+            partition_order_bys.clear();
+            partition_order_bys.extend(
+                order_bys
+                    .iter()
+                    .map(|column| column.slice(start, partition.len())),
+            );
+            // Only the state of a GROUPS frame is specific to a partition

Review Comment:
   Optional cleanup: this comment could say why RANGE needs no reset, since 
that relies on its comparator cache being keyed by the ORDER BY arrays:
   
   ```suggestion
               // A GROUPS frame keeps the group boundaries of the previous 
partition.
               // A RANGE frame caches only a comparator keyed by the ORDER BY 
arrays,
               // which are new slices for each partition.
   ```



##########
datafusion/expr/src/partition_evaluator.rs:
##########
@@ -214,6 +214,14 @@ pub trait PartitionEvaluator: Debug + Send + std::any::Any 
{
         ScalarValue::iter_to_array(results)
     }
 
+    /// Returns `true` if, until [`Self::memoize`] is called, the result of
+    /// [`Self::evaluate_ranges`] for a frame depends only on `values` and that
+    /// frame. A new evaluator can then evaluate the frames of several small
+    /// partitions in one call.

Review Comment:
   Agree with @kumarUjjawal: "depends only on `values` and that frame" still 
allows reading rows of `values` outside the frame, which breaks once `values` 
holds several partitions. Maybe:
   
   ```rs
       /// Returns `true` if, until [`Self::memoize`] is called, the result of
       /// [`Self::evaluate_ranges`] for a frame depends only on the rows of
       /// `values` inside that frame. A new evaluator can then evaluate the
       /// frames of several partitions, concatenated in `values`, in one call.
   ```



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