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


##########
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();

Review Comment:
   `per_partition.clear()` runs for every run, so every unsupported expression 
is asked again each time.



##########
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)?;

Review Comment:
   `aggregate_evaluate_partitions` builds one array for all partitions of a run 
with `ScalarValue::iter_to_array`. For Dictionary results this calls 
`dict_from_values`, which gives every scalar its own key with no 
de-duplication. Small key types now overflow across partitions, where `main` 
overflowed only within one partition.



##########
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();

Review Comment:
   `calculate_frames` slices every ORDER BY column for every partition, even 
for ROWS frames. `WindowFrameContext::Rows` never reads `range_columns`.



##########
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:
   Cap complete-partition runs for oversized input batches



##########
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:
   Avoid slicing ORDER BY columns for ROWS frame calculation



##########
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:
   do we need to keep this public?



##########
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:
   Bound the search for the end of a partition run



##########
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)?

Review Comment:
   Avoid rebuilding ineligible UDWF evaluators for every run



##########
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)?;

Review Comment:
   Use a dictionary-aware builder or decline the batched path for affected 
result types, and add a regression test with more result positions than the key 
type can represent.



##########
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:
   Skip the identity gather for one-row partitions



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