Apache DataFusion SQL Query Engine
Do not break pipeline for window queries with GROUPS (#5587)
Mustafa Akurc62938280a96
diff --git a/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs b/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rsindex 0ac836cf28..fa276c4238 100644--- a/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs+++ b/datafusion/core/src/physical_plan/windows/bounded_window_agg_exec.rs@@ -353,12 +353,12 @@ impl PartitionByHandler for SortedPartitionByBoundedWindowStream {// For instance, if `n_out` number of rows are calculated, we can remove// first `n_out` rows from `self.input_buffer_record_batch`.fn prune_state(&mut self, n_out: usize) -> Result<()> {+ // Prune `self.window_agg_states`:+ self.prune_out_columns(n_out)?;// Prune `self.partition_batches`:self.prune_partition_batches()?;// Prune `self.input_buffer_record_batch`:self.prune_input_batch(n_out)?;- // Prune `self.window_agg_states`:- self.prune_out_columns(n_out)?;Ok(())}@@ -548,9 +548,9 @@ impl SortedPartitionByBoundedWindowStream {for (partition_row, WindowState { state: value, .. }) in window_agg_state {let n_prune =min(value.window_frame_range.start, value.last_calculated_index);- if let Some(state) = n_prune_each_partition.get_mut(partition_row) {- if n_prune < *state {- *state = n_prune;+ if let Some(current) = n_prune_each_partition.get_mut(partition_row) {+ if n_prune < *current {+ *current = n_prune;}} else {n_prune_each_partition.insert(partition_row.clone(), n_prune);@@ -571,15 +571,7 @@ impl SortedPartitionByBoundedWindowStream {// Update state indices since we have pruned some rows from the beginning:for window_agg_state in self.window_agg_states.iter_mut() {- let window_state =- window_agg_state.get_mut(partition_row).ok_or_else(err)?;- let mut state = &mut window_state.state;- state.window_frame_range = Range {- start: state.window_frame_range.start - n_prune,- end: state.window_frame_range.end - n_prune,- };- state.last_calculated_index -= n_prune;- state.offset_pruned_rows += n_prune;+ window_agg_state[partition_row].state.prune_state(*n_prune);}}Ok(())diff --git a/datafusion/core/tests/sql/window.rs b/datafusion/core/tests/sql/window.rsindex 8f95eba572..535e1d8917 100644--- a/datafusion/core/tests/sql/window.rs+++ b/datafusion/core/tests/sql/window.rs@@ -61,7 +61,20 @@ async fn window_frame_creation_type_checking() -> Result<()> {).await}-fn write_test_data_to_parquet(tmpdir: &TempDir, n_file: usize) -> Result<()> {+fn split_record_batch(batch: RecordBatch, n_split: usize) -> Vec<RecordBatch> {+ let n_chunk = batch.num_rows() / n_split;+ let mut res = vec![];+ for i in 0..n_split - 1 {+ let chunk = batch.slice(i * n_chunk, n_chunk);+ res.push(chunk);+ }+ let start = (n_split - 1) * n_chunk;+ let len = batch.num_rows() - start;+ res.push(batch.slice(start, len));+ res+}++fn get_test_data(n_split: usize) -> Result<Vec<RecordBatch>> {let ts_field = Field::new("ts", DataType::Int32, false);let inc_field = Field::new("inc_col", DataType::Int32, false);let desc_field = Field::new("desc_col", DataType::Int32, false);@@ -100,19 +113,19 @@ fn write_test_data_to_parquet(tmpdir: &TempDir, n_file: usize) -> Result<()> {])),],)?;- let n_chunk = batch.num_rows() / n_file;- for i in 0..n_file {+ Ok(split_record_batch(batch, n_split))+}++fn write_test_data_to_parquet(tmpdir: &TempDir, n_split: usize) -> Result<()> {+ let batches = get_test_data(n_split)?;+ for (i, batch) in batches.into_iter().enumerate() {let target_file = tmpdir.path().join(format!("{i}.parquet"));let file = File::create(target_file).unwrap();// Default writer propertieslet props = WriterProperties::builder().build();- let chunks_start = i * n_chunk;- let cur_batch = batch.slice(chunks_start, n_chunk);- // let chunks_end = chunks_start + n_chunk;- let mut writer =- ArrowWriter::try_new(file, cur_batch.schema(), Some(props)).unwrap();+ let mut writer = ArrowWriter::try_new(file, batch.schema(), Some(props)).unwrap();- writer.write(&cur_batch).expect("Writing batch");+ writer.write(&batch).expect("Writing batch");// writer must be closed to write footerwriter.close().unwrap();@@ -120,12 +133,11 @@ fn write_test_data_to_parquet(tmpdir: &TempDir, n_file: usize) -> Result<()> {Ok(())}-async fn get_test_context(tmpdir: &TempDir) -> Result<SessionContext> {+async fn get_test_context(tmpdir: &TempDir, n_batch: usize) -> Result<SessionContext> {let session_config = SessionConfig::new().with_target_partitions(1);let ctx = SessionContext::with_config(session_config);let parquet_read_options = ParquetReadOptions::default();- // The sort order is specified (not actually correct in this case)let file_sort_order = [col("ts")].into_iter().map(|e| {@@ -139,7 +151,7 @@ async fn get_test_context(tmpdir: &TempDir) -> Result<SessionContext> {.to_listing_options(&ctx.copied_config()).with_file_sort_order(Some(file_sort_order));- write_test_data_to_parquet(tmpdir, 1)?;+ write_test_data_to_parquet(tmpdir, n_batch)?;let provided_schema = None;let sql_definition = None;ctx.register_listing_table(@@ -160,7 +172,7 @@ mod tests {#[tokio::test]async fn test_source_sorted_aggregate() -> Result<()> {let tmpdir = TempDir::new().unwrap();- let ctx = get_test_context(&tmpdir).await?;+ let ctx = get_test_context(&tmpdir, 1).await?;let sql = "SELECTSUM(inc_col) OVER(ORDER BY ts RANGE BETWEEN 10 PRECEDING AND 1 FOLLOWING) as sum1,@@ -235,7 +247,7 @@ mod tests {#[tokio::test]async fn test_source_sorted_builtin() -> Result<()> {let tmpdir = TempDir::new().unwrap();- let ctx = get_test_context(&tmpdir).await?;+ let ctx = get_test_context(&tmpdir, 1).await?;let sql = "SELECTFIRST_VALUE(inc_col) OVER(ORDER BY ts RANGE BETWEEN 10 PRECEDING and 1 FOLLOWING) as fv1,@@ -309,7 +321,7 @@ mod tests {#[tokio::test]async fn test_source_sorted_unbounded_preceding() -> Result<()> {let tmpdir = TempDir::new().unwrap();- let ctx = get_test_context(&tmpdir).await?;+ let ctx = get_test_context(&tmpdir, 1).await?;let sql = "SELECTSUM(inc_col) OVER(ORDER BY ts ASC RANGE BETWEEN UNBOUNDED PRECEDING AND 5 FOLLOWING) as sum1,@@ -368,7 +380,7 @@ mod tests {#[tokio::test]async fn test_source_sorted_unbounded_preceding_builtin() -> Result<()> {let tmpdir = TempDir::new().unwrap();- let ctx = get_test_context(&tmpdir).await?;+ let ctx = get_test_context(&tmpdir, 1).await?;let sql = "SELECTFIRST_VALUE(inc_col) OVER(ORDER BY ts ASC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING) as first_value1,diff --git a/datafusion/core/tests/sqllogictests/test_files/window.slt b/datafusion/core/tests/sqllogictests/test_files/window.sltindex 148c7a4fd0..85a5bc18d4 100644--- a/datafusion/core/tests/sqllogictests/test_files/window.slt+++ b/datafusion/core/tests/sqllogictests/test_files/window.slt@@ -2038,3 +2038,39 @@ SELECTstatement okset datafusion.execution.target_partitions = 2;++# test_window_agg_with_bounded_group+query TT+EXPLAIN SELECT SUM(c12) OVER(ORDER BY c1, c2 GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as sum1,+ SUM(c12) OVER(ORDER BY c1 GROUPS BETWEEN 5 PRECEDING AND 3 PRECEDING) as sum2+ FROM aggregate_test_100 ORDER BY c9 LIMIT 5+----+logical_plan+Projection: sum1, sum2+ Limit: skip=0, fetch=5+ Sort: aggregate_test_100.c9 ASC NULLS LAST, fetch=5+ Projection: SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING AS sum1, SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST] GROUPS BETWEEN 5 PRECEDING AND 3 PRECEDING AS sum2, aggregate_test_100.c9+ WindowAggr: windowExpr=[[SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST] GROUPS BETWEEN 5 PRECEDING AND 3 PRECEDING]]+ WindowAggr: windowExpr=[[SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING]]+ TableScan: aggregate_test_100 projection=[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13]+physical_plan+ProjectionExec: expr=[sum1@0 as sum1, sum2@1 as sum2]+ GlobalLimitExec: skip=0, fetch=5+ SortExec: fetch=5, expr=[c9@2 ASC NULLS LAST]+ ProjectionExec: expr=[SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST, aggregate_test_100.c2 ASC NULLS LAST] GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING@13 as sum1, SUM(aggregate_test_100.c12) ORDER BY [aggregate_test_100.c1 ASC NULLS LAST] GROUPS BETWEEN 5 PRECEDING AND 3 PRECEDING@14 as sum2, c9@8 as c9]+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c12): Ok(Field { name: "SUM(aggregate_test_100.c12)", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Groups, start_bound: Preceding(UInt64(5)), end_bound: Preceding(UInt64(3)) }]+ BoundedWindowAggExec: wdw=[SUM(aggregate_test_100.c12): Ok(Field { name: "SUM(aggregate_test_100.c12)", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Groups, start_bound: Preceding(UInt64(1)), end_bound: Following(UInt64(1)) }]+ SortExec: expr=[c1@0 ASC NULLS LAST,c2@1 ASC NULLS LAST]+ CsvExec: files={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, has_header=true, limit=None, projection=[c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13]++query RR+SELECT SUM(c12) OVER(ORDER BY c1, c2 GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as sum1,+ SUM(c12) OVER(ORDER BY c1 GROUPS BETWEEN 5 PRECEDING AND 3 PRECEDING) as sum2+ FROM aggregate_test_100 ORDER BY c9 LIMIT 5+----+4.561269874379 18.036183428008+6.808931568966 10.238448667883+2.994840293343 NULL+9.674390599321 NULL+7.728066219895 NULL+diff --git a/datafusion/core/tests/window_fuzz.rs b/datafusion/core/tests/window_fuzz.rsindex e037586009..a71aab280e 100644--- a/datafusion/core/tests/window_fuzz.rs+++ b/datafusion/core/tests/window_fuzz.rs@@ -227,9 +227,7 @@ fn get_random_window_frame(rng: &mut StdRng) -> WindowFrame {} else if rand_num < 2 {WindowFrameUnits::Rows} else {- // For now we do not support GROUPS in BoundedWindowAggExec implementation- // TODO: once GROUPS handling is available, use WindowFrameUnits::GROUPS in randomized tests also.- WindowFrameUnits::Range+ WindowFrameUnits::Groups};match units {// In range queries window frame boundaries should match column type@@ -256,8 +254,8 @@ fn get_random_window_frame(rng: &mut StdRng) -> WindowFrame {}window_frame}- // In window queries, window frame boundary should be Uint64- WindowFrameUnits::Rows => {+ // Window frame boundary should be UInt64 for both ROWS and GROUPS frames:+ WindowFrameUnits::Rows | WindowFrameUnits::Groups => {let start_bound = if start_bound.is_preceding {WindowFrameBound::Preceding(ScalarValue::UInt64(Some(start_bound.val as u64,@@ -286,10 +284,10 @@ fn get_random_window_frame(rng: &mut StdRng) -> WindowFrame {window_frame.start_bound =WindowFrameBound::Preceding(ScalarValue::UInt64(None));}+ // We never use UNBOUNDED FOLLOWING in test. Because that case is not prunable and+ // should work only with WindowAggExecwindow_frame}- // Once GROUPS support is added construct window frame for this case also- _ => todo!(),}}@@ -401,7 +399,7 @@ async fn run_window_test(assert_eq!((i, usual_line),(i, running_line),- "Inconsistent result for window_fn: {window_fn:?}, args:{args:?}"+ "Inconsistent result for window_frame: {window_frame:?}, window_fn: {window_fn:?}, args:{args:?}");}}diff --git a/datafusion/physical-expr/src/window/aggregate.rs b/datafusion/physical-expr/src/window/aggregate.rsindex e9b43cd070..95fd86148a 100644--- a/datafusion/physical-expr/src/window/aggregate.rs+++ b/datafusion/physical-expr/src/window/aggregate.rs@@ -27,7 +27,7 @@ use arrow::{array::ArrayRef, datatypes::Field};use datafusion_common::ScalarValue;use datafusion_common::{DataFusionError, Result};-use datafusion_expr::{Accumulator, WindowFrame, WindowFrameUnits};+use datafusion_expr::{Accumulator, WindowFrame};use crate::window::window_expr::{reverse_order_bys, AggregateWindowExpr};use crate::window::{@@ -115,11 +115,8 @@ impl WindowExpr for PlainAggregateWindowExpr {})?;let mut state = &mut window_state.state;if self.window_frame.start_bound.is_unbounded() {- state.window_frame_range.start = if state.window_frame_range.end >= 1 {- state.window_frame_range.end - 1- } else {- 0- };+ state.window_frame_range.start =+ state.window_frame_range.end.saturating_sub(1);}}Ok(())@@ -159,10 +156,8 @@ impl WindowExpr for PlainAggregateWindowExpr {}fn uses_bounded_memory(&self) -> bool {- // NOTE: Currently, groups queries do not support the bounded memory variant.self.aggregate.supports_bounded_execution()&& !self.window_frame.end_bound.is_unbounded()- && !matches!(self.window_frame.units, WindowFrameUnits::Groups)}}diff --git a/datafusion/physical-expr/src/window/built_in.rs b/datafusion/physical-expr/src/window/built_in.rsindex 70ddb2c767..329eac3334 100644--- a/datafusion/physical-expr/src/window/built_in.rs+++ b/datafusion/physical-expr/src/window/built_in.rs@@ -32,11 +32,11 @@ use crate::window::{};use crate::{expressions::PhysicalSortExpr, PhysicalExpr};use arrow::array::{new_empty_array, Array, ArrayRef};-use arrow::compute::{concat, SortOptions};+use arrow::compute::SortOptions;use arrow::datatypes::Field;use arrow::record_batch::RecordBatch;-use datafusion_common::{DataFusionError, Result, ScalarValue};-use datafusion_expr::{WindowFrame, WindowFrameUnits};+use datafusion_common::{Result, ScalarValue};+use datafusion_expr::WindowFrame;/// A window expr that takes the form of a built in window function#[derive(Debug)]@@ -104,17 +104,20 @@ impl WindowExpr for BuiltInWindowExpr {let mut row_wise_results = vec![];let (values, order_bys) = self.get_values_orderbys(batch)?;- let mut window_frame_ctx = WindowFrameContext::new(- &self.window_frame,- sort_options,- Range { start: 0, end: 0 },- );+ let mut window_frame_ctx =+ WindowFrameContext::new(self.window_frame.clone(), sort_options);+ let mut last_range = Range { start: 0, end: 0 };// We iterate on each row to calculate window frame range and and window function resultfor idx in 0..num_rows {- let range =- window_frame_ctx.calculate_range(&order_bys, num_rows, idx)?;+ let range = window_frame_ctx.calculate_range(+ &order_bys,+ &last_range,+ num_rows,+ idx,+ )?;let value = evaluator.evaluate_inside_range(&values, &range)?;row_wise_results.push(value);+ last_range = range;}ScalarValue::iter_to_array(row_wise_results.into_iter())} else if evaluator.include_rank() {@@ -139,26 +142,23 @@ impl WindowExpr for BuiltInWindowExpr {let out_type = field.data_type();let sort_options = self.order_by.iter().map(|o| o.options).collect::<Vec<_>>();for (partition_row, partition_batch_state) in partition_batches.iter() {- if !window_agg_state.contains_key(partition_row) {- let evaluator = self.expr.create_evaluator()?;- window_agg_state.insert(- partition_row.clone(),- WindowState {- state: WindowAggState::new(out_type)?,- window_fn: WindowFn::Builtin(evaluator),- },- );- };let window_state =- window_agg_state.get_mut(partition_row).ok_or_else(|| {- DataFusionError::Execution("Cannot find state".to_string())- })?;+ if let Some(window_state) = window_agg_state.get_mut(partition_row) {+ window_state+ } else {+ let evaluator = self.expr.create_evaluator()?;+ window_agg_state+ .entry(partition_row.clone())+ .or_insert(WindowState {+ state: WindowAggState::new(out_type)?,+ window_fn: WindowFn::Builtin(evaluator),+ })+ };let evaluator = match &mut window_state.window_fn {WindowFn::Builtin(evaluator) => evaluator,_ => unreachable!(),};let mut state = &mut window_state.state;- state.is_end = partition_batch_state.is_end;let (values, order_bys) =self.get_values_orderbys(&partition_batch_state.record_batch)?;@@ -166,13 +166,6 @@ impl WindowExpr for BuiltInWindowExpr {// We iterate on each row to perform a running calculation.let record_batch = &partition_batch_state.record_batch;let num_rows = record_batch.num_rows();- let last_range = state.window_frame_range.clone();- let mut window_frame_ctx = WindowFrameContext::new(- &self.window_frame,- sort_options.clone(),- // Start search from the last range- last_range,- );let sort_partition_points = if evaluator.include_rank() {let columns = self.sort_columns(record_batch)?;self.evaluate_partition_points(num_rows, &columns)?@@ -180,33 +173,43 @@ impl WindowExpr for BuiltInWindowExpr {vec![]};let mut row_wise_results: Vec<ScalarValue> = vec![];- let mut last_range = state.window_frame_range.clone();for idx in state.last_calculated_index..num_rows {- state.window_frame_range = if self.expr.uses_window_frame() {- window_frame_ctx.calculate_range(&order_bys, num_rows, idx)+ let frame_range = if self.expr.uses_window_frame() {+ state+ .window_frame_ctx+ .get_or_insert_with(|| {+ WindowFrameContext::new(+ self.window_frame.clone(),+ sort_options.clone(),+ )+ })+ .calculate_range(+ &order_bys,+ // Start search from the last range+ &state.window_frame_range,+ num_rows,+ idx,+ )} else {- evaluator.get_range(state, num_rows)+ evaluator.get_range(idx, num_rows)}?;- evaluator.update_state(state, &order_bys, &sort_partition_points)?;- let frame_range = &state.window_frame_range;// Exit if the range extends all the way:- if frame_range.end == num_rows && !state.is_end {+ if frame_range.end == num_rows && !partition_batch_state.is_end {break;}+ // Update last range+ state.window_frame_range = frame_range;+ evaluator.update_state(state, idx, &order_bys, &sort_partition_points)?;row_wise_results.push(evaluator.evaluate_stateful(&values)?);- last_range.clone_from(frame_range);- state.last_calculated_index += 1;}- state.window_frame_range = last_range;let out_col = if row_wise_results.is_empty() {new_empty_array(out_type)} else {ScalarValue::iter_to_array(row_wise_results.into_iter())?};- state.out_col = concat(&[&state.out_col, &out_col])?;- state.n_row_result_missing = num_rows - state.last_calculated_index;+ state.update(&out_col, partition_batch_state)?;if self.window_frame.start_bound.is_unbounded() {let mut evaluator_state = evaluator.state()?;if let BuiltinWindowState::NthValue(nth_value_state) =@@ -236,11 +239,9 @@ impl WindowExpr for BuiltInWindowExpr {}fn uses_bounded_memory(&self) -> bool {- // NOTE: Currently, groups queries do not support the bounded memory variant.self.expr.supports_bounded_execution()&& (!self.expr.uses_window_frame()- || !(self.window_frame.end_bound.is_unbounded()- || matches!(self.window_frame.units, WindowFrameUnits::Groups)))+ || !self.window_frame.end_bound.is_unbounded())}}@@ -271,9 +272,7 @@ fn memoize_nth_value(let result = ScalarValue::try_from_array(out, size - 1)?;nth_value_state.finalized_result = Some(result);}- if state.window_frame_range.end > 0 {- state.window_frame_range.start = state.window_frame_range.end - 1;- }+ state.window_frame_range.start = state.window_frame_range.end.saturating_sub(1);}Ok(())}diff --git a/datafusion/physical-expr/src/window/lead_lag.rs b/datafusion/physical-expr/src/window/lead_lag.rsindex 794c7bd392..e2dfd52daf 100644--- a/datafusion/physical-expr/src/window/lead_lag.rs+++ b/datafusion/physical-expr/src/window/lead_lag.rs@@ -189,33 +189,25 @@ impl PartitionEvaluator for WindowShiftEvaluator {fn update_state(&mut self,- state: &WindowAggState,+ _state: &WindowAggState,+ idx: usize,_range_columns: &[ArrayRef],_sort_partition_points: &[Range<usize>],) -> Result<()> {- self.state.idx = state.last_calculated_index;+ self.state.idx = idx;Ok(())}- fn get_range(&self, state: &WindowAggState, n_rows: usize) -> Result<Range<usize>> {+ fn get_range(&self, idx: usize, n_rows: usize) -> Result<Range<usize>> {if self.shift_offset > 0 {let offset = self.shift_offset as usize;- let start = if state.last_calculated_index > offset {- state.last_calculated_index - offset- } else {- 0- };- Ok(Range {- start,- end: state.last_calculated_index + 1,- })+ let start = idx.saturating_sub(offset);+ let end = idx + 1;+ Ok(Range { start, end })} else {let offset = (-self.shift_offset) as usize;- let end = min(state.last_calculated_index + offset, n_rows);- Ok(Range {- start: state.last_calculated_index,- end,- })+ let end = min(idx + offset, n_rows);+ Ok(Range { start: idx, end })}}diff --git a/datafusion/physical-expr/src/window/nth_value.rs b/datafusion/physical-expr/src/window/nth_value.rsindex ef6e3c6d01..4da91e75ef 100644--- a/datafusion/physical-expr/src/window/nth_value.rs+++ b/datafusion/physical-expr/src/window/nth_value.rs@@ -160,6 +160,7 @@ impl PartitionEvaluator for NthValueEvaluator {fn update_state(&mut self,state: &WindowAggState,+ _idx: usize,_range_columns: &[ArrayRef],_sort_partition_points: &[Range<usize>],) -> Result<()> {diff --git a/datafusion/physical-expr/src/window/partition_evaluator.rs b/datafusion/physical-expr/src/window/partition_evaluator.rsindex 7887d1412b..758f7c3b1b 100644--- a/datafusion/physical-expr/src/window/partition_evaluator.rs+++ b/datafusion/physical-expr/src/window/partition_evaluator.rs@@ -38,9 +38,15 @@ pub trait PartitionEvaluator: Debug + Send {Ok(BuiltinWindowState::Default)}+ /// Updates the internal state for Built-in window function+ // state is useful to update internal state for Built-in window function.+ // idx is the index of last row for which result is calculated.+ // range_columns is the result of order by column values. It is used to calculate rank boundaries+ // sort_partition_points is the boundaries of each rank in the range_column. It is used to update rank.fn update_state(&mut self,_state: &WindowAggState,+ _idx: usize,_range_columns: &[ArrayRef],_sort_partition_points: &[Range<usize>],) -> Result<()> {@@ -54,20 +60,23 @@ pub trait PartitionEvaluator: Debug + Send {))}- fn get_range(&self, _state: &WindowAggState, _n_rows: usize) -> Result<Range<usize>> {+ /// Gets the range where Built-in window function result is calculated.+ // idx is the index of last row for which result is calculated.+ // n_rows is the number of rows of the input record batch (Used during bound check)+ fn get_range(&self, _idx: usize, _n_rows: usize) -> Result<Range<usize>> {Err(DataFusionError::NotImplemented("get_range is not implemented for this window function".to_string(),))}- /// evaluate the partition evaluator against the partition+ /// Evaluate the partition evaluator against the partitionfn evaluate(&self, _values: &[ArrayRef], _num_rows: usize) -> Result<ArrayRef> {Err(DataFusionError::NotImplemented("evaluate is not implemented by default".into(),))}- /// evaluate window function result inside given range+ /// Evaluate window function result inside given rangefn evaluate_stateful(&mut self, _values: &[ArrayRef]) -> Result<ScalarValue> {Err(DataFusionError::NotImplemented("evaluate_stateful is not implemented by default".into(),diff --git a/datafusion/physical-expr/src/window/rank.rs b/datafusion/physical-expr/src/window/rank.rsindex ead9d44535..5f016739cf 100644--- a/datafusion/physical-expr/src/window/rank.rs+++ b/datafusion/physical-expr/src/window/rank.rs@@ -25,6 +25,7 @@ use crate::PhysicalExpr;use arrow::array::ArrayRef;use arrow::array::{Float64Array, UInt64Array};use arrow::datatypes::{DataType, Field};+use datafusion_common::utils::get_row_at_idx;use datafusion_common::{DataFusionError, Result, ScalarValue};use std::any::Any;use std::iter;@@ -118,11 +119,10 @@ pub(crate) struct RankEvaluator {}impl PartitionEvaluator for RankEvaluator {- fn get_range(&self, state: &WindowAggState, _n_rows: usize) -> Result<Range<usize>> {- Ok(Range {- start: state.last_calculated_index,- end: state.last_calculated_index + 1,- })+ fn get_range(&self, idx: usize, _n_rows: usize) -> Result<Range<usize>> {+ let start = idx;+ let end = idx + 1;+ Ok(Range { start, end })}fn state(&self) -> Result<BuiltinWindowState> {@@ -132,22 +132,21 @@ impl PartitionEvaluator for RankEvaluator {fn update_state(&mut self,state: &WindowAggState,+ idx: usize,range_columns: &[ArrayRef],sort_partition_points: &[Range<usize>],) -> Result<()> {- // find range inside `sort_partition_points` containing `state.last_calculated_index`+ // find range inside `sort_partition_points` containing `idx`let chunk_idx = sort_partition_points.iter()- .position(|elem| {- elem.start <= state.last_calculated_index- && state.last_calculated_index < elem.end- })- .ok_or_else(|| DataFusionError::Execution("Expects sort_partition_points to contain state.last_calculated_index".to_string()))?;+ .position(|elem| elem.start <= idx && idx < elem.end)+ .ok_or_else(|| {+ DataFusionError::Execution(+ "Expects sort_partition_points to contain idx".to_string(),+ )+ })?;let chunk = &sort_partition_points[chunk_idx];- let last_rank_data = range_columns- .iter()- .map(|c| ScalarValue::try_from_array(c, chunk.end - 1))- .collect::<Result<Vec<_>>>()?;+ let last_rank_data = get_row_at_idx(range_columns, chunk.end - 1)?;let empty = self.state.last_rank_data.is_empty();if empty || self.state.last_rank_data != last_rank_data {self.state.last_rank_data = last_rank_data;diff --git a/datafusion/physical-expr/src/window/row_number.rs b/datafusion/physical-expr/src/window/row_number.rsindex c858a5724a..8961b277e7 100644--- a/datafusion/physical-expr/src/window/row_number.rs+++ b/datafusion/physical-expr/src/window/row_number.rs@@ -19,7 +19,7 @@use crate::window::partition_evaluator::PartitionEvaluator;use crate::window::window_expr::{BuiltinWindowState, NumRowsState};-use crate::window::{BuiltInWindowFunctionExpr, WindowAggState};+use crate::window::BuiltInWindowFunctionExpr;use crate::PhysicalExpr;use arrow::array::{ArrayRef, UInt64Array};use arrow::datatypes::{DataType, Field};@@ -81,11 +81,10 @@ impl PartitionEvaluator for NumRowsEvaluator {Ok(BuiltinWindowState::NumRows(self.state.clone()))}- fn get_range(&self, state: &WindowAggState, _n_rows: usize) -> Result<Range<usize>> {- Ok(Range {- start: state.last_calculated_index,- end: state.last_calculated_index + 1,- })+ fn get_range(&self, idx: usize, _n_rows: usize) -> Result<Range<usize>> {+ let start = idx;+ let end = idx + 1;+ Ok(Range { start, end })}/// evaluate window function result inside given rangediff --git a/datafusion/physical-expr/src/window/sliding_aggregate.rs b/datafusion/physical-expr/src/window/sliding_aggregate.rsindex 0723f05c59..7fa33d71ca 100644--- a/datafusion/physical-expr/src/window/sliding_aggregate.rs+++ b/datafusion/physical-expr/src/window/sliding_aggregate.rs@@ -26,7 +26,7 @@ use arrow::datatypes::Field;use arrow::record_batch::RecordBatch;use datafusion_common::{Result, ScalarValue};-use datafusion_expr::{Accumulator, WindowFrame, WindowFrameUnits};+use datafusion_expr::{Accumulator, WindowFrame};use crate::window::window_expr::{reverse_order_bys, AggregateWindowExpr};use crate::window::{@@ -138,10 +138,8 @@ impl WindowExpr for SlidingAggregateWindowExpr {}fn uses_bounded_memory(&self) -> bool {- // NOTE: Currently, groups queries do not support the bounded memory variant.self.aggregate.supports_bounded_execution()&& !self.window_frame.end_bound.is_unbounded()- && !matches!(self.window_frame.units, WindowFrameUnits::Groups)}}diff --git a/datafusion/physical-expr/src/window/window_expr.rs b/datafusion/physical-expr/src/window/window_expr.rsindex 96e22976b3..7568fa3b2b 100644--- a/datafusion/physical-expr/src/window/window_expr.rs+++ b/datafusion/physical-expr/src/window/window_expr.rs@@ -18,7 +18,7 @@use crate::window::partition_evaluator::PartitionEvaluator;use crate::window::window_frame_state::WindowFrameContext;use crate::{PhysicalExpr, PhysicalSortExpr};-use arrow::array::{new_empty_array, ArrayRef};+use arrow::array::{new_empty_array, Array, ArrayRef};use arrow::compute::kernels::partition::lexicographical_partition_ranges;use arrow::compute::kernels::sort::SortColumn;use arrow::compute::{concat, SortOptions};@@ -164,8 +164,18 @@ pub trait AggregateWindowExpr: WindowExpr {fn aggregate_evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {let mut accumulator = self.get_accumulator()?;let mut last_range = Range { start: 0, end: 0 };- let mut idx = 0;- self.get_result_column(&mut accumulator, batch, &mut last_range, &mut idx, false)+ let sort_options: Vec<SortOptions> =+ self.order_by().iter().map(|o| o.options).collect();+ let mut window_frame_ctx =+ WindowFrameContext::new(self.get_window_frame().clone(), sort_options);+ self.get_result_column(+ &mut accumulator,+ batch,+ &mut last_range,+ &mut window_frame_ctx,+ 0,+ false,+ )}/// Statefully evaluates the window function against the batch. Maintains@@ -196,20 +206,25 @@ pub trait AggregateWindowExpr: WindowExpr {WindowFn::Aggregate(accumulator) => accumulator,_ => unreachable!(),};- let mut state = &mut window_state.state;-+ let state = &mut window_state.state;let record_batch = &partition_batch_state.record_batch;++ // If there is no window state context, initialize it.+ let window_frame_ctx = state.window_frame_ctx.get_or_insert_with(|| {+ let sort_options: Vec<SortOptions> =+ self.order_by().iter().map(|o| o.options).collect();+ WindowFrameContext::new(self.get_window_frame().clone(), sort_options)+ });let out_col = self.get_result_column(accumulator,record_batch,+ // Start search from the last range&mut state.window_frame_range,- &mut state.last_calculated_index,+ window_frame_ctx,+ state.last_calculated_index,!partition_batch_state.is_end,)?;- state.is_end = partition_batch_state.is_end;- state.out_col = concat(&[&state.out_col, &out_col])?;- state.n_row_result_missing =- record_batch.num_rows() - state.last_calculated_index;+ state.update(&out_col, partition_batch_state)?;}Ok(())}@@ -221,23 +236,18 @@ pub trait AggregateWindowExpr: WindowExpr {accumulator: &mut Box<dyn Accumulator>,record_batch: &RecordBatch,last_range: &mut Range<usize>,- idx: &mut usize,+ window_frame_ctx: &mut WindowFrameContext,+ mut idx: usize,not_end: bool,) -> Result<ArrayRef> {let (values, order_bys) = self.get_values_orderbys(record_batch)?;// We iterate on each row to perform a running calculation.let length = values[0].len();- let sort_options: Vec<SortOptions> =- self.order_by().iter().map(|o| o.options).collect();- let mut window_frame_ctx = WindowFrameContext::new(- self.get_window_frame(),- sort_options,- // Start search from the last range- last_range.clone(),- );let mut row_wise_results: Vec<ScalarValue> = vec![];- while *idx < length {- let cur_range = window_frame_ctx.calculate_range(&order_bys, length, *idx)?;+ while idx < length {+ // Start search from the last_range. This squeezes searched range.+ let cur_range =+ window_frame_ctx.calculate_range(&order_bys, last_range, length, idx)?;// Exit if the range extends all the way:if cur_range.end == length && not_end {break;@@ -248,9 +258,10 @@ pub trait AggregateWindowExpr: WindowExpr {&values,accumulator,)?;- last_range.clone_from(&cur_range);+ // Update last range+ *last_range = cur_range;row_wise_results.push(value);- *idx += 1;+ idx += 1;}if row_wise_results.is_empty() {let field = self.field()?;@@ -340,6 +351,7 @@ pub enum BuiltinWindowState {pub struct WindowAggState {/// The range that we calculate the window functionpub window_frame_range: Range<usize>,+ pub window_frame_ctx: Option<WindowFrameContext>,/// The index of the last row that its result is calculated inside the partition record batch buffer.pub last_calculated_index: usize,/// The offset of the deleted row number@@ -353,6 +365,54 @@ pub struct WindowAggState {pub is_end: bool,}+impl WindowAggState {+ pub fn prune_state(&mut self, n_prune: usize) {+ self.window_frame_range = Range {+ start: self.window_frame_range.start - n_prune,+ end: self.window_frame_range.end - n_prune,+ };+ self.last_calculated_index -= n_prune;+ self.offset_pruned_rows += n_prune;++ match self.window_frame_ctx.as_mut() {+ // Rows have no state do nothing+ Some(WindowFrameContext::Rows(_)) => {}+ Some(WindowFrameContext::Range { .. }) => {}+ Some(WindowFrameContext::Groups { state, .. }) => {+ let mut n_group_to_del = 0;+ for (_, end_idx) in &state.group_end_indices {+ if n_prune < *end_idx {+ break;+ }+ n_group_to_del += 1;+ }+ state.group_end_indices.drain(0..n_group_to_del);+ state+ .group_end_indices+ .iter_mut()+ .for_each(|(_, start_idx)| *start_idx -= n_prune);+ state.current_group_idx -= n_group_to_del;+ }+ None => {}+ };+ }+}++impl WindowAggState {+ pub fn update(+ &mut self,+ out_col: &ArrayRef,+ partition_batch_state: &PartitionBatchState,+ ) -> Result<()> {+ self.last_calculated_index += out_col.len();+ self.out_col = concat(&[&self.out_col, &out_col])?;+ self.n_row_result_missing =+ partition_batch_state.record_batch.num_rows() - self.last_calculated_index;+ self.is_end = partition_batch_state.is_end;+ Ok(())+ }+}+/// State for each unique partition determined according to PARTITION BY column(s)#[derive(Debug)]pub struct PartitionBatchState {@@ -383,6 +443,7 @@ impl WindowAggState {let empty_out_col = ScalarValue::try_from(out_type)?.to_array_of_size(0);Ok(Self {window_frame_range: Range { start: 0, end: 0 },+ window_frame_ctx: None,last_calculated_index: 0,offset_pruned_rows: 0,out_col: empty_out_col,diff --git a/datafusion/physical-expr/src/window/window_frame_state.rs b/datafusion/physical-expr/src/window/window_frame_state.rsindex 64abacde49..01a4f9ad71 100644--- a/datafusion/physical-expr/src/window/window_frame_state.rs+++ b/datafusion/physical-expr/src/window/window_frame_state.rs@@ -31,37 +31,33 @@ use std::sync::Arc;/// This object stores the window frame state for use in incremental calculations.#[derive(Debug)]-pub enum WindowFrameContext<'a> {+pub enum WindowFrameContext {/// ROWS frames are inherently stateless.- Rows(&'a Arc<WindowFrame>),+ Rows(Arc<WindowFrame>),/// RANGE frames are stateful, they store indices specifying where the/// previous search left off. This amortizes the overall cost to O(n)/// where n denotes the row count.Range {- window_frame: &'a Arc<WindowFrame>,+ window_frame: Arc<WindowFrame>,state: WindowFrameStateRange,},/// GROUPS frames are stateful, they store group boundaries and indices/// specifying where the previous search left off. This amortizes the/// overall cost to O(n) where n denotes the row count.Groups {- window_frame: &'a Arc<WindowFrame>,+ window_frame: Arc<WindowFrame>,state: WindowFrameStateGroups,},}-impl<'a> WindowFrameContext<'a> {+impl WindowFrameContext {/// Create a new state object for the given window frame.- pub fn new(- window_frame: &'a Arc<WindowFrame>,- sort_options: Vec<SortOptions>,- last_range: Range<usize>,- ) -> Self {+ pub fn new(window_frame: Arc<WindowFrame>, sort_options: Vec<SortOptions>) -> Self {match window_frame.units {WindowFrameUnits::Rows => WindowFrameContext::Rows(window_frame),WindowFrameUnits::Range => WindowFrameContext::Range {window_frame,- state: WindowFrameStateRange::new(sort_options, last_range),+ state: WindowFrameStateRange::new(sort_options),},WindowFrameUnits::Groups => WindowFrameContext::Groups {window_frame,@@ -74,10 +70,11 @@ impl<'a> WindowFrameContext<'a> {pub fn calculate_range(&mut self,range_columns: &[ArrayRef],+ last_range: &Range<usize>,length: usize,idx: usize,) -> Result<Range<usize>> {- match *self {+ match self {WindowFrameContext::Rows(window_frame) => {Self::calculate_range_rows(window_frame, length, idx)}@@ -87,7 +84,13 @@ impl<'a> WindowFrameContext<'a> {WindowFrameContext::Range {window_frame,ref mut state,- } => state.calculate_range(window_frame, range_columns, length, idx),+ } => state.calculate_range(+ window_frame,+ last_range,+ range_columns,+ length,+ idx,+ ),// Sort options is not used in GROUPS mode calculations as the// inequality of two rows indicates a group change, and ordering// or position of NULLs do not impact inequality.@@ -159,33 +162,29 @@ impl<'a> WindowFrameContext<'a> {}/// This structure encapsulates all the state information we require as we scan-/// ranges of data while processing RANGE frames. Attribute `last_range` stores-/// the resulting indices from the previous search. Since the indices only-/// advance forward, we start from `last_range` subsequently. Thus, the overall-/// time complexity of linear search amortizes to O(n) where n denotes the total-/// row count.+/// ranges of data while processing RANGE frames./// Attribute `sort_options` stores the column ordering specified by the ORDER/// BY clause. This information is used to calculate the range.#[derive(Debug, Default)]pub struct WindowFrameStateRange {- last_range: Range<usize>,sort_options: Vec<SortOptions>,}impl WindowFrameStateRange {/// Create a new object to store the search state.- fn new(sort_options: Vec<SortOptions>, last_range: Range<usize>) -> Self {- Self {- // Stores the search range we calculate for future use.- last_range,- sort_options,- }+ fn new(sort_options: Vec<SortOptions>) -> Self {+ Self { sort_options }}/// This function calculates beginning/ending indices for the frame of the current row.+ // Argument `last_range` stores the resulting indices from the previous search. Since the indices only+ // advance forward, we start from `last_range` subsequently. Thus, the overall+ // time complexity of linear search amortizes to O(n) where n denotes the total+ // row count.fn calculate_range(&mut self,window_frame: &Arc<WindowFrame>,+ last_range: &Range<usize>,range_columns: &[ArrayRef],length: usize,idx: usize,@@ -198,6 +197,7 @@ impl WindowFrameStateRange {} else {self.calculate_index_of_row::<true, true>(range_columns,+ last_range,idx,Some(n),length,@@ -206,6 +206,7 @@ impl WindowFrameStateRange {}WindowFrameBound::CurrentRow => self.calculate_index_of_row::<true, true>(range_columns,+ last_range,idx,None,length,@@ -213,6 +214,7 @@ impl WindowFrameStateRange {WindowFrameBound::Following(ref n) => self.calculate_index_of_row::<true, false>(range_columns,+ last_range,idx,Some(n),length,@@ -222,12 +224,14 @@ impl WindowFrameStateRange {WindowFrameBound::Preceding(ref n) => self.calculate_index_of_row::<false, true>(range_columns,+ last_range,idx,Some(n),length,)?,WindowFrameBound::CurrentRow => self.calculate_index_of_row::<false, false>(range_columns,+ last_range,idx,None,length,@@ -239,6 +243,7 @@ impl WindowFrameStateRange {} else {self.calculate_index_of_row::<false, false>(range_columns,+ last_range,idx,Some(n),length,@@ -246,9 +251,6 @@ impl WindowFrameStateRange {}}};- // Store the resulting range so we can start from here subsequently:- self.last_range.start = start;- self.last_range.end = end;Ok(Range { start, end })}@@ -258,6 +260,7 @@ impl WindowFrameStateRange {fn calculate_index_of_row<const SIDE: bool, const SEARCH_SIDE: bool>(&mut self,range_columns: &[ArrayRef],+ last_range: &Range<usize>,idx: usize,delta: Option<&ScalarValue>,length: usize,@@ -298,9 +301,9 @@ impl WindowFrameStateRange {current_row_values};let search_start = if SIDE {- self.last_range.start+ last_range.start} else {- self.last_range.end+ last_range.end};let compare_fn = |current: &[ScalarValue], target: &[ScalarValue]| {let cmp = compare_rows(current, target, &self.sort_options)?;@@ -332,16 +335,16 @@ impl WindowFrameStateRange {// last row of the group that comes "offset" groups after the current group.// - UNBOUNDED FOLLOWING: End with the last row of the partition. Possible only in frame_end.-// This structure encapsulates all the state information we require as we-// scan groups of data while processing window frames.+/// This structure encapsulates all the state information we require as we+/// scan groups of data while processing window frames.#[derive(Debug, Default)]pub struct WindowFrameStateGroups {/// A tuple containing group values and the row index where the group ends./// Example: [[1, 1], [1, 1], [2, 1], [2, 1], ...] would correspond to/// [([1, 1], 2), ([2, 1], 4), ...].- group_start_indices: VecDeque<(Vec<ScalarValue>, usize)>,+ pub group_end_indices: VecDeque<(Vec<ScalarValue>, usize)>,/// The group index to which the row index belongs.- current_group_idx: usize,+ pub current_group_idx: usize,}impl WindowFrameStateGroups {@@ -435,14 +438,28 @@ impl WindowFrameStateGroups {0};let mut group_start = 0;- let last_group = self.group_start_indices.back();- if let Some((_, group_end)) = last_group {+ let last_group = self.group_end_indices.back_mut();+ if let Some((group_row, group_end)) = last_group {+ if *group_end < length {+ let new_group_row = get_row_at_idx(range_columns, *group_end)?;+ // If last/current group keys are the same, we extend the last group:+ if new_group_row.eq(group_row) {+ // Update the end boundary of the group (search right boundary):+ *group_end = search_in_slice(+ range_columns,+ group_row,+ check_equality,+ *group_end,+ length,+ )?;+ }+ }// Start searching from the last group boundary:group_start = *group_end;}// Advance groups until `idx` is inside a group:- while idx > group_start {+ while idx >= group_start {let group_row = get_row_at_idx(range_columns, group_start)?;// Find end boundary of the group (search right boundary):let group_end = search_in_slice(@@ -452,13 +469,13 @@ impl WindowFrameStateGroups {group_start,length,)?;- self.group_start_indices.push_back((group_row, group_end));+ self.group_end_indices.push_back((group_row, group_end));group_start = group_end;}// Update the group index `idx` belongs to:- while self.current_group_idx < self.group_start_indices.len()- && idx >= self.group_start_indices[self.current_group_idx].1+ while self.current_group_idx < self.group_end_indices.len()+ && idx >= self.group_end_indices[self.current_group_idx].1{self.current_group_idx += 1;}@@ -475,7 +492,7 @@ impl WindowFrameStateGroups {};// Extend `group_start_indices` until it includes at least `group_idx`:- while self.group_start_indices.len() <= group_idx && group_start < length {+ while self.group_end_indices.len() <= group_idx && group_start < length {let group_row = get_row_at_idx(range_columns, group_start)?;// Find end boundary of the group (search right boundary):let group_end = search_in_slice(@@ -485,7 +502,7 @@ impl WindowFrameStateGroups {group_start,length,)?;- self.group_start_indices.push_back((group_row, group_end));+ self.group_end_indices.push_back((group_row, group_end));group_start = group_end;}@@ -493,10 +510,10 @@ impl WindowFrameStateGroups {Ok(match (SIDE, SEARCH_SIDE) {// Window frame start:(true, _) => {- let group_idx = min(group_idx, self.group_start_indices.len());+ let group_idx = min(group_idx, self.group_end_indices.len());if group_idx > 0 {// Normally, start at the boundary of the previous group.- self.group_start_indices[group_idx - 1].1+ self.group_end_indices[group_idx - 1].1} else {// If previous group is out of the table, start at zero.0@@ -506,7 +523,7 @@ impl WindowFrameStateGroups {(false, true) => {if self.current_group_idx >= delta {let group_idx = self.current_group_idx - delta;- self.group_start_indices[group_idx].1+ self.group_end_indices[group_idx].1} else {// Group is out of the table, therefore end at zero.0@@ -516,9 +533,9 @@ impl WindowFrameStateGroups {(false, false) => {let group_idx = min(self.current_group_idx + delta,- self.group_start_indices.len() - 1,+ self.group_end_indices.len() - 1,);- self.group_start_indices[group_idx].1+ self.group_end_indices[group_idx].1}})}