Skip to main content

zu_vector/kernels/
agg.rs

1//! Aggregate input kernels: straight-line reductions over a vector,
2//! validity- and selection-aware. These feed the aggregate operators;
3//! the grouping machinery lives with the executor.
4
5use crate::sel::SelVector;
6use crate::vector::{ValueVector, VecEncoding};
7
8/// Wrapping sum of an Int64-domain vector. The no-null no-selection flat
9/// case is the B3 scan+sum inner loop and must stay a bare reduction the
10/// auto-vectorizer folds.
11pub fn sum_i64(v: &ValueVector, sel: Option<&SelVector>) -> i64 {
12    match (v.encoding, sel, &v.validity) {
13        (VecEncoding::Constant, sel, _) => {
14            let n = match sel {
15                Some(s) => s.len() as i64,
16                None => i64::from(v.len),
17            };
18            v.constant_value::<i64>().wrapping_mul(n)
19        }
20        (VecEncoding::Flat, None, None) => {
21            let mut acc = 0i64;
22            for &x in v.values::<i64>() {
23                acc = acc.wrapping_add(x);
24            }
25            acc
26        }
27        (VecEncoding::Flat, None, Some(valid)) => {
28            // Branch-free: multiply each value by its validity bit.
29            let mut acc = 0i64;
30            for (i, &x) in v.values::<i64>().iter().enumerate() {
31                acc = acc.wrapping_add(x.wrapping_mul(i64::from(valid.get(i))));
32            }
33            acc
34        }
35        (VecEncoding::Flat, Some(s), _) => {
36            let vals = v.values::<i64>();
37            let mut acc = 0i64;
38            for &row in s.as_slice() {
39                let i = row as usize;
40                if v.is_valid(i) {
41                    acc = acc.wrapping_add(vals[i]);
42                }
43            }
44            acc
45        }
46        (VecEncoding::Dict { .. }, _, _) => unreachable!("no i64 dict vectors"),
47    }
48}
49
50pub fn sum_f64(v: &ValueVector, sel: Option<&SelVector>) -> f64 {
51    match (v.encoding, sel) {
52        (VecEncoding::Constant, sel) => {
53            let n = match sel {
54                Some(s) => s.len() as f64,
55                None => f64::from(v.len),
56            };
57            v.constant_value::<f64>() * n
58        }
59        (VecEncoding::Flat, None) => {
60            let mut acc = 0f64;
61            for (i, &x) in v.values::<f64>().iter().enumerate() {
62                if v.is_valid(i) {
63                    acc += x;
64                }
65            }
66            acc
67        }
68        (VecEncoding::Flat, Some(s)) => {
69            let vals = v.values::<f64>();
70            let mut acc = 0f64;
71            for &row in s.as_slice() {
72                let i = row as usize;
73                if v.is_valid(i) {
74                    acc += vals[i];
75                }
76            }
77            acc
78        }
79        (VecEncoding::Dict { .. }, _) => unreachable!("no f64 dict vectors"),
80    }
81}
82
83/// Non-null row count under the selection.
84pub fn count_valid(v: &ValueVector, sel: Option<&SelVector>) -> usize {
85    match (&v.validity, sel) {
86        (None, None) => v.len(),
87        (None, Some(s)) => s.len(),
88        (Some(valid), None) => valid.count_ones(),
89        (Some(valid), Some(s)) => s
90            .as_slice()
91            .iter()
92            .filter(|&&row| valid.get(row as usize))
93            .count(),
94    }
95}
96
97macro_rules! minmax {
98    ($name:ident, $better:tt) => {
99        /// Extreme of the valid rows, None when every row is null.
100        pub fn $name(v: &ValueVector, sel: Option<&SelVector>) -> Option<i64> {
101            let mut best: Option<i64> = None;
102            let mut consider = |x: i64| match best {
103                Some(b) if !(x $better b) => {}
104                _ => best = Some(x),
105            };
106            match (v.encoding, sel) {
107                (VecEncoding::Constant, _) => {
108                    if count_valid(v, sel) > 0 {
109                        consider(v.constant_value::<i64>());
110                    }
111                }
112                // A column with nothing missing in it, which is the
113                // scan this reduction is on the hot path of, and the
114                // one shape here written for the vectorizer rather than
115                // for the reader. The accumulator is an i64 and not an
116                // Option of one, and the row is a select rather than a
117                // branch, which is the pair of things that turn into a
118                // lane wide minimum. The loop below it, folding an
119                // Option that is empty until the first row over a
120                // validity nobody here has to ask about, takes a row at
121                // a time and measured 0 vector instructions on both
122                // architectures; this one takes 31 on aarch64.
123                //
124                // Where it lands is the ISA's to say. NEON compares two
125                // 64 bit lanes with cmgt and selects with bsl, so the
126                // reduction folds. A generic x86-64 build has neither:
127                // the packed 64 bit compare is SSE4.2 and the packed 64
128                // bit minimum is AVX-512, and with only SSE2 to hand
129                // LLVM leaves the loop scalar. The disassembly gate
130                // knows that and asks for lanes on the one where they
131                // are reachable.
132                (VecEncoding::Flat, None) if v.validity.is_none() => {
133                    let vals = v.values::<i64>();
134                    if let Some((&first, rest)) = vals.split_first() {
135                        let mut acc = first;
136                        for &x in rest {
137                            acc = if x $better acc { x } else { acc };
138                        }
139                        consider(acc);
140                    }
141                }
142                (VecEncoding::Flat, None) => {
143                    for (i, &x) in v.values::<i64>().iter().enumerate() {
144                        if v.is_valid(i) {
145                            consider(x);
146                        }
147                    }
148                }
149                (VecEncoding::Flat, Some(s)) => {
150                    let vals = v.values::<i64>();
151                    for &row in s.as_slice() {
152                        if v.is_valid(row as usize) {
153                            consider(vals[row as usize]);
154                        }
155                    }
156                }
157                (VecEncoding::Dict { .. }, _) => unreachable!("no i64 dict vectors"),
158            }
159            best
160        }
161    };
162}
163
164minmax!(min_i64, <);
165minmax!(max_i64, >);
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::arena::MorselArena;
171    use crate::bitmap::Bitmap;
172    use crate::vector::PhysType;
173
174    #[test]
175    fn sums_and_extremes() {
176        let mut arena = MorselArena::new();
177        let v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[3i64, -1, 7, 0]);
178        assert_eq!(sum_i64(&v, None), 9);
179        assert_eq!(min_i64(&v, None), Some(-1));
180        assert_eq!(max_i64(&v, None), Some(7));
181        assert_eq!(count_valid(&v, None), 4);
182    }
183
184    #[test]
185    fn nulls_are_skipped() {
186        let mut arena = MorselArena::new();
187        let mut v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[5i64, 100, 2]);
188        let mut valid = Bitmap::new_in(&mut arena, 3, true);
189        valid.clear(1);
190        v.validity = Some(valid);
191        assert_eq!(sum_i64(&v, None), 7);
192        assert_eq!(max_i64(&v, None), Some(5));
193        assert_eq!(count_valid(&v, None), 2);
194    }
195
196    #[test]
197    fn constant_scales_by_count() {
198        let mut arena = MorselArena::new();
199        let v = ValueVector::constant(&mut arena, PhysType::Int64, 4i64, 10);
200        assert_eq!(sum_i64(&v, None), 40);
201    }
202}