comphead commented on code in PR #27466:
URL: https://github.com/apache/datafusion/pull/27466#discussion_r4620295672
##########
datafusion/core/tests/user_defined/user_defined_window_functions.rs:
##########
@@ -369,6 +369,43 @@ async fn test_udwf_bounded_window_returns_null() {
assert_eq!(test_state.evaluate_all_called(), 0);
}
+/// A partition that starts and ends inside an input batch is evaluated with
+/// the same calls as one that is buffered
+#[tokio::test]
+async fn test_udwf_bounded_window_complete_partition() {
+ let test_state = TestState::new().with_supports_bounded_execution();
Review Comment:
Right, and that is what it pins: a function that is neither an aggregate nor
sets the flag keeps the buffered path for a partition inside a batch. Admitting
every window function in `can_evaluate_complete` makes it fail, because
`evaluate` would then call `evaluate_all` for that partition. I reworded its
doc to say this. The direct path is covered by the `complete_partitions` case
in `window.slt`.
##########
datafusion/sqllogictest/test_files/window.slt:
##########
@@ -8126,6 +8126,55 @@ DROP TABLE ordered_through_cast;
statement ok
DROP TABLE per_partition_constant;
+# Partitions that start and end inside an input batch are evaluated without
+# being buffered: aggregates one partition at a time, and FIRST_VALUE,
+# LAST_VALUE and NTH_VALUE for all of them in one call. With 8-row batches,
+# k = 2, 3 and 4 are complete in the first batch and k = 6 and 7 in the
+# second, which starts inside the buffered k = 5 and ends inside k = 8. `o`
+# repeats across partitions, so a frame that leaves its partition changes a
+# result.
+# https://github.com/apache/datafusion/issues/26541
+# https://github.com/apache/datafusion/issues/27463
+statement ok
+CREATE TABLE complete_partitions(k INT, o INT, v INT) AS VALUES
+ (1, 1, 10), (2, 2, NULL), (2, 3, 20), (3, 3, NULL), (3, 4, 30), (4, 1, 40),
(4, 3, 41),
+ (5, 1, 50), (5, 2, 51), (6, 2, NULL), (6, 3, NULL), (7, 1, 70), (8, 1, 80),
(8, 2, 81);
+
+statement ok
+set datafusion.execution.batch_size = 8;
+
+query IIIIIIIII
Review Comment:
Added an `EXPLAIN` of the same query, which shows `BoundedWindowAggExec` in
`Sorted` mode over the `SortExec`. The results check the rest: injecting faults
into the complete-partition path (frames that leave their partition, a stale
frame or GROUPS state, the splice order, the first partition evaluated
directly) makes this case fail.
##########
datafusion/physical-plan/src/windows/utils.rs:
##########
@@ -22,3 +26,36 @@ 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.
+pub(crate) fn compute_window_aggregates(
+ window_expr: &[Arc<dyn WindowExpr>],
+ batch: &RecordBatch,
+ partitions: &[Range<usize>],
+) -> Result<Vec<ArrayRef>> {
+ let mut results = Vec::with_capacity(window_expr.len());
+ // The expressions that are evaluated one partition at a time, and their
results
+ let mut per_partition = vec![];
+ for (idx, expr) in window_expr.iter().enumerate() {
+ let result = expr.evaluate_partitions(batch, partitions)?;
+ if result.is_none() {
+ per_partition.push((idx, Vec::with_capacity(partitions.len())));
+ }
+ results.push(result);
+ }
+ if !per_partition.is_empty() {
+ for range in partitions {
+ let partition = batch.slice(range.start, range.len());
+ for (idx, arrays) in &mut per_partition {
+ arrays.push(window_expr[*idx].evaluate(&partition)?);
+ }
+ }
+ }
+ for (idx, arrays) in per_partition {
+ let arrays = arrays.iter().map(|a| a.as_ref()).collect::<Vec<_>>();
+ results[idx] = Some(concat(&arrays)?);
+ }
+ Ok(results.into_iter().flatten().collect())
Review Comment:
Rewrote it so that every expression gets exactly one concatenated array,
with no `Option` slots.
##########
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:
Fixed here rather than in a follow-up. `compute_window_aggregates` now gives
`evaluate_partitions` runs of at most `batch_size` rows, or one larger
partition, and `WindowAggExec` passes its `batch_size`. On the query jayzhan211
measured (8M rows, 1000-row partitions, `first_value` to `UNBOUNDED
FOLLOWING`), peak RSS goes from 962 MB to 803 MB, the same as `main` (804 MB).
The extra concatenation costs at most about 3% for a struct argument and
nothing measurable for an `INT`.
##########
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:
Adopted the wording suggested in this thread. `NthValueEvaluator` reads only
the validity bits inside the frame and gathers one row of it, so it meets the
stricter contract.
##########
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:
Confirmed: with the flag check removed, every
`user_defined_window_functions` test and every `window*.slt` file still passed.
Instead of a new test, `test_udwf_bounded_window` now asserts it. It already
runs `odd_counter` with `uses_window_frame` and without the flag in
`WindowAggExec`, so it only needed `target_partitions = 1` and the
`max_values_len` counter from your snippet. It sees 7 rows on the PR and fails
with 10 when the check is removed.
--
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]