kumarUjjawal commented on code in PR #27466:
URL: https://github.com/apache/datafusion/pull/27466#discussion_r4610489467
##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1095,13 +1121,26 @@ 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 {
+ let complete = 1..n_partitions - 1;
+ self.complete_out = compute_window_aggregates(
Review Comment:
Complete-partition results pass from `evaluate_partition_batches` to
`calculate_out_columns` through the mutable `SortedSearch::complete_out` field.
Correct output relies on unstated rules: exactly one `calculate_out_columns`
call per batch, and the last entry of every expression's state map being that
batch's last partition.
##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1095,13 +1121,26 @@ 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 {
Review Comment:
The optimization is all-or-nothing: one unsupported expression
(`row_number`, `rank`, `lag`, or any UDWF without the flag) in the same window
node turns it off for every expression.
##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1661,12 +1702,25 @@ fn window_lookahead(exprs: &[Arc<dyn WindowExpr>]) ->
Option<WindowLookahead> {
Some(lookahead)
}
+fn is_aggregate(expr: &Arc<dyn WindowExpr>) -> bool {
+ expr.as_any().is::<PlainAggregateWindowExpr>()
+ || expr.as_any().is::<SlidingAggregateWindowExpr>()
+}
+
+/// See [`SortedSearch::can_evaluate_complete`]
+fn can_evaluate_complete(expr: &Arc<dyn WindowExpr>) -> bool {
Review Comment:
`can_evaluate_complete` decides eligibility by downcasting to concrete types
and repeats the capability check that `StandardWindowExpr::evaluate_partitions`
already does, instead of asking the `WindowExpr` trait.
##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -1575,23 +1616,23 @@ fn argmin<T: PartialOrd>(data: impl Iterator<Item = T>)
-> Option<(usize, T)> {
.min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(Ordering::Equal))
}
-/// Calculates the section we can show results for expression
+/// Calculates the section we can show results for expression. `complete`
+/// holds the results of the partitions between the last two buffered ones
+/// (see [`SortedSearch::complete_out`]).
fn get_aggregate_result_out_column(
partition_window_agg_states: &PartitionWindowAggStates,
+ complete: Option<&ArrayRef>,
len_to_show: usize,
) -> Result<ArrayRef> {
let mut result = None;
let mut running_length = 0;
- let mut batches_to_concat =
Vec::with_capacity(partition_window_agg_states.len());
+ let mut batches_to_concat =
Vec::with_capacity(partition_window_agg_states.len() + 1);
// We assume that iteration order is according to insertion order
- for (
- _,
- WindowState {
- state: WindowAggState { out_col, .. },
- ..
- },
- ) in partition_window_agg_states
- {
+ let mut out_cols = partition_window_agg_states
+ .values()
+ .map(|WindowState { state, .. }| &state.out_col);
+ let last = complete.and_then(|_| out_cols.next_back());
Review Comment:
`get_aggregate_result_out_column` places `complete` before the last
partition by taking `next_back()` from each expression's IndexMap. This assumes
every expression's map ends with the same partition, the current batch's last
one, which nothing enforces.
##########
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:
`test_udwf_bounded_window_complete_partition` never exercises the new path.
`odd_counter` neither sets `evaluates_frames_independently` nor
`uses_window_frame`, so `can_evaluate_complete` is false and the query is
buffered exactly as before.
##########
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:
`complete_partitions` case does not assert its plan (EXPLAIN). Nothing
checks that the query runs through `BoundedWindowAggExec` in Sorted mode with
8-row input batches that actually contain complete partitions.
##########
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:
`compute_window_aggregates` builds a `Vec<Option<ArrayRef>>` and returns it
through `.flatten()`. Any slot left `None` would be dropped silently instead of
raising an error.
##########
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:
Should we document that results must remain equivalent when partition
arrays are concatenated and frame indices are rebased; otherwise UDWF authors
can satisfy the stated contract and still obtain incorrect results.
##########
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:
Bound temporary frame storage in WindowAggExec. When called from
`WindowAggExec`, this allocates frame ranges for the entire accumulated input,
rather than releasing them after each partition as before.
##########
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()?;
Review Comment:
`StandardWindowExpr::evaluate_partitions` calls `create_evaluator()` on
every call only to check two flags, then throws the evaluator away when the
function does not qualify.
--
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]