neilconway commented on code in PR #23827:
URL: https://github.com/apache/datafusion/pull/23827#discussion_r3645964553


##########
datafusion/functions-aggregate/src/min_max.rs:
##########
@@ -751,28 +745,29 @@ impl Accumulator for SlidingMinAccumulator {
 /// moving_min.push(3);
 ///
 /// assert_eq!(moving_min.min(), Some(&1));
-/// assert_eq!(moving_min.pop(), Some(2));
+/// moving_min.pop();
 ///
 /// assert_eq!(moving_min.min(), Some(&1));
-/// assert_eq!(moving_min.pop(), Some(1));
+/// moving_min.pop();
 ///
 /// assert_eq!(moving_min.min(), Some(&3));
-/// assert_eq!(moving_min.pop(), Some(3));
+/// moving_min.pop();
 ///
 /// assert_eq!(moving_min.min(), None);
-/// assert_eq!(moving_min.pop(), None);
 /// ```
 #[derive(Debug)]
 pub struct MovingMin<T> {
-    push_stack: Vec<(T, T)>,
-    pop_stack: Vec<(T, T)>,
+    deque: VecDeque<(u64, T)>,
+    push_seq: u64,
+    pop_seq: u64,
 }
 
 impl<T: Clone + PartialOrd> Default for MovingMin<T> {

Review Comment:
   I don't think we need `Clone` anymore.



##########
datafusion/functions-aggregate/src/min_max.rs:
##########
@@ -790,72 +785,54 @@ impl<T: Clone + PartialOrd> MovingMin<T> {
     #[inline]
     pub fn with_capacity(capacity: usize) -> Self {
         Self {
-            push_stack: Vec::with_capacity(capacity),
-            pop_stack: Vec::with_capacity(capacity),
+            deque: VecDeque::with_capacity(capacity),
+            push_seq: 0,
+            pop_seq: 0,
         }
     }
 
     /// Returns the minimum of the sliding window or `None` if the window is
     /// empty.
     #[inline]
     pub fn min(&self) -> Option<&T> {
-        match (self.push_stack.last(), self.pop_stack.last()) {
-            (None, None) => None,
-            (Some((_, min)), None) => Some(min),
-            (None, Some((_, min))) => Some(min),
-            (Some((_, a)), Some((_, b))) => Some(if a < b { a } else { b }),
-        }
+        self.deque.front().map(|(_, val)| val)
     }
 
     /// Pushes a new element into the sliding window.
     #[inline]
     pub fn push(&mut self, val: T) {
-        self.push_stack.push(match self.push_stack.last() {
-            Some((_, min)) => {
-                if val > *min {
-                    (val, min.clone())
-                } else {
-                    (val.clone(), val)
-                }
-            }
-            None => (val.clone(), val),
-        });
+        let seq = self.push_seq;
+        self.push_seq += 1;
+        while self.deque.back().is_some_and(|back_val| back_val.1 > val) {
+            self.deque.pop_back();
+        }

Review Comment:
   I think `>=` would be correct and a bit more efficient for duplicate-heavy 
inputs?



##########
datafusion/functions-aggregate/src/min_max.rs:
##########
@@ -909,71 +887,53 @@ impl<T: Clone + PartialOrd> MovingMax<T> {
     #[inline]
     pub fn with_capacity(capacity: usize) -> Self {
         Self {
-            push_stack: Vec::with_capacity(capacity),
-            pop_stack: Vec::with_capacity(capacity),
+            deque: VecDeque::with_capacity(capacity),
+            push_seq: 0,
+            pop_seq: 0,
         }
     }
 
     /// Returns the maximum of the sliding window or `None` if the window is 
empty.
     #[inline]
     pub fn max(&self) -> Option<&T> {
-        match (self.push_stack.last(), self.pop_stack.last()) {
-            (None, None) => None,
-            (Some((_, max)), None) => Some(max),
-            (None, Some((_, max))) => Some(max),
-            (Some((_, a)), Some((_, b))) => Some(if a > b { a } else { b }),
-        }
+        self.deque.front().map(|(_, val)| val)
     }
 
     /// Pushes a new element into the sliding window.
     #[inline]
     pub fn push(&mut self, val: T) {

Review Comment:
   What do you think of adding some `debug_assert`s to check that invariants on 
the data structure hold after `push()` and `pop()`? For example:
   
   * `pop_seq <= push_seq`
   * `if let Some((front_seq, _)) = self.deque.front() { front_seq >= pop_seq }`



##########
datafusion/functions-aggregate/benches/sliding_min_max.rs:
##########
@@ -0,0 +1,113 @@
+// 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 criterion::{BenchmarkId, Criterion, Throughput, criterion_group, 
criterion_main};
+use datafusion_common::ScalarValue;
+use datafusion_functions_aggregate::min_max::MovingMax;
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+
+// === Generator Utilities ===
+fn generate_random_i64(size: usize) -> Vec<i64> {
+    let mut rng = StdRng::seed_from_u64(42);
+    (0..size).map(|_| rng.random_range(0..1000000)).collect()
+}
+
+fn generate_random_f64(size: usize) -> Vec<f64> {
+    let mut rng = StdRng::seed_from_u64(42);
+    (0..size).map(|_| rng.random()).collect()
+}
+
+fn generate_random_strings(size: usize) -> Vec<String> {
+    let mut rng = StdRng::seed_from_u64(42);
+    (0..size)
+        .map(|_| {
+            let len = rng.random_range(10..40);
+            (0..len)
+                .map(|_| rng.random_range(b'a'..=b'z') as char)
+                .collect()
+        })
+        .collect()
+}
+
+fn bench_sliding_max(c: &mut Criterion) {
+    let data_size = 50000;
+
+    // Generate raw inputs
+    let i64_raw = generate_random_i64(data_size);
+    let f64_raw = generate_random_f64(data_size);
+    let str_raw = generate_random_strings(data_size);
+
+    // Map to ScalarValue types
+    let scalar_int_data: Vec<ScalarValue> = i64_raw
+        .iter()
+        .map(|&val| ScalarValue::Int64(Some(val)))
+        .collect();
+    let scalar_float_data: Vec<ScalarValue> = f64_raw
+        .iter()
+        .map(|&val| ScalarValue::Float64(Some(val)))
+        .collect();
+    let scalar_timestamp_data: Vec<ScalarValue> = i64_raw
+        .iter()
+        .map(|&val| ScalarValue::TimestampNanosecond(Some(val), None))
+        .collect();
+    let scalar_decimal_data: Vec<ScalarValue> = i64_raw
+        .iter()
+        .map(|&val| ScalarValue::Decimal128(Some(val as i128), 38, 10))
+        .collect();
+    let scalar_utf8_data: Vec<ScalarValue> = str_raw
+        .iter()
+        .map(|val| ScalarValue::Utf8(Some(val.clone())))
+        .collect();
+
+    let datasets = vec![
+        ("scalar_int64", scalar_int_data),
+        ("scalar_float64", scalar_float_data),
+        ("scalar_timestamp", scalar_timestamp_data),
+        ("scalar_decimal128", scalar_decimal_data),
+        ("scalar_utf8_string", scalar_utf8_data),
+    ];
+
+    for (label, data) in datasets {
+        let mut group = 
c.benchmark_group(format!("sliding_window_max_{label}"));
+
+        for window_size in [100, 1000, 5000] {
+            group.throughput(Throughput::Elements(data_size as u64));
+
+            group.bench_with_input(
+                BenchmarkId::new("monotonic_deque", window_size),
+                &window_size,
+                |b, &w| {
+                    b.iter(|| {
+                        let mut q = MovingMax::new();
+                        for (i, val) in data.iter().enumerate() {
+                            q.push(val.clone());
+                            if i >= w {
+                                q.pop();
+                            }
+                            let _res = q.max();

Review Comment:
   `std::hint::black_box(q.max());` is safer I think.



##########
datafusion/functions-aggregate/benches/sliding_min_max.rs:
##########
@@ -0,0 +1,113 @@
+// 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 criterion::{BenchmarkId, Criterion, Throughput, criterion_group, 
criterion_main};
+use datafusion_common::ScalarValue;
+use datafusion_functions_aggregate::min_max::MovingMax;
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+
+// === Generator Utilities ===
+fn generate_random_i64(size: usize) -> Vec<i64> {
+    let mut rng = StdRng::seed_from_u64(42);
+    (0..size).map(|_| rng.random_range(0..1000000)).collect()
+}
+
+fn generate_random_f64(size: usize) -> Vec<f64> {
+    let mut rng = StdRng::seed_from_u64(42);
+    (0..size).map(|_| rng.random()).collect()
+}
+
+fn generate_random_strings(size: usize) -> Vec<String> {
+    let mut rng = StdRng::seed_from_u64(42);
+    (0..size)
+        .map(|_| {
+            let len = rng.random_range(10..40);
+            (0..len)
+                .map(|_| rng.random_range(b'a'..=b'z') as char)
+                .collect()
+        })
+        .collect()
+}
+
+fn bench_sliding_max(c: &mut Criterion) {
+    let data_size = 50000;
+
+    // Generate raw inputs
+    let i64_raw = generate_random_i64(data_size);
+    let f64_raw = generate_random_f64(data_size);
+    let str_raw = generate_random_strings(data_size);
+
+    // Map to ScalarValue types
+    let scalar_int_data: Vec<ScalarValue> = i64_raw
+        .iter()
+        .map(|&val| ScalarValue::Int64(Some(val)))
+        .collect();
+    let scalar_float_data: Vec<ScalarValue> = f64_raw
+        .iter()
+        .map(|&val| ScalarValue::Float64(Some(val)))
+        .collect();
+    let scalar_timestamp_data: Vec<ScalarValue> = i64_raw
+        .iter()
+        .map(|&val| ScalarValue::TimestampNanosecond(Some(val), None))
+        .collect();
+    let scalar_decimal_data: Vec<ScalarValue> = i64_raw
+        .iter()
+        .map(|&val| ScalarValue::Decimal128(Some(val as i128), 38, 10))
+        .collect();
+    let scalar_utf8_data: Vec<ScalarValue> = str_raw
+        .iter()
+        .map(|val| ScalarValue::Utf8(Some(val.clone())))
+        .collect();
+
+    let datasets = vec![
+        ("scalar_int64", scalar_int_data),
+        ("scalar_float64", scalar_float_data),
+        ("scalar_timestamp", scalar_timestamp_data),
+        ("scalar_decimal128", scalar_decimal_data),
+        ("scalar_utf8_string", scalar_utf8_data),
+    ];
+
+    for (label, data) in datasets {
+        let mut group = 
c.benchmark_group(format!("sliding_window_max_{label}"));
+
+        for window_size in [100, 1000, 5000] {
+            group.throughput(Throughput::Elements(data_size as u64));
+
+            group.bench_with_input(
+                BenchmarkId::new("monotonic_deque", window_size),

Review Comment:
   A name like "sliding_max" is probably more descriptive.



##########
datafusion/functions-aggregate/src/min_max.rs:
##########
@@ -790,72 +785,54 @@ impl<T: Clone + PartialOrd> MovingMin<T> {
     #[inline]
     pub fn with_capacity(capacity: usize) -> Self {
         Self {
-            push_stack: Vec::with_capacity(capacity),
-            pop_stack: Vec::with_capacity(capacity),
+            deque: VecDeque::with_capacity(capacity),
+            push_seq: 0,
+            pop_seq: 0,
         }
     }
 
     /// Returns the minimum of the sliding window or `None` if the window is
     /// empty.
     #[inline]
     pub fn min(&self) -> Option<&T> {
-        match (self.push_stack.last(), self.pop_stack.last()) {
-            (None, None) => None,
-            (Some((_, min)), None) => Some(min),
-            (None, Some((_, min))) => Some(min),
-            (Some((_, a)), Some((_, b))) => Some(if a < b { a } else { b }),
-        }
+        self.deque.front().map(|(_, val)| val)
     }
 
     /// Pushes a new element into the sliding window.
     #[inline]
     pub fn push(&mut self, val: T) {
-        self.push_stack.push(match self.push_stack.last() {
-            Some((_, min)) => {
-                if val > *min {
-                    (val, min.clone())
-                } else {
-                    (val.clone(), val)
-                }
-            }
-            None => (val.clone(), val),
-        });
+        let seq = self.push_seq;
+        self.push_seq += 1;
+        while self.deque.back().is_some_and(|back_val| back_val.1 > val) {
+            self.deque.pop_back();
+        }
+        self.deque.push_back((seq, val));
     }
 
-    /// Removes and returns the last value of the sliding window.
+    /// Removes the oldest value from the sliding window.
     #[inline]
-    pub fn pop(&mut self) -> Option<T> {
-        if self.pop_stack.is_empty() {
-            match self.push_stack.pop() {
-                Some((val, _)) => {
-                    let mut last = (val.clone(), val);
-                    self.pop_stack.push(last.clone());
-                    while let Some((val, _)) = self.push_stack.pop() {
-                        let min = if last.1 < val {
-                            last.1.clone()
-                        } else {
-                            val.clone()
-                        };
-                        last = (val.clone(), min);
-                        self.pop_stack.push(last.clone());
-                    }
-                }
-                None => return None,
-            }
+    pub fn pop(&mut self) {
+        let seq = self.pop_seq;
+        self.pop_seq += 1;
+        if self
+            .deque
+            .front()
+            .is_some_and(|front_val| front_val.0 == seq)
+        {
+            self.deque.pop_front();
         }

Review Comment:
   What behavior do we want for `pop` on an empty window? Probably should be a 
no-op. Can you also add a unit test for this case?



-- 
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]

Reply via email to