comphead commented on code in PR #27466:
URL: https://github.com/apache/datafusion/pull/27466#discussion_r4744674219
##########
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:
Confirmed, thanks. The fill still left a gap, so I measured more before
changing it.
- On Linux (an arm64 container, criterion, each case in its own process, two
rounds), the gather and the fill were both 1.4x to 1.7x slower than `main` for
`max(s)` with 2000 to 4000 rows per partition.
- A samply profile of `max(s)` with 4000-row partitions shows why. Over 60
queries the fill spends 137 ms in `concat`, against 50 ms on `main`, and 74 ms
of it in the concatenation inside each run. `WindowAggExec` copied each run and
then all runs again.
So in 7335a1ad6 `evaluate_partitions` may decline a run, and
`compute_window_aggregates` then evaluates its partitions one at a time, as
`main` does. Constant aggregates gather while a run's partitions average fewer
than 32 rows, and decline otherwise. On 4M rows (macOS, window
`elapsed_compute`, median of three rounds, each in a new process):
| `OVER (PARTITION BY k)`, rows per partition | main | gather (`e0d1948b1`)
| fill (suggestion) | now |
|---|---:|---:|---:|---:|
| `sum(v)`, 1 | 710 ms | 286 ms | 406 ms | 283 ms |
| `sum(v)`, 16 | 49.0 ms | 23.7 ms | 29.9 ms | 23.1 ms |
| `sum(v)`, 100 | 12.0 ms | 9.0 ms | 8.9 ms | 11.1 ms |
| `sum(v)`, 4000 | 3.9 ms | 6.0 ms | 4.5 ms | 4.1 ms |
| `max(s)`, 1 | 905 ms | 337 ms | 498 ms | 330 ms |
| `max(s)`, 100 | 28.7 ms | 32.0 ms | 18.6 ms | 24.4 ms |
| `max(s)`, 2000 | 14.7 ms | 23.9 ms | 14.1 ms | 13.8 ms |
| `max(s)`, 4000 | 13.3 ms | 22.9 ms | 13.7 ms | 13.2 ms |
Between 32 and about 100 rows per partition the fill was faster, so this
gives up as much as 30% there, in exchange for matching `main` on large
partitions. I did not run the final code on Linux. The aggregate differential
against `main` gained a key with 50-row partitions, so declined runs are
compared too.
##########
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:
Confirmed: with `partition_runs(partitions, usize::MAX)` every test still
passed. In 7335a1ad6 the existing flag-on run became a loop over `batch_size`
8192 and 4, which expects 10 and 7 rows, rather than a third copy of the block.
Without the limit it now fails with 10 against 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]