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


##########
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:
   Confirmed. `any_value` keeps the dictionary type, and over 300 one-row 
partitions of a `Dictionary(Int8, Utf8)` column it failed on the previous head 
with `Internal error: Can not create index of type Int8 from value 128`, both 
in `WindowAggExec` (no ORDER BY) and in `BoundedWindowAggExec` (with ORDER BY). 
`main` returned all 300 rows. `min` and `max` return the value type, so they 
were not affected. Fixed in cc0ea5871, see the next comment.
   



##########
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:
   Done in cc0ea5871 by declining: an aggregate with a dictionary result now 
evaluates each partition on its own, as on `main`. The new `window.slt` query 
runs `any_value` over those 300 partitions in both operators, and fails with 
the error above without the fix. I preferred declining over a dictionary-aware 
builder, which would need its own path for a rare result type.
   



##########
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:
   Right, and for a function without `evaluates_frames_independently` each of 
those asks created an evaluator just to read its flags. In cc0ea5871 
`StandardWindowExpr` checks once and keeps the answer in a `OnceLock`, so the 
later asks return `None` without an evaluator. The asks per run stay, because 
an aggregate can decline one run and take the next.
   



##########
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:
   Done in cc0ea5871: the flag check is cached in `StandardWindowExpr`, so an 
ineligible function no longer creates an evaluator per run.
   



##########
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:
   Confirmed, `WindowFrameContext::Rows` never reads `range_columns`. In 
cc0ea5871 `calculate_frames` passes no ORDER BY columns for ROWS frames. On 4M 
rows (window `elapsed_compute`, median of two rounds, each in a new process):
   
   | case | before | after |
   |---|---:|---:|
   | `nth_value(v, 2)`, `ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING`, 1 row per 
partition | 97.0 ms | 41.9 ms |
   | the same, 4 rows per partition | 36.1 ms | 26.5 ms |
   | `sum(v)`, `ROWS BETWEEN 1 PRECEDING AND CURRENT ROW`, 1 row per partition 
| 360 ms | 308 ms |
   | `sum(v)` with a RANGE frame, 1 row per partition (unchanged path) | 517 ms 
| 521 ms |
   



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