Skip to main content

zu_vector/kernels/
arith.rs

1//! Binary arithmetic kernels.
2//!
3//! The answers are the row engine's answers, conditions included: an
4//! integer answer that does not fit raises `22003`, and a divisor of
5//! nought raises `22012` whatever the numeric type, rather than
6//! answering the infinity the hardware would. A kernel that quietly answered the
7//! wrapped number or a null would be giving a wrong answer where the
8//! standard asks for a condition, and which of the two a query got
9//! would depend on which engine took its plan.
10//!
11//! What that costs is arranged so the rows that have an answer pay
12//! almost nothing for the rows that do not. The compute loop stays
13//! branch free and wraps, and whether any row could have raised is
14//! answered by one pass over the operands that folds them into a single
15//! magnitude, which is cheap and vectorizes. Only when that pass says a
16//! row might have gone over does the kernel walk the selection with
17//! checked arithmetic to find which one, and that walk is the only
18//! place a condition is built.
19//!
20//! The rows outside the chunk's selection are computed and never
21//! looked at, which is what lets the compute loop stay branch free, and
22//! they are not looked at here either: a row the selection dropped is a
23//! row the row engine never evaluated, so it has no condition to raise.
24
25use zu_common::{Result, ZuError, gqlstatus::codes};
26
27use crate::arena::{MorselArena, Pod};
28use crate::bitmap::Bitmap;
29use crate::sel::SelVector;
30use crate::vector::{PhysType, ValueVector, VecEncoding};
31
32#[derive(Clone, Copy, PartialEq, Eq, Debug)]
33pub enum BinOp {
34    Add,
35    Sub,
36    Mul,
37    Div,
38    Mod,
39}
40
41/// The answer for one pair, which is what a chunk of two constants
42/// needs. The loops below do not go through here: they settle the
43/// operation before they start, for the reason `fill` gives.
44#[inline(always)]
45fn apply_i64(op: BinOp, a: i64, b: i64) -> i64 {
46    match op {
47        BinOp::Add => a.wrapping_add(b),
48        BinOp::Sub => a.wrapping_sub(b),
49        BinOp::Mul => a.wrapping_mul(b),
50        BinOp::Div => a.wrapping_div(if b == 0 { 1 } else { b }),
51        BinOp::Mod => a.wrapping_rem(if b == 0 { 1 } else { b }),
52    }
53}
54
55#[inline(always)]
56fn apply_f64(op: BinOp, a: f64, b: f64) -> f64 {
57    match op {
58        BinOp::Add => a + b,
59        BinOp::Sub => a - b,
60        BinOp::Mul => a * b,
61        BinOp::Div => a / b,
62        BinOp::Mod => a % b,
63    }
64}
65
66/// The compute loop over one of the three shapes a pair of vectors
67/// comes in, with the operation already chosen.
68///
69/// `f` arrives monomorphic, so the compiler stamps one loop per
70/// operation and each one holds a single instruction per row wherever
71/// the hardware has one. Which operation it is has to be settled
72/// outside, the way the compare kernel has always settled it: a match
73/// left standing in the loop is a branch the vectorizer will not lift,
74/// and it costs about seven times the throughput of the loop it is
75/// standing in.
76#[inline(always)]
77fn fill<T: Pod, F: Fn(T, T) -> T>(
78    dst: &mut [T],
79    l: &ValueVector,
80    r: &ValueVector,
81    len: usize,
82    f: F,
83) -> Result<()> {
84    match (l.encoding, r.encoding) {
85        (VecEncoding::Flat, VecEncoding::Flat) => {
86            let (a, b) = (l.values::<T>(), r.values::<T>());
87            for i in 0..len {
88                dst[i] = f(a[i], b[i]);
89            }
90        }
91        (VecEncoding::Flat, VecEncoding::Constant) => {
92            let a = l.values::<T>();
93            let c = r.constant_value::<T>();
94            for i in 0..len {
95                dst[i] = f(a[i], c);
96            }
97        }
98        (VecEncoding::Constant, VecEncoding::Flat) => {
99            let c = l.constant_value::<T>();
100            let b = r.values::<T>();
101            for i in 0..len {
102                dst[i] = f(c, b[i]);
103            }
104        }
105        _ => {
106            return Err(ZuError::InvalidArgument(
107                "arithmetic on dict vectors: materialize first".into(),
108            ));
109        }
110    }
111    Ok(())
112}
113
114/// Evaluate `l op r` into a new flat vector. The full vector is computed
115/// regardless of selection: the loop is branch-free and cheaper than
116/// gathering, and selections keep their meaning positionally.
117///
118/// `sel` is the chunk's selection, which says which rows are the
119/// query's. It is what the conditions are raised over and nothing else
120/// reads it, so a caller with every row in hand passes `None`.
121pub fn binary(
122    arena: &mut MorselArena,
123    op: BinOp,
124    l: &ValueVector,
125    r: &ValueVector,
126    sel: Option<&SelVector>,
127) -> Result<ValueVector> {
128    debug_assert_eq!(l.len, r.len);
129    if l.phys != r.phys {
130        return Err(ZuError::InvalidArgument(format!(
131            "no arithmetic kernel for {:?} vs {:?}",
132            l.phys, r.phys
133        )));
134    }
135    let len = l.len as usize;
136    check(op, l, r, sel, len)?;
137    // Two constants make a constant, and it is worth spotting because
138    // it is not a corner case: a value pinned on a level below arrives
139    // here broadcast, so `outer.x * $k` is this shape on every vector
140    // the level above produces. One apply and one word beats a full
141    // pass, and everything downstream reads a constant the same way.
142    if let (VecEncoding::Constant, VecEncoding::Constant) = (l.encoding, r.encoding)
143        && matches!(
144            l.phys,
145            PhysType::Int64 | PhysType::Interval | PhysType::Float64
146        )
147    {
148        let mut out = match l.phys {
149            PhysType::Float64 => {
150                let v = apply_f64(op, l.constant_value::<f64>(), r.constant_value::<f64>());
151                ValueVector::constant(arena, l.phys, v, len)
152            }
153            _ => {
154                let v = apply_i64(op, l.constant_value::<i64>(), r.constant_value::<i64>());
155                ValueVector::constant(arena, l.phys, v, len)
156            }
157        };
158        out.validity = merged_validity(arena, l, r, len);
159        return Ok(out);
160    }
161    let mut out = ValueVector::flat_uninit(arena, l.phys, len);
162    match l.phys {
163        PhysType::Int64 | PhysType::Interval => {
164            {
165                let dst = out.values_mut::<i64>();
166                match op {
167                    BinOp::Add => fill(dst, l, r, len, i64::wrapping_add)?,
168                    BinOp::Sub => fill(dst, l, r, len, i64::wrapping_sub)?,
169                    BinOp::Mul => fill(dst, l, r, len, i64::wrapping_mul)?,
170                    // A divisor of nought is remapped to one so the
171                    // hardware cannot trap on a row nobody selected. A
172                    // selected row never gets here with one, since the
173                    // check ahead of the loop raised on it, so the
174                    // number these two answer is never read.
175                    BinOp::Div => fill(dst, l, r, len, |a: i64, b: i64| {
176                        a.wrapping_div(if b == 0 { 1 } else { b })
177                    })?,
178                    BinOp::Mod => fill(dst, l, r, len, |a: i64, b: i64| {
179                        a.wrapping_rem(if b == 0 { 1 } else { b })
180                    })?,
181                }
182            }
183            out.validity = merged_validity(arena, l, r, len);
184        }
185        PhysType::Float64 => {
186            {
187                let dst = out.values_mut::<f64>();
188                match op {
189                    BinOp::Add => fill(dst, l, r, len, |a: f64, b: f64| a + b)?,
190                    BinOp::Sub => fill(dst, l, r, len, |a: f64, b: f64| a - b)?,
191                    BinOp::Mul => fill(dst, l, r, len, |a: f64, b: f64| a * b)?,
192                    BinOp::Div => fill(dst, l, r, len, |a: f64, b: f64| a / b)?,
193                    BinOp::Mod => fill(dst, l, r, len, |a: f64, b: f64| a % b)?,
194                }
195            }
196            out.validity = merged_validity(arena, l, r, len);
197        }
198        _ => {
199            return Err(ZuError::InvalidArgument(format!(
200                "no arithmetic kernel for {:?}",
201                l.phys
202            )));
203        }
204    }
205    Ok(out)
206}
207
208/// `22012 data exception, division by zero`, for both `/` and `%`, in
209/// the words the row engine raises it with. The standard's name says
210/// division, and the modulus of a zero divisor is undefined for exactly
211/// the same reason.
212fn divide_by_zero(op: BinOp) -> ZuError {
213    let what = if matches!(op, BinOp::Mod) {
214        "modulus"
215    } else {
216        "division"
217    };
218    ZuError::gql(codes::C22012, format!("{what} by zero"))
219}
220
221/// `22003 data exception, numeric value out of range`, for the other
222/// thing arithmetic can fail at: an answer that does not fit the type
223/// holding it.
224///
225/// The float half of the library has always raised this for an answer
226/// that left the range a double holds, and an integer answer that left
227/// the range an i64 holds is the same sentence about a different width.
228/// A statement that got a bare refusal instead was told the engine
229/// would not answer without being told what the standard calls it.
230fn overflow() -> ZuError {
231    ZuError::gql(codes::C22003, "integer overflow".to_string())
232}
233
234/// Raises what the row engine raises for the first row of the selection
235/// that has no answer, and answers `Ok` when every selected row has
236/// one.
237///
238/// A row whose operands are not both valid is skipped, since a null
239/// operand answers null rather than raising, and a row the selection
240/// dropped is skipped because the row engine never evaluated it.
241fn check(
242    op: BinOp,
243    l: &ValueVector,
244    r: &ValueVector,
245    sel: Option<&SelVector>,
246    len: usize,
247) -> Result<()> {
248    let risky = match l.phys {
249        PhysType::Int64 | PhysType::Interval => match op {
250            // Two numbers below two to the sixty second cannot add or
251            // subtract past the top, and two below two to the thirty
252            // first cannot multiply past it, so one fold over the
253            // operands answers for the whole chunk. It answers
254            // conservatively, which is the right way round: a chunk of
255            // large numbers pays for a walk that finds nothing.
256            BinOp::Add | BinOp::Sub => (magnitude(l, len) | magnitude(r, len)) >= 1u64 << 62,
257            BinOp::Mul => (magnitude(l, len) | magnitude(r, len)) >= 1u64 << 31,
258            // Nought has no answer at all, and minus one has none for
259            // the one dividend whose negation does not fit.
260            BinOp::Div | BinOp::Mod => awkward_divisor(r, len),
261        },
262        // The approximate numbers overflow to an infinity, which is
263        // what the row engine answers too, so a divisor of nought is
264        // the whole of what can go wrong.
265        PhysType::Float64 => matches!(op, BinOp::Div | BinOp::Mod) && zero_divisor_f64(r, len),
266        _ => false,
267    };
268    if !risky {
269        return Ok(());
270    }
271    let float = l.phys == PhysType::Float64;
272    let visit = |i: usize| -> Result<()> {
273        if !l.is_valid(i) || !r.is_valid(i) {
274            return Ok(());
275        }
276        if float {
277            if at_f64(r, i) == 0.0 {
278                return Err(divide_by_zero(op));
279            }
280            return Ok(());
281        }
282        let (a, b) = (at_i64(l, i), at_i64(r, i));
283        let fits = match op {
284            BinOp::Add => a.checked_add(b).is_some(),
285            BinOp::Sub => a.checked_sub(b).is_some(),
286            BinOp::Mul => a.checked_mul(b).is_some(),
287            BinOp::Div | BinOp::Mod => {
288                if b == 0 {
289                    return Err(divide_by_zero(op));
290                }
291                a.checked_div(b).is_some()
292            }
293        };
294        if fits { Ok(()) } else { Err(overflow()) }
295    };
296    match sel {
297        Some(sel) => {
298            for &row in sel.as_slice() {
299                visit(row as usize)?;
300            }
301        }
302        None => {
303            for i in 0..len {
304                visit(i)?;
305            }
306        }
307    }
308    Ok(())
309}
310
311/// The bits every value in the vector fits inside, as the OR of what
312/// each one takes without its sign. A dict vector answers with every
313/// bit set, since the arithmetic loops refuse one anyway and this is
314/// read before them.
315fn magnitude(v: &ValueVector, len: usize) -> u64 {
316    match v.encoding {
317        VecEncoding::Flat => v.values::<i64>()[..len]
318            .iter()
319            .fold(0u64, |acc, x| acc | x.unsigned_abs()),
320        VecEncoding::Constant => v.constant_value::<i64>().unsigned_abs(),
321        VecEncoding::Dict { .. } => u64::MAX,
322    }
323}
324
325/// Whether the divisor holds a value the division has no answer for.
326fn awkward_divisor(v: &ValueVector, len: usize) -> bool {
327    match v.encoding {
328        VecEncoding::Flat => v.values::<i64>()[..len].iter().any(|&x| x == 0 || x == -1),
329        VecEncoding::Constant => matches!(v.constant_value::<i64>(), 0 | -1),
330        VecEncoding::Dict { .. } => true,
331    }
332}
333
334/// The same question over the approximate numbers, where minus one is
335/// an ordinary divisor and nought is not.
336fn zero_divisor_f64(v: &ValueVector, len: usize) -> bool {
337    match v.encoding {
338        // Nought and minus nought are one value to a comparison, which
339        // is what the fold is asking, so both are found here.
340        VecEncoding::Flat => v.values::<f64>()[..len].contains(&0.0),
341        VecEncoding::Constant => v.constant_value::<f64>() == 0.0,
342        VecEncoding::Dict { .. } => true,
343    }
344}
345
346fn at_i64(v: &ValueVector, i: usize) -> i64 {
347    match v.encoding {
348        VecEncoding::Constant => v.constant_value::<i64>(),
349        _ => v.values::<i64>()[i],
350    }
351}
352
353fn at_f64(v: &ValueVector, i: usize) -> f64 {
354    match v.encoding {
355        VecEncoding::Constant => v.constant_value::<f64>(),
356        _ => v.values::<f64>()[i],
357    }
358}
359
360/// NULL in, NULL out: the output validity is the AND of the inputs',
361/// allocated only when either side actually carries one.
362fn merged_validity(
363    arena: &mut MorselArena,
364    l: &ValueVector,
365    r: &ValueVector,
366    len: usize,
367) -> Option<Bitmap> {
368    match (&l.validity, &r.validity) {
369        (None, None) => None,
370        (a, b) => {
371            let mut v = Bitmap::new_in(arena, len, true);
372            if let Some(a) = a {
373                v.and_with(a);
374            }
375            if let Some(b) = b {
376                v.and_with(b);
377            }
378            Some(v)
379        }
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    use crate::sel::SelVector;
388
389    /// The condition a kernel raised, as the words a caller reads.
390    /// `ValueVector` says nothing about itself, so the answer arm names
391    /// what happened rather than printing what came back.
392    fn raised(out: Result<ValueVector>) -> String {
393        match out {
394            Ok(_) => panic!("the kernel answered where it has no answer"),
395            Err(err) => err.to_string(),
396        }
397    }
398
399    #[test]
400    fn add_flat_const() {
401        let mut arena = MorselArena::new();
402        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 2, 3]);
403        let r = ValueVector::constant(&mut arena, PhysType::Int64, 10i64, 3);
404        let out = binary(&mut arena, BinOp::Add, &l, &r, None).unwrap();
405        assert_eq!(out.values::<i64>(), &[11, 12, 13]);
406        assert!(out.validity.is_none());
407    }
408
409    /// The condition the standard names for it, in the words the row
410    /// engine uses, since a query cannot tell which engine answered it.
411    #[test]
412    fn div_by_zero_raises() {
413        let mut arena = MorselArena::new();
414        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
415        let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
416        let out = binary(&mut arena, BinOp::Div, &l, &r, None);
417        assert_eq!(raised(out), "22012: division by zero");
418        let out = binary(&mut arena, BinOp::Mod, &l, &r, None);
419        assert_eq!(raised(out), "22012: modulus by zero");
420    }
421
422    /// A row the selection dropped is a row the query never asked
423    /// about, so the divisor it holds is not a condition.
424    #[test]
425    fn a_row_outside_the_selection_raises_nothing() {
426        let mut arena = MorselArena::new();
427        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
428        let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
429        let mut sel = SelVector::with_capacity(&mut arena, 2);
430        sel.push(0);
431        sel.push(2);
432        let out = binary(&mut arena, BinOp::Div, &l, &r, Some(&sel)).unwrap();
433        assert_eq!(out.values::<i64>()[0], 5);
434        assert_eq!(out.values::<i64>()[2], 10);
435    }
436
437    /// A null operand answers null, which is not a condition either, so
438    /// the divisor under it is never read.
439    #[test]
440    fn a_null_operand_is_not_a_condition() {
441        let mut arena = MorselArena::new();
442        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30]);
443        let mut r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 0, 3]);
444        let mut valid = Bitmap::new_in(&mut arena, 3, true);
445        valid.clear(1);
446        r.validity = Some(valid);
447        let out = binary(&mut arena, BinOp::Div, &l, &r, None).unwrap();
448        assert!(!out.is_valid(1), "null in, null out");
449    }
450
451    /// An answer too wide for the type is `22003 numeric value out of
452    /// range`, the same condition the row engine raises for it, and the
453    /// fold that finds it looks at the operands rather than at the
454    /// answer, so a chunk of ordinary numbers never reaches the walk
455    /// that builds the condition.
456    #[test]
457    fn an_integer_answer_that_does_not_fit_raises() {
458        let mut arena = MorselArena::new();
459        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, i64::MAX]);
460        let r = ValueVector::constant(&mut arena, PhysType::Int64, 1i64, 2);
461        let out = binary(&mut arena, BinOp::Add, &l, &r, None);
462        assert_eq!(raised(out), "22003: integer overflow");
463
464        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[1i64, 1 << 40]);
465        let r = ValueVector::constant(&mut arena, PhysType::Int64, 1i64 << 40, 2);
466        let out = binary(&mut arena, BinOp::Mul, &l, &r, None);
467        assert_eq!(raised(out), "22003: integer overflow");
468
469        // The one dividend a divisor of minus one has no answer for.
470        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[i64::MIN]);
471        let r = ValueVector::constant(&mut arena, PhysType::Int64, -1i64, 1);
472        let out = binary(&mut arena, BinOp::Div, &l, &r, None);
473        assert_eq!(raised(out), "22003: integer overflow");
474    }
475
476    /// The approximate numbers raise on a divisor of nought too, which
477    /// is where a kernel that answered what the hardware answers would
478    /// hand back an infinity the statement never asked for.
479    #[test]
480    fn a_float_divisor_of_nought_raises() {
481        let mut arena = MorselArena::new();
482        let l = ValueVector::flat_from(&mut arena, PhysType::Float64, &[1.0f64, 2.0]);
483        let r = ValueVector::flat_from(&mut arena, PhysType::Float64, &[2.0f64, 0.0]);
484        let out = binary(&mut arena, BinOp::Div, &l, &r, None);
485        assert_eq!(raised(out), "22012: division by zero");
486    }
487
488    /// Two numbers wide enough to worry the fold but whose answer fits.
489    #[test]
490    fn a_wide_answer_that_fits_is_an_answer() {
491        let mut arena = MorselArena::new();
492        let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &[i64::MAX, i64::MIN]);
493        let r = ValueVector::constant(&mut arena, PhysType::Int64, 0i64, 2);
494        let out = binary(&mut arena, BinOp::Add, &l, &r, None).unwrap();
495        assert_eq!(out.values::<i64>(), &[i64::MAX, i64::MIN]);
496    }
497
498    /// The kernel settles the operation outside its loop, so the answer
499    /// a chunk gets is written in five places where it used to be
500    /// written in one. This walks every operation over every shape a
501    /// pair of vectors comes in and compares what the kernel wrote
502    /// against what one pair at a time answers, which is the check that
503    /// keeps the two from drifting apart.
504    #[test]
505    fn every_operation_answers_what_one_pair_answers() {
506        const OPS: [BinOp; 5] = [BinOp::Add, BinOp::Sub, BinOp::Mul, BinOp::Div, BinOp::Mod];
507        let whole: [i64; 4] = [7, -30, 1, 5];
508        let real: [f64; 4] = [7.5, -30.25, 1.0, 5.0];
509        let mut arena = MorselArena::new();
510        for op in OPS {
511            let l = ValueVector::flat_from(&mut arena, PhysType::Int64, &whole);
512            let r = ValueVector::flat_from(&mut arena, PhysType::Int64, &[2i64, 3, 4, 5]);
513            let c = ValueVector::constant(&mut arena, PhysType::Int64, 3i64, 4);
514            for (name, l, r) in [("flat flat", &l, &r), ("flat const", &l, &c)] {
515                let out = binary(&mut arena, op, l, r, None).unwrap();
516                for i in 0..4 {
517                    let want = apply_i64(op, at_i64(l, i), at_i64(r, i));
518                    assert_eq!(out.values::<i64>()[i], want, "{op:?} {name} row {i}");
519                }
520            }
521            let out = binary(&mut arena, op, &c, &r, None).unwrap();
522            for i in 0..4 {
523                let want = apply_i64(op, 3, at_i64(&r, i));
524                assert_eq!(out.values::<i64>()[i], want, "{op:?} const flat row {i}");
525            }
526
527            let l = ValueVector::flat_from(&mut arena, PhysType::Float64, &real);
528            let r = ValueVector::flat_from(&mut arena, PhysType::Float64, &[2.0f64, 3.0, 4.0, 0.5]);
529            let out = binary(&mut arena, op, &l, &r, None).unwrap();
530            for (i, x) in real.iter().enumerate() {
531                let want = apply_f64(op, *x, at_f64(&r, i));
532                assert_eq!(out.values::<f64>()[i], want, "{op:?} float row {i}");
533            }
534        }
535    }
536}