Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-datalog/tests/computed.rs

//! K1 + K2: computed values in a rule body (`O = LO + I`, `T = INFO & 0xF`) and conditions
//! over expressions (`F & 4 != 0`), each against plain Rust over the same rows, at 1, 2 and
//! 4 threads.

use std::collections::BTreeSet;
use std::sync::Arc;

use arrow_array::{ArrayRef, Int64Array, UInt64Array};
use kleene_datalog::{
    Datum, Engine, Expr, Facts, Inputs, Program, Term, Type, compute, datalog, ne, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};

fn engine(threads: usize) -> Engine<CpuBackend> {
    Engine::new(CpuDevice::new(threads)).explain(true)
}

/// Deterministic pseudo-random numbers (a 64-bit LCG), no dependency.
struct Lcg(u64);

impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0 >> 11
    }

    /// A value: mostly small, some near the top of u64, some zero.
    fn value(&mut self) -> u64 {
        match self.next() % 8 {
            0 => 0,
            1 => u64::MAX - self.next() % 64,
            2 => 1 << (self.next() % 64),
            _ => self.next() % 5000,
        }
    }
}

fn facts<const N: usize>(rows: &[[u64; N]]) -> Facts {
    Facts::from_rows(N, rows.iter().map(|r| r.to_vec())).unwrap()
}

fn set(f: Option<&Facts>) -> BTreeSet<Vec<u64>> {
    f.map(|f| f.rows().collect()).unwrap_or_default()
}

/// A u64 value of an exact integer, if it fits.
fn fit(x: i128) -> Option<u64> {
    u64::try_from(x).ok()
}

#[tokio::test]
async fn the_contract_examples_equal_plain_rust_at_every_thread_count() {
    let mask = 0x8u64;
    let (p, r) = datalog! {
        input st/2, ix/2, origin/4, piece/3, sym_info/2, line_flags/2, kdecl_arg/2, line/2.
        derived off/2, addr/2, size/2, stype/2, ended/1, exec/1, next/3, prev_ix/2.
        off(S, O)   :- st(S, LO), ix(S, I), O = LO + I.
        addr(X, A)  :- origin(X, SA, OFF, SO), A = SA + OFF - SO.
        size(P, N)  :- piece(P, LO, HI), N = HI - LO.
        stype(S, T) :- sym_info(S, INFO), T = INFO & {0xF}.
        ended(L)    :- line_flags(L, F), F & {mask} != 0.
        exec(M)     :- kdecl_arg(M, V), V & 4 != 0.
        next(R, A, A1) :- line(R, A), R1 = R + 1, line(R1, A1).
        prev_ix(S, J) :- ix(S, I), J = I - 1.
    }
    .unwrap();
    assert!(plan(&p).is_ok());
    let mut g = Lcg(11);
    let n = 40_000usize;
    let st: Vec<[u64; 2]> = (0..n as u64 / 8).map(|s| [s, g.value()]).collect();
    let ix: Vec<[u64; 2]> = (0..n as u64)
        .map(|k| [k % (n as u64 / 8), g.value()])
        .collect();
    let origin: Vec<[u64; 4]> = (0..n as u64)
        .map(|x| [x, g.value(), g.value(), g.value()])
        .collect();
    let piece: Vec<[u64; 3]> = (0..n as u64).map(|x| [x, g.value(), g.value()]).collect();
    let sym: Vec<[u64; 2]> = (0..n as u64).map(|x| [x, g.next()]).collect();
    let flags: Vec<[u64; 2]> = (0..n as u64).map(|x| [x, g.next() % 64]).collect();
    let karg: Vec<[u64; 2]> = (0..n as u64).map(|x| [x, g.value()]).collect();
    // rows numbered with gaps: the next row exists for most
    let line: Vec<[u64; 2]> = (0..n as u64)
        .filter(|r| r % 7 != 3)
        .map(|r| [r, g.value()])
        .collect();
    let mut inputs = Inputs::new();
    inputs.facts(&r.st, facts(&st)).unwrap();
    inputs.facts(&r.ix, facts(&ix)).unwrap();
    inputs.facts(&r.origin, facts(&origin)).unwrap();
    inputs.facts(&r.piece, facts(&piece)).unwrap();
    inputs.facts(&r.sym_info, facts(&sym)).unwrap();
    inputs.facts(&r.line_flags, facts(&flags)).unwrap();
    inputs.facts(&r.kdecl_arg, facts(&karg)).unwrap();
    inputs.facts(&r.line, facts(&line)).unwrap();

    // the plain reference
    let st_lo: std::collections::HashMap<u64, u64> = st.iter().map(|&[s, lo]| (s, lo)).collect();
    let mut want_off = BTreeSet::new();
    for &[s, i] in &ix {
        if let Some(&lo) = st_lo.get(&s)
            && let Some(o) = fit(lo as i128 + i as i128)
        {
            want_off.insert(vec![s, o]);
        }
    }
    let want_addr: BTreeSet<Vec<u64>> = origin
        .iter()
        .filter_map(|&[x, sa, off, so]| {
            fit(sa as i128 + off as i128 - so as i128).map(|a| vec![x, a])
        })
        .collect();
    let want_size: BTreeSet<Vec<u64>> = piece
        .iter()
        .filter_map(|&[pc, lo, hi]| hi.checked_sub(lo).map(|n| vec![pc, n]))
        .collect();
    let want_stype: BTreeSet<Vec<u64>> = sym.iter().map(|&[s, i]| vec![s, i & 0xF]).collect();
    let want_ended: BTreeSet<Vec<u64>> = flags
        .iter()
        .filter(|f| f[1] & mask != 0)
        .map(|f| vec![f[0]])
        .collect();
    let want_exec: BTreeSet<Vec<u64>> = karg
        .iter()
        .filter(|f| f[1] & 4 != 0)
        .map(|f| vec![f[0]])
        .collect();
    let by_row: std::collections::HashMap<u64, u64> = line.iter().map(|&[r, a]| (r, a)).collect();
    let want_next: BTreeSet<Vec<u64>> = line
        .iter()
        .filter_map(|&[r, a]| by_row.get(&(r + 1)).map(|&a1| vec![r, a, a1]))
        .collect();
    let want_prev: BTreeSet<Vec<u64>> = ix
        .iter()
        .filter_map(|&[s, i]| i.checked_sub(1).map(|j| vec![s, j]))
        .collect();
    assert!(want_off.len() > 1000 && want_next.len() > 1000);
    assert!(want_addr.len() < origin.len(), "some origins do not fit");
    assert!(want_size.len() < piece.len(), "some pieces are below 0");

    let mut proofs_at_one: Option<Vec<String>> = None;
    for threads in [1, 2, 4] {
        let out = engine(threads).run(&p, &inputs).await.unwrap();
        assert_eq!(set(out.get(&r.off)), want_off, "off at {threads}");
        assert_eq!(set(out.get(&r.addr)), want_addr, "addr at {threads}");
        assert_eq!(set(out.get(&r.size)), want_size, "size at {threads}");
        assert_eq!(set(out.get(&r.stype)), want_stype, "stype at {threads}");
        assert_eq!(set(out.get(&r.ended)), want_ended, "ended at {threads}");
        assert_eq!(set(out.get(&r.exec)), want_exec, "exec at {threads}");
        assert_eq!(set(out.get(&r.next)), want_next, "next at {threads}");
        assert_eq!(set(out.get(&r.prev_ix)), want_prev, "prev_ix at {threads}");
        // a sample of proofs, the same at every thread count
        let mut proofs = Vec::new();
        for row in want_addr.iter().take(50) {
            proofs.push(out.why(&p, &r.addr, [row[0], row[1]]).unwrap().render(&p));
        }
        for row in want_next.iter().take(50) {
            proofs.push(
                out.why(&p, &r.next, [row[0], row[1], row[2]])
                    .unwrap()
                    .render(&p),
            );
        }
        for row in want_ended.iter().take(50) {
            proofs.push(out.why(&p, &r.ended, [row[0]]).unwrap().render(&p));
        }
        match &proofs_at_one {
            None => proofs_at_one = Some(proofs),
            Some(one) => assert_eq!(one, &proofs, "proofs at {threads}"),
        }
    }
}

#[tokio::test]
async fn show_rule_as_written_and_the_proof_shows_the_operands() {
    let (p, r) = datalog! {
        input st/2, ix/2, line_flags/2.
        derived off/2, ended/1, inside/2.
        off(S, O) :- st(S, LO), ix(S, I), O = LO + I.
        ended(L) :- line_flags(L, F), F & 4 != 0.
        inside(S, I) :- st(S, LO), ix(S, I), I + 1 in LO..(LO << 1) + 3.
    }
    .unwrap();
    let shown: Vec<String> = (0..3)
        .map(|i| p.show_rule(kleene_datalog_rule(i)))
        .collect();
    assert_eq!(
        shown,
        [
            "off(S, O) :- st(S, LO), ix(S, I), O = LO + I.",
            "ended(L) :- line_flags(L, F), F & 4 != 0.",
            "inside(S, I) :- st(S, LO), ix(S, I), I + 1 in [LO, (LO << 1) + 3).",
        ]
    );
    let mut inputs = Inputs::new();
    inputs.facts(&r.st, facts(&[[1, 3], [2, 10]])).unwrap();
    inputs
        .facts(&r.ix, facts(&[[1, 4], [2, 9], [2, 30]]))
        .unwrap();
    inputs
        .facts(&r.line_flags, facts(&[[7, 5], [8, 2]]))
        .unwrap();
    let out = engine(2).run(&p, &inputs).await.unwrap();
    assert_eq!(
        set(out.get(&r.off)),
        [vec![1, 7], vec![2, 19], vec![2, 40]].into()
    );
    assert_eq!(set(out.get(&r.ended)), [vec![7]].into());
    // 1 + 4 = 5 in [3, 9); 2: 10 in [10, 23), 31 not
    assert_eq!(set(out.get(&r.inside)), [vec![1, 4], vec![2, 9]].into());
    let off = out.why(&p, &r.off, [1u64, 7]).unwrap().render(&p);
    assert!(off.contains("O = LO + I = 3 + 4 = 7  [computed]"), "{off}");
    let ended = out.why(&p, &r.ended, [7u64]).unwrap().render(&p);
    assert!(ended.contains("F & 4 = 5 & 4 = 4  [computed]"), "{ended}");
    assert!(ended.contains("4 != 0  [holds]"), "{ended}");
}

/// The id of rule `i` (rules are numbered as added).
fn kleene_datalog_rule(i: usize) -> kleene_datalog::RuleId {
    let mut p = Program::new();
    let a = p.input::<1>("a");
    let d = p.derived::<1>("d");
    let x = p.var("X");
    let mut last = None;
    for _ in 0..=i {
        last = Some(p.rule(d.at([x]), [a.at([x])]).unwrap());
    }
    last.unwrap()
}

#[tokio::test]
async fn no_row_where_an_unsigned_value_does_not_fit() {
    let (p, r) = datalog! {
        input pair/2.
        derived add/3, sub/3, mul/3, div/3, rem/3, shl/3, shr/3, wide/3, neg/2, not/2, both/2.
        add(A, B, C) :- pair(A, B), C = A + B.
        sub(A, B, C) :- pair(A, B), C = A - B.
        mul(A, B, C) :- pair(A, B), C = A * B.
        div(A, B, C) :- pair(A, B), C = A / B.
        rem(A, B, C) :- pair(A, B), C = A % B.
        shl(A, B, C) :- pair(A, B), C = A << B.
        shr(A, B, C) :- pair(A, B), C = A >> B.
        wide(A, B, C) :- pair(A, B), C = A - B + 100.
        neg(A, C) :- pair(A, _), C = -A.
        not(A, C) :- pair(A, B), C = !A & B.
        both(A, B) :- pair(A, B), -A + B == B - A.
    }
    .unwrap();
    let vals = [
        0u64,
        1,
        2,
        3,
        7,
        63,
        64,
        65,
        100,
        1 << 40,
        u64::MAX - 1,
        u64::MAX,
    ];
    let rows: Vec<[u64; 2]> = vals
        .iter()
        .flat_map(|&a| vals.iter().map(move |&b| [a, b]))
        .collect();
    let mut inputs = Inputs::new();
    inputs.facts(&r.pair, facts(&rows)).unwrap();
    let out = engine(2).run(&p, &inputs).await.unwrap();
    let want = |f: &dyn Fn(u64, u64) -> Option<u64>| -> BTreeSet<Vec<u64>> {
        rows.iter()
            .filter_map(|&[a, b]| f(a, b).map(|c| vec![a, b, c]))
            .collect()
    };
    assert_eq!(set(out.get(&r.add)), want(&|a, b| a.checked_add(b)));
    assert_eq!(set(out.get(&r.sub)), want(&|a, b| a.checked_sub(b)));
    assert_eq!(set(out.get(&r.mul)), want(&|a, b| a.checked_mul(b)));
    assert_eq!(set(out.get(&r.div)), want(&|a, b| a.checked_div(b)));
    assert_eq!(set(out.get(&r.rem)), want(&|a, b| a.checked_rem(b)));
    assert_eq!(
        set(out.get(&r.shl)),
        want(&|a, b| (b < 64).then(|| a << b).filter(|&c| c >> b == a))
    );
    assert_eq!(set(out.get(&r.shr)), want(&|a, b| (b < 64).then(|| a >> b)));
    assert_eq!(
        set(out.get(&r.wide)),
        want(&|a, b| fit(a as i128 - b as i128 + 100))
    );
    let neg: BTreeSet<Vec<u64>> = vals
        .iter()
        .filter(|&&a| a == 0)
        .map(|&a| vec![a, 0])
        .collect();
    assert_eq!(set(out.get(&r.neg)), neg);
    let not: BTreeSet<Vec<u64>> = rows.iter().map(|&[a, b]| vec![a, !a & b]).collect();
    assert_eq!(set(out.get(&r.not)), not);
    // -A + B == B - A holds where both sides have a value
    let both: BTreeSet<Vec<u64>> = rows
        .iter()
        .filter(|&&[a, b]| b >= a)
        .map(|&[a, b]| vec![a, b])
        .collect();
    assert_eq!(set(out.get(&r.both)), both);
}

#[tokio::test]
async fn a_bound_variable_is_an_equality_test() {
    let (p, r) = datalog! {
        input pair/2, num/1.
        derived double/2, back/1.
        double(X, Y) :- pair(X, Y), Y = X * 2.
        back(X) :- num(X), Y = X + 5, num(Y), Z = Y - 5, Z == X.
    }
    .unwrap();
    let mut inputs = Inputs::new();
    inputs
        .facts(&r.pair, facts(&[[1, 2], [2, 5], [3, 6], [u64::MAX, 0]]))
        .unwrap();
    inputs.facts(&r.num, facts(&[[1], [6], [7], [20]])).unwrap();
    let out = engine(1).run(&p, &inputs).await.unwrap();
    assert_eq!(set(out.get(&r.double)), [vec![1, 2], vec![3, 6]].into());
    assert_eq!(set(out.get(&r.back)), [vec![1]].into());
}

#[tokio::test]
async fn a_signed_link_column_joins_unsigned_ids() {
    // site_iid(S, IID): an int64 column holding a row of `inst` (base 100), one negative,
    // one null; callee(S, ID) :- site_iid(S, IID), ID = IID + {base}, inst(ID).
    let base = 100u64;
    let mut p = Program::new();
    let site_iid = p.input_typed("site_iid", [Type::U64, Type::I64]);
    let inst = p.input::<1>("inst");
    let shifted = p.derived_typed("shifted", [Type::U64, Type::I64]);
    let r = datalog!(&mut p =>
        derived callee/2.
        callee(S, ID) :- site_iid(S, IID), ID = IID + {base}, inst(ID).
        shifted(S, J) :- site_iid(S, IID), J = IID - 1.
    )
    .unwrap();
    let ss: ArrayRef = Arc::new(UInt64Array::from(vec![1u64, 2, 3, 4, 5]));
    let iids: ArrayRef = Arc::new(Int64Array::from(vec![
        Some(0),
        Some(5),
        Some(-1),
        None,
        Some(-100),
    ]));
    let mut inputs = Inputs::new();
    inputs.columns(&site_iid, [ss, iids]);
    inputs
        .facts(&inst, facts(&[[100], [105], [99], [0]]))
        .unwrap();
    for threads in [1, 2, 4] {
        let out = engine(threads).run(&p, &inputs).await.unwrap();
        // -1 + 100 = 99 is an id; null gives no row; -100 + 100 = 0
        assert_eq!(
            set(out.get(&r.callee)),
            [vec![1, 100], vec![2, 105], vec![3, 99], vec![5, 0]].into()
        );
        let mut got = out.datums(&p, &shifted).unwrap();
        got.sort_by_key(|r| format!("{r:?}"));
        let want = [
            [Datum::U64(1), Datum::I64(-1)],
            [Datum::U64(2), Datum::I64(4)],
            [Datum::U64(3), Datum::I64(-2)],
            [Datum::U64(4), Datum::Null],
            [Datum::U64(5), Datum::I64(-101)],
        ];
        let mut want = want.to_vec();
        want.sort_by_key(|r| format!("{r:?}"));
        assert_eq!(got, want);
        let q = out.why(&p, &r.callee, [3u64, 99]).unwrap().render(&p);
        assert!(
            q.contains("ID = IID + 100 = -1 + 100 = 99  [computed]"),
            "{q}"
        );
    }
}

#[test]
fn refused_when_added() {
    // a bit operator on a float
    let mut p = Program::new();
    let fl = p.input_typed("fl", [Type::U64, Type::F64]);
    let d = p.derived::<2>("d");
    let (x, f, t) = (p.var("X"), p.var("F"), p.var("T"));
    let e = p
        .rule(
            d.at([x, t]),
            [fl.at([x, f]).into(), compute(t, Expr::from(f) & 1u64)],
        )
        .unwrap_err();
    assert!(e.to_string().contains("bit operator"), "{e}");
    // a float into an unsigned head column
    let e = p
        .rule(
            d.at([x, t]),
            [fl.at([x, f]).into(), compute(t, Expr::from(f) + 1u64)],
        )
        .unwrap_err();
    assert!(e.to_string().contains("float"), "{e}");
    // operands bound by nothing: each needs the other
    let mut p = Program::new();
    let a = p.input::<1>("a");
    let d = p.derived::<1>("d");
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    let e = p
        .rule(
            d.at([x]),
            [
                a.at([x]).into(),
                compute(y, Expr::from(z) + 1u64),
                compute(z, Expr::from(y) + 1u64),
            ],
        )
        .unwrap_err();
    assert!(e.to_string().contains("bound by no positive atom"), "{e}");
    // an expression in a condition over a string
    let mut p = Program::new();
    let s = p.input_typed("s", [Type::Str]);
    let d = p.derived_typed("d", [Type::Str]);
    let x = p.var("X");
    let e = p
        .rule(
            d.at([x]),
            [s.at([x]).into(), ne(Expr::from(x) + 1u64, Term::Const(0))],
        )
        .unwrap_err();
    assert!(e.to_string().contains("str"), "{e}");
}