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


##########
datafusion/physical-expr/src/window/window_expr.rs:
##########
@@ -601,6 +685,50 @@ fn is_row_ahead(
     Ok(ahead)
 }
 
+/// The rows of `partitions`, consecutive ranges of whole partitions
+pub(crate) fn partition_span(partitions: &[Range<usize>]) -> Range<usize> {
+    partitions.first().map_or(0, |p| p.start)..partitions.last().map_or(0, |p| 
p.end)
+}
+
+/// Calculates the frame of every row of `partitions`, consecutive ranges of
+/// whole partitions, relative to the start of the first partition.
+/// `order_bys` holds the ORDER BY values of the rows of `partitions`.
+pub(crate) fn calculate_frames(
+    window_frame: &Arc<WindowFrame>,
+    order_by: &[PhysicalSortExpr],
+    order_bys: &[ArrayRef],
+    partitions: &[Range<usize>],
+) -> Result<Vec<Range<usize>>> {
+    let span = partition_span(partitions);
+    let offset = span.start;
+    let sort_options = order_by.iter().map(|o| o.options).collect();
+    let mut window_frame_ctx =
+        WindowFrameContext::new(Arc::clone(window_frame), sort_options);
+    let mut partition_order_bys = Vec::with_capacity(order_bys.len());
+    let mut frames = Vec::with_capacity(span.len());
+    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())),
+        );

Review Comment:
   Done in cc0ea5871, with the numbers in the comment above.
   



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1099,13 +1134,32 @@ 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 {
+            debug_assert!(
+                self.complete_out.is_empty(),
+                "the complete partitions of the previous batch must be emitted"
+            );
+            let complete = 1..n_partitions - 1;
+            // One run, since these partitions are inside one input batch
+            self.complete_out = compute_window_aggregates(
+                window_expr,
+                record_batch,
+                &partition_points[complete.clone()],
+                num_rows,

Review Comment:
   Confirmed. I measured the heap with a counting allocator: one 4M-row sorted 
input batch, 1000-row partitions and a running `count`, at `batch_size` 8192. 
The previous head peaked 352 MB above the input, against 70 MB on `main`, 
because its single run held a frame and a `ScalarValue` for every row. In 
cc0ea5871 `SortedSearch` passes the session `batch_size` to 
`compute_window_aggregates`, and the peak is 64 MB.
   



##########
datafusion/physical-expr/src/window/window_expr.rs:
##########
@@ -211,6 +225,76 @@ pub trait AggregateWindowExpr: WindowExpr {
         )
     }
 
+    /// Evaluates the window function on `partitions` in one call, or returns
+    /// `None` where evaluating them one at a time is cheaper (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<Option<ArrayRef>> {
+        let span = partition_span(partitions);
+        // The gather below costs more than evaluating partitions one at a time
+        // once they average 32 rows
+        let is_constant = self.is_constant_in_partition();
+        if is_constant && span.len() >= 32 * partitions.len() {
+            return Ok(None);
+        }
+        let offset = span.start;
+        let batch = batch.slice(offset, span.len());
+        let values = self.evaluate_args(&batch)?;
+        let filter_mask_arr =
+            evaluate_expressions_to_arrays(self.filter_expr(), &batch)?.pop();
+        let filter_mask = filter_mask_arr
+            .as_deref()
+            .map(as_boolean_array)
+            .transpose()?;
+        // A constant result is evaluated once, on the whole 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;
+            }
+        }
+        let results = ScalarValue::iter_to_array(results)?;
+        if !is_constant {
+            return Ok(Some(results));
+        }
+        // Repeat the result of each partition for its rows
+        let mut indices = Vec::with_capacity(batch.num_rows());

Review Comment:
   Done in cc0ea5871: when every partition of a run has one row, the results 
are returned without the gather. A samply profile of that case shows the `take` 
gone (22 ms of 6.2 s of CPU over 20 queries), so the end-to-end gain is within 
noise.
   



##########
datafusion/physical-plan/src/windows/utils.rs:
##########
@@ -22,3 +26,69 @@ pub(crate) fn create_schema(
         .finish()
         .with_metadata(input_schema.metadata().clone()))
 }
+
+/// Evaluates `window_expr` on each of the whole partitions of `batch` in
+/// `partitions`, and returns one array per window expression that covers
+/// `partitions` in order. An expression that evaluates several partitions in
+/// one call gets runs of at most `batch_size` rows, so that its frames stay
+/// batch-sized. A run of one partition, which can be larger, and a run that
+/// an expression declines are evaluated one partition at a time.
+pub(crate) fn compute_window_aggregates(
+    window_expr: &[Arc<dyn WindowExpr>],
+    batch: &RecordBatch,
+    partitions: &[Range<usize>],
+    batch_size: usize,
+) -> Result<Vec<ArrayRef>> {
+    // The arrays to concatenate for each expression
+    let mut results = vec![vec![]; window_expr.len()];
+    // The expressions that declined the current run
+    let mut per_partition = vec![];
+    for run in partition_runs(partitions, batch_size) {
+        per_partition.clear();
+        for (idx, expr) in window_expr.iter().enumerate() {
+            let result = if run.len() > 1 {
+                expr.evaluate_partitions(batch, run)?
+            } else {
+                None
+            };
+            match result {
+                Some(result) => results[idx].push(result),
+                None => per_partition.push(idx),
+            }
+        }
+        if per_partition.is_empty() {
+            continue;
+        }
+        for range in run {
+            let partition = batch.slice(range.start, range.len());
+            for &idx in &per_partition {
+                results[idx].push(window_expr[idx].evaluate(&partition)?);
+            }
+        }
+    }
+    results
+        .iter()
+        .map(|arrays| {
+            let arrays = arrays.iter().map(|a| a.as_ref()).collect::<Vec<_>>();
+            Ok(concat(&arrays)?)
+        })
+        .collect()
+}
+
+/// Splits `partitions`, consecutive row ranges, into runs of at most
+/// `max_rows` rows, or of one larger partition
+fn partition_runs(
+    partitions: &[Range<usize>],
+    max_rows: usize,
+) -> impl Iterator<Item = &[Range<usize>]> {
+    let mut rest = partitions;
+    std::iter::from_fn(move || {
+        let first = rest.first()?;
+        let len = rest
+            .partition_point(|p| p.end - first.start <= max_rows)
+            .max(1);

Review Comment:
   `partition_point` is already a binary search, so finding the end of a run 
costs at most log2 of the remaining partitions: 22 probes with 4M one-row 
partitions, against 13 if bounded to `batch_size`, once per run of up to 
`batch_size` rows. I kept it as is, since bounding it would not be measurable.
   



##########
datafusion/expr/src/window_state.rs:
##########
@@ -196,6 +196,19 @@ impl WindowFrameContext {
         }
     }
 
+    /// Clears the state kept from previous rows, so that the context can
+    /// calculate the frames of a new partition
+    pub fn reset(&mut self) {

Review Comment:
   It has to be public: the only caller, `calculate_frames`, is in 
`datafusion-physical-expr`, while `WindowFrameContext` is in `datafusion-expr`, 
where `new` and `calculate_range` are public as well. A new context per 
partition avoids the method, but it was slower: cloning the shared 
`Arc<WindowFrame>` for each of 1M one-row partitions took 90 ms against 7 ms 
with a reused context, at `target_partitions = 18`.
   



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