You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/08/19 14:57:00 UTC

(datafusion) branch gh-readonly-queue/main/pr-24453-8dc6c291fb4c0b7d95d51de062e344f3f406709a created (now 1a39ae85db)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-24453-8dc6c291fb4c0b7d95d51de062e344f3f406709a
in repository https://gitbox.apache.org/repos/asf/datafusion.git


      at 1a39ae85db perf: avoid processing discarded rows for negative `nth_value` (#24453)

This branch includes the following new commits:

     new 1a39ae85db perf: avoid processing discarded rows for negative `nth_value` (#24453)

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



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


(datafusion) 01/01: perf: avoid processing discarded rows for negative `nth_value` (#24453)

Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-24453-8dc6c291fb4c0b7d95d51de062e344f3f406709a
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit 1a39ae85db50ac1a97f119854704c551bf852269
Author: linfeng <33...@users.noreply.github.com>
AuthorDate: Wed Aug 19 14:56:38 2026 +0000

    perf: avoid processing discarded rows for negative `nth_value` (#24453)
    
    ## 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.
    -->
    
    - Closes #.
    
    ## 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.
    
    Please explain the problem you are trying to solve in terms of the
    user-visible
    behavior, rather than the implementation.
    
    For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of
    the
    implementation. "COUNT(DISTINCT) returns wrong results when the column
    contains
    nulls" is the user-visible problem.
    -->
    
    For negative `n`, `NTH_VALUE` only needs to retain the last n rows.
    However, each update currently converts and appends every row in the
    input batch before discarding rows that cannot affect the result.
    
    This adds unnecessary work for large batches, especially when n is
    small.
    
    ## 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.
    -->
    
    - Retain only the required portion of the existing accumulator state.
    - Append only the trailing input rows that can affect the result.
    - Apply the optimization to both trivial and ordered accumulators.
    - Add benchmark for `nth_value` with positive and negative `n`
    
    ## 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.
    
    ## Benchmark
    ```
    group                       main                                     optimized
    -----                       ----                                     ---------
    nth_value/ordered/n=-1      5154.01     6.4±0.19ms        ? ?/sec    1.00  1233.7±449.90ns        ? ?/sec
    nth_value/ordered/n=-10     819.35     6.5±0.25ms        ? ?/sec     1.00      7.9±0.14µs        ? ?/sec
    nth_value/ordered/n=-100    87.44     6.4±0.18ms        ? ?/sec      1.00     73.7±1.80µs        ? ?/sec
    nth_value/ordered/n=1       1.00   241.0±24.66ns        ? ?/sec      1.04   251.0±22.94ns        ? ?/sec
    nth_value/ordered/n=10      1.13  1375.2±281.33ns        ? ?/sec     1.00  1219.0±51.07ns        ? ?/sec
    nth_value/ordered/n=100     1.03      8.4±0.74µs        ? ?/sec      1.00      8.2±0.18µs        ? ?/sec
    nth_value/trivial/n=-1      6821.05     3.3±0.24ms        ? ?/sec    1.00   485.5±20.29ns        ? ?/sec
    nth_value/trivial/n=-10     822.65     3.4±0.33ms        ? ?/sec     1.00      4.1±0.10µs        ? ?/sec
    nth_value/trivial/n=-100    82.35     3.3±0.26ms        ? ?/sec      1.00     40.2±4.02µs        ? ?/sec
    nth_value/trivial/n=1       1.00     97.0±1.56ns        ? ?/sec      1.03   100.1±10.38ns        ? ?/sec
    nth_value/trivial/n=10      1.01   599.9±38.67ns        ? ?/sec      1.00   591.2±22.46ns        ? ?/sec
    nth_value/trivial/n=100     1.06      4.5±0.50µs        ? ?/sec      1.00      4.3±0.19µs        ? ?/sec
    ```
---
 datafusion/functions-aggregate/Cargo.toml          |   4 +
 .../functions-aggregate/benches/nth_value.rs       | 102 +++++++++++++++++++++
 datafusion/functions-aggregate/src/nth_value.rs    |  47 +++++-----
 datafusion/sqllogictest/test_files/aggregate.slt   |  38 ++++++++
 4 files changed, 165 insertions(+), 26 deletions(-)

diff --git a/datafusion/functions-aggregate/Cargo.toml b/datafusion/functions-aggregate/Cargo.toml
index 5abea16e2c..ae6bf70088 100644
--- a/datafusion/functions-aggregate/Cargo.toml
+++ b/datafusion/functions-aggregate/Cargo.toml
@@ -92,6 +92,10 @@ harness = false
 name = "median"
 harness = false
 
+[[bench]]
+name = "nth_value"
+harness = false
+
 [[bench]]
 name = "percentile_cont"
 harness = false
diff --git a/datafusion/functions-aggregate/benches/nth_value.rs b/datafusion/functions-aggregate/benches/nth_value.rs
new file mode 100644
index 0000000000..a0cff5397b
--- /dev/null
+++ b/datafusion/functions-aggregate/benches/nth_value.rs
@@ -0,0 +1,102 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::hint::black_box;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, Int64Array};
+use arrow::compute::SortOptions;
+use arrow::datatypes::DataType;
+use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main};
+use datafusion_expr::Accumulator;
+use datafusion_functions_aggregate::nth_value::{
+    NthValueAccumulator, TrivialNthValueAccumulator,
+};
+use datafusion_physical_expr::expressions::Column;
+use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};
+
+const N_VALUES: [i64; 6] = [-100, -10, -1, 1, 10, 100];
+const BATCH_LEN: usize = 8192;
+const UPDATES_PER_ITER: usize = 10;
+
+fn int64_array(values: impl IntoIterator<Item = i64>) -> ArrayRef {
+    Arc::new(Int64Array::from_iter_values(values))
+}
+
+fn trivial_accumulator(n: i64) -> TrivialNthValueAccumulator {
+    TrivialNthValueAccumulator::try_new(n, &DataType::Int64).unwrap()
+}
+
+fn ordered_accumulator(n: i64) -> NthValueAccumulator {
+    let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
+        Arc::new(Column::new("ordering", 0)),
+        SortOptions::default(),
+    )])
+    .unwrap();
+    NthValueAccumulator::try_new(n, &DataType::Int64, &[DataType::Int64], ordering)
+        .unwrap()
+}
+
+fn nth_value_benchmark(c: &mut Criterion) {
+    let values = int64_array(0..BATCH_LEN as i64);
+    let mut group = c.benchmark_group("nth_value");
+
+    for n in N_VALUES {
+        let n_values = int64_array(std::iter::repeat_n(n, BATCH_LEN));
+        let trivial_batch = vec![Arc::clone(&values), Arc::clone(&n_values)];
+        group.bench_function(BenchmarkId::new("trivial", format!("n={n}")), |b| {
+            b.iter_batched(
+                || trivial_accumulator(n),
+                |mut accumulator| {
+                    for _ in 0..UPDATES_PER_ITER {
+                        accumulator.update_batch(&trivial_batch).unwrap();
+                    }
+                    black_box(accumulator.evaluate().unwrap());
+                },
+                BatchSize::SmallInput,
+            )
+        });
+
+        let ordered_batches = (0..UPDATES_PER_ITER)
+            .map(|batch_idx| {
+                let start = (batch_idx * BATCH_LEN) as i64;
+                vec![
+                    Arc::clone(&values),
+                    Arc::clone(&n_values),
+                    int64_array(start..start + BATCH_LEN as i64),
+                ]
+            })
+            .collect::<Vec<_>>();
+        group.bench_function(BenchmarkId::new("ordered", format!("n={n}")), |b| {
+            b.iter_batched(
+                || ordered_accumulator(n),
+                |mut accumulator| {
+                    for batch in &ordered_batches {
+                        accumulator.update_batch(batch).unwrap();
+                    }
+                    black_box(accumulator.evaluate().unwrap());
+                },
+                BatchSize::SmallInput,
+            )
+        });
+    }
+
+    group.finish();
+}
+
+criterion_group!(benches, nth_value_benchmark);
+criterion_main!(benches);
diff --git a/datafusion/functions-aggregate/src/nth_value.rs b/datafusion/functions-aggregate/src/nth_value.rs
index bddc46e27e..32d9d3057c 100644
--- a/datafusion/functions-aggregate/src/nth_value.rs
+++ b/datafusion/functions-aggregate/src/nth_value.rs
@@ -20,6 +20,7 @@
 
 use std::collections::VecDeque;
 use std::mem::{size_of, size_of_val};
+use std::ops::Range;
 use std::sync::Arc;
 
 use arrow::array::{ArrayRef, AsArray, StructArray, new_empty_array};
@@ -214,20 +215,13 @@ impl TrivialNthValueAccumulator {
         })
     }
 
-    /// Updates state, with the `values`. Fetch contains missing number of entries for state to be complete
-    /// None represents all of the new `values` need to be added to the state.
+    /// Updates state with rows in `range` from `values`.
     fn append_new_data(
         &mut self,
         values: &[ArrayRef],
-        fetch: Option<usize>,
+        range: Range<usize>,
     ) -> Result<()> {
-        let n_row = values[0].len();
-        let n_to_add = if let Some(fetch) = fetch {
-            std::cmp::min(fetch, n_row)
-        } else {
-            n_row
-        };
-        for index in 0..n_to_add {
+        for index in range {
             let mut row = get_row_at_idx(values, index)?;
             self.values.push_back(row.swap_remove(0));
             // At index 1, we have n index argument, which is constant.
@@ -246,14 +240,18 @@ impl Accumulator for TrivialNthValueAccumulator {
             if from_start {
                 // direction is from start
                 let n_remaining = n_required.saturating_sub(self.values.len());
-                self.append_new_data(values, Some(n_remaining))?;
+                let batch_len = values[0].len();
+                self.append_new_data(values, 0..n_remaining.min(batch_len))?;
             } else {
                 // direction is from end
-                self.append_new_data(values, None)?;
-                let start_offset = self.values.len().saturating_sub(n_required);
+                let batch_len = values[0].len();
+                let new_count = n_required.min(batch_len);
+                let retain_count = n_required - new_count;
+                let start_offset = self.values.len().saturating_sub(retain_count);
                 if start_offset > 0 {
                     self.values.drain(0..start_offset);
                 }
+                self.append_new_data(values, batch_len - new_count..batch_len)?;
             }
         }
         Ok(())
@@ -387,20 +385,13 @@ impl NthValueAccumulator {
         ))
     }
 
-    /// Updates state, with the `values`. Fetch contains missing number of entries for state to be complete
-    /// None represents all of the new `values` need to be added to the state.
+    /// Updates state with rows in `range` from `values`.
     fn append_new_data(
         &mut self,
         values: &[ArrayRef],
-        fetch: Option<usize>,
+        range: Range<usize>,
     ) -> Result<()> {
-        let n_row = values[0].len();
-        let n_to_add = if let Some(fetch) = fetch {
-            std::cmp::min(fetch, n_row)
-        } else {
-            n_row
-        };
-        for index in 0..n_to_add {
+        for index in range {
             let row = get_row_at_idx(values, index)?;
             self.values.push_back(row[0].clone());
             // At index 1, we have n index argument.
@@ -424,15 +415,19 @@ impl Accumulator for NthValueAccumulator {
         if from_start {
             // direction is from start
             let n_remaining = n_required.saturating_sub(self.values.len());
-            self.append_new_data(values, Some(n_remaining))?;
+            let batch_len = values[0].len();
+            self.append_new_data(values, 0..n_remaining.min(batch_len))?;
         } else {
             // direction is from end
-            self.append_new_data(values, None)?;
-            let start_offset = self.values.len().saturating_sub(n_required);
+            let batch_len = values[0].len();
+            let new_count = n_required.min(batch_len);
+            let retain_count = n_required - new_count;
+            let start_offset = self.values.len().saturating_sub(retain_count);
             if start_offset > 0 {
                 self.values.drain(0..start_offset);
                 self.ordering_values.drain(0..start_offset);
             }
+            self.append_new_data(values, batch_len - new_count..batch_len)?;
         }
 
         Ok(())
diff --git a/datafusion/sqllogictest/test_files/aggregate.slt b/datafusion/sqllogictest/test_files/aggregate.slt
index 460d4cd2ff..70f080aed5 100644
--- a/datafusion/sqllogictest/test_files/aggregate.slt
+++ b/datafusion/sqllogictest/test_files/aggregate.slt
@@ -7237,6 +7237,44 @@ from aggregate_test_100;
 statement ok
 set datafusion.execution.batch_size = 8192;
 
+# Test negative nth_value update_batch() with batches smaller than, equal to,
+# and larger than N for both order-insensitive and order-sensitive accumulators.
+statement ok
+set datafusion.execution.target_partitions = 1;
+
+statement ok
+set datafusion.execution.batch_size = 1;
+
+query II
+select nth_value(i, -3), nth_value(i, -3 order by i)
+from generate_series(1, 4) t(i);
+----
+2 2
+
+statement ok
+set datafusion.execution.batch_size = 3;
+
+query II
+select nth_value(i, -3), nth_value(i, -3 order by i)
+from generate_series(1, 6) t(i);
+----
+4 4
+
+statement ok
+set datafusion.execution.batch_size = 4;
+
+query II
+select nth_value(i, -3), nth_value(i, -3 order by i)
+from generate_series(1, 8) t(i);
+----
+6 6
+
+statement ok
+set datafusion.execution.batch_size = 8192;
+
+statement ok
+set datafusion.execution.target_partitions = 4;
+
 
 # regr_*() testing retract_batch() from RegrAccumulator's internal implementation
 query RRIRRRRRR


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