You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "nuno-faria (via GitHub)" <gi...@apache.org> on 2025/09/11 17:36:14 UTC

[PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

nuno-faria opened a new pull request, #17528:
URL: https://github.com/apache/datafusion/pull/17528

   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   - N/A.
   
   ## Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   Improves the performance of window functions in more than 3x when there are a large number of distinct partition keys. The performance with few groups remains the same.
   
   I believe the performance could be further improved, but it might require deeper changes.
   
   Here is a small benchmark:
   ```rust
   use datafusion::error::Result;
   use datafusion::prelude::SessionContext;
   use tokio::time::Instant;
   
   #[tokio::main]
   async fn main() -> Result<()> {
       let ctx = SessionContext::new();
   
       ctx.sql("SET datafusion.execution.target_partitions = '1';")
           .await?
           .collect()
           .await?;
   
       ctx.sql("create table t (k1 int, k2 int, v int);")
           .await?
           .collect()
           .await?;
   
       ctx.sql("insert into t select i as k1, 1 as k2, i as v from generate_series(1, 10000000) t(i);")
           .await?
           .collect()
           .await?;
   
       // partition by k1: each key is unique
       let t = Instant::now();
       ctx.sql("
           explain analyze
           select *, rank() over(partition by k1 order by v) as rank
           from t
           "
       )
           .await?
           .collect()
           .await?;
       println!("partition by k1: {}s", t.elapsed().as_secs_f64());
   
       // partition by k2: each key is the same
       let t = Instant::now();
       ctx.sql("
           explain analyze
           select *, rank() over(partition by k2 order by v) as rank
           from t
           "
       )
           .await?
           .collect()
           .await?;
       println!("partition by k2: {}s", t.elapsed().as_secs_f64());
   
       Ok(())
   }
   ```
   
   ```
   # before
   partition by k1: 62.201990669s
   partition by k2: 1.89616558s
   
   # after
   partition by k1: 18.177335377s
   partition by k2: 1.870575527s
   ```
   
   ## What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   - Reuse `WindowAggState` to avoid potentially having to create many in `StandardWindowExpr::evaluate_stateful` (`standard.rs`).
   - Avoid `concat` in `WindowAggState::update` when the existing result in empty (`window_state.rs`).
   - Use `to_array` instead of `iter_to_array` when an `ArrayRef` only has a single row, in `StandardWindowExpr::evaluate_stateful` (`standard.rs`).
   - Concat all batches once instead of one at a time, in `get_aggregate_result_out_column` (`bounded_window_agg_exec.rs`).
   - Use `clone` instead of `slice` when the entire column is used, in `get_aggregate_result_out_column` (`bounded_window_agg_exec.rs`).
   - Avoid concatenating batches unnecessarily in `PartitionSearcher::update_partition_batch` (`bounded_window_agg_exec.rs`).
   - Iterate over `IndexMap` and probe `HashMap` instead of the other way around, in `SortedSearch::calculate_n_out_row` (`bounded_window_agg_exec.rs`).
   
   ## Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   Yes.
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   
   No.


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#issuecomment-3289375101

   No regression on window integration benchmark (`./bench.sh run h2o_small_window`) ๐Ÿš€ 
   
   ```sh
   โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“
   โ”ƒ Query        โ”ƒ       main โ”ƒ   pr-17528 โ”ƒ        Change โ”ƒ
   โ”กโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ฉ
   โ”‚ QQuery 1     โ”‚  124.36 ms โ”‚  125.83 ms โ”‚     no change โ”‚
   โ”‚ QQuery 2     โ”‚ 1541.36 ms โ”‚ 1528.17 ms โ”‚     no change โ”‚
   โ”‚ QQuery 3     โ”‚ 3226.98 ms โ”‚ 3276.38 ms โ”‚     no change โ”‚
   โ”‚ QQuery 4     โ”‚  393.17 ms โ”‚  391.10 ms โ”‚     no change โ”‚
   โ”‚ QQuery 5     โ”‚  916.36 ms โ”‚  926.75 ms โ”‚     no change โ”‚
   โ”‚ QQuery 6     โ”‚ 1294.89 ms โ”‚ 1286.95 ms โ”‚     no change โ”‚
   โ”‚ QQuery 7     โ”‚ 1165.18 ms โ”‚ 1163.57 ms โ”‚     no change โ”‚
   โ”‚ QQuery 8     โ”‚ 4794.23 ms โ”‚ 4757.72 ms โ”‚     no change โ”‚
   โ”‚ QQuery 9     โ”‚  326.90 ms โ”‚  307.08 ms โ”‚ +1.06x faster โ”‚
   โ”‚ QQuery 10    โ”‚  370.69 ms โ”‚  355.40 ms โ”‚     no change โ”‚
   โ”‚ QQuery 11    โ”‚  357.53 ms โ”‚  338.48 ms โ”‚ +1.06x faster โ”‚
   โ”‚ QQuery 12    โ”‚  680.16 ms โ”‚  685.44 ms โ”‚     no change โ”‚
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   ```


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#discussion_r2346847161


##########
datafusion/expr/src/window_state.rs:
##########
@@ -90,7 +90,12 @@ impl WindowAggState {
         partition_batch_state: &PartitionBatchState,
     ) -> Result<()> {
         self.last_calculated_index += out_col.len();
-        self.out_col = concat(&[&self.out_col, &out_col])?;
+        // no need to use concat if the current `out_col` is empty

Review Comment:
   Is this not something already done in `concat`? (At least it would make sense to have this optimization there if not already).



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#discussion_r2346850435


##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -870,9 +879,11 @@ impl SortedSearch {
             cur_window_expr_out_result_len
         });
         argmin(out_col_counts).map_or(0, |(min_idx, minima)| {
-            for (row, count) in counts.swap_remove(min_idx).into_iter() {
-                let partition_batch = &mut partition_buffers[row];
-                partition_batch.n_out_row = count;
+            let mut counts = counts.swap_remove(min_idx);
+            for (partition_key, partition_batch) in partition_buffers.iter_mut() {
+                if let Some(count) = counts.remove(partition_key) {

Review Comment:
   Isn't this `O(n^2)`



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -870,9 +879,11 @@ impl SortedSearch {
             cur_window_expr_out_result_len
         });
         argmin(out_col_counts).map_or(0, |(min_idx, minima)| {
-            for (row, count) in counts.swap_remove(min_idx).into_iter() {
-                let partition_batch = &mut partition_buffers[row];
-                partition_batch.n_out_row = count;
+            let mut counts = counts.swap_remove(min_idx);
+            for (partition_key, partition_batch) in partition_buffers.iter_mut() {
+                if let Some(count) = counts.remove(partition_key) {

Review Comment:
   Isn't this `O(n^2)`?



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan merged PR #17528:
URL: https://github.com/apache/datafusion/pull/17528


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#issuecomment-3318374433

   Thank you @nuno-faria !


-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "nuno-faria (via GitHub)" <gi...@apache.org>.
nuno-faria commented on code in PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#discussion_r2348167812


##########
datafusion/expr/src/window_state.rs:
##########
@@ -90,7 +90,12 @@ impl WindowAggState {
         partition_batch_state: &PartitionBatchState,
     ) -> Result<()> {
         self.last_calculated_index += out_col.len();
-        self.out_col = concat(&[&self.out_col, &out_col])?;
+        // no need to use concat if the current `out_col` is empty

Review Comment:
   I don't think so, there is only an early exit if there is only a single array. I did a quick benchmark and confirmed that is considerably faster to use clone here.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "nuno-faria (via GitHub)" <gi...@apache.org>.
nuno-faria commented on code in PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#discussion_r2348169771


##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -870,9 +879,11 @@ impl SortedSearch {
             cur_window_expr_out_result_len
         });
         argmin(out_col_counts).map_or(0, |(min_idx, minima)| {
-            for (row, count) in counts.swap_remove(min_idx).into_iter() {
-                let partition_batch = &mut partition_buffers[row];
-                partition_batch.n_out_row = count;
+            let mut counts = counts.swap_remove(min_idx);
+            for (partition_key, partition_batch) in partition_buffers.iter_mut() {
+                if let Some(count) = counts.remove(partition_key) {

Review Comment:
   The new `counts` here is an `HashMap`, so its O(N) but the naming is confusing. I've updated the variable.



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve the performance of WINDOW functions with many partitions [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #17528:
URL: https://github.com/apache/datafusion/pull/17528#discussion_r2367768086


##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -870,9 +879,11 @@ impl SortedSearch {
             cur_window_expr_out_result_len
         });
         argmin(out_col_counts).map_or(0, |(min_idx, minima)| {
-            for (row, count) in counts.swap_remove(min_idx).into_iter() {
-                let partition_batch = &mut partition_buffers[row];
-                partition_batch.n_out_row = count;
+            let mut counts = counts.swap_remove(min_idx);
+            for (partition_key, partition_batch) in partition_buffers.iter_mut() {
+                if let Some(count) = counts.remove(partition_key) {

Review Comment:
   ok :) 



-- 
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: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org