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/rule_text.rs

//! The rule text of `datalog!` for what the core already has, each form against its builder
//! twin (the same rules) and a plain loop over the same rows: constants coded for the place
//! they meet, string tests, value reductions, null tests and the bag count.

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

use arrow_array::{Array, ArrayRef, BooleanArray, Float64Array, Int64Array, StringArray};
use kleene_datalog::{
    Aggregate, Constant, Datum, Engine, Facts, Inputs, Program, Reduce, Rel, Term, TextOp, Type,
    contains, datalog, ends_with, eq, ge, gt, is_not_null, is_null, lt, starts_with, text, within,
};
use kleene_sparse::{CpuBackend, CpuDevice};

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

fn arr(a: impl Array + 'static) -> ArrayRef {
    Arc::new(a)
}

/// (name, age, score, admin): some values missing.
type Person = (&'static str, Option<i64>, Option<f64>, Option<bool>);

fn people() -> Vec<Person> {
    vec![
        ("ann", Some(34), Some(7.5), Some(true)),
        ("bo", Some(17), Some(-1.25), Some(false)),
        ("cy", None, Some(3.0), None),
        ("dee", Some(-1), None, Some(false)),
        ("eve", Some(61), Some(1.5), Some(true)),
        ("fay", Some(-7), Some(0.0), Some(true)),
        ("gus", Some(18), Some(-0.5), Some(false)),
    ]
}

/// `person(Name, Age, Score, Admin)`.
fn db() -> (Program, Inputs, Rel<4>) {
    let mut p = Program::new();
    let person = p.input_typed("person", [Type::Str, Type::I64, Type::F64, Type::Bool]);
    let ps = people();
    let mut inp = Inputs::new();
    inp.columns(
        &person,
        [
            arr(StringArray::from_iter_values(ps.iter().map(|x| x.0))),
            arr(Int64Array::from(ps.iter().map(|x| x.1).collect::<Vec<_>>())),
            arr(Float64Array::from(
                ps.iter().map(|x| x.2).collect::<Vec<_>>(),
            )),
            arr(BooleanArray::from(
                ps.iter().map(|x| x.3).collect::<Vec<_>>(),
            )),
        ],
    );
    (p, inp, person)
}

fn names(rows: Vec<[Datum; 1]>) -> BTreeSet<String> {
    rows.into_iter()
        .map(|[d]| match d {
            Datum::Str(s) => s,
            other => panic!("not a string: {other:?}"),
        })
        .collect()
}

fn want(f: impl Fn(&Person) -> bool) -> BTreeSet<String> {
    people()
        .iter()
        .filter(|x| f(x))
        .map(|x| x.0.to_string())
        .collect()
}

mod age {
    pub const OLD: i64 = 60;
}

#[tokio::test]
async fn constants_are_coded_for_the_column_or_variable_they_meet() {
    let names_of = [
        "neg", "young", "high", "low", "old", "grown", "admin", "band",
    ];
    // the builder, every constant coded by hand
    let (mut b, inp, person) = db();
    let rels = names_of.map(|n| b.derived_typed(n, [Type::Str]));
    let ages = b.derived_typed("ages", [Type::I64]);
    let tag = b.derived_typed("tag", [Type::Str, Type::I64]);
    let [n, a, s, ad] = ["N", "A", "S", "B"].map(|x| b.var(x));
    let row = || person.atom([n.into(), a.into(), s.into(), ad.into()]);
    let ann = b.str("ann");
    let conds = [
        eq(a, Term::int(-1)),
        lt(a, Term::int(18)),
        ge(s, Term::float(1.5)),
        gt(Term::float(-0.5), s),
        gt(a, Term::int(age::OLD)),
        ge(a, Term::int(18)),
        eq(ad, Term::bool(true)),
        within(a, Term::int(-5), Term::int(18)),
    ];
    for (r, c) in rels.iter().zip(conds) {
        b.rule(r.at([n]), [row().into(), c]).unwrap();
    }
    b.rule(
        ages.at([a]),
        [person.atom([ann, a.into(), s.into(), ad.into()])],
    )
    .unwrap();
    b.rule(
        tag.atom([n.into(), Term::int(-1)]),
        [
            row(),
            person.atom([n.into(), a.into(), s.into(), Term::bool(false)]),
        ],
    )
    .unwrap();

    // the text: bare literals and Rust values, coded where they meet a column or variable
    let (mut m, _, person) = db();
    let [neg, young, high, low, old, grown, admin, band] =
        names_of.map(|n| m.derived_typed(n, [Type::Str]));
    let ages = m.derived_typed("ages", [Type::I64]);
    let tag = m.derived_typed("tag", [Type::Str, Type::I64]);
    // a Rust value is raw, as in the builder: a signed one is written as a `Term`
    datalog!(&mut m =>
        neg(N)   :- person(N, A, S, B), A == -1.
        young(N) :- person(N, A, S, B), A < 18.
        high(N)  :- person(N, A, S, B), S >= 1.5.
        low(N)   :- person(N, A, S, B), -0.5 > S.
        old(N)   :- person(N, A, S, B), A > {Term::int(age::OLD)}.
        grown(N) :- person(N, A, S, B), A >= 18.
        admin(N) :- person(N, A, S, B), B == true.
        band(N)  :- person(N, A, S, B), A in -5..18.
        ages(A)  :- person("ann", A, S, B).
        tag(N, -1) :- person(N, A, S, B), person(N, A, S, false).
    )
    .unwrap();
    assert_eq!(m.rules(), b.rules());

    for threads in [1, 2, 4] {
        let out = engine(threads).run(&m, &inp).await.unwrap();
        let got = |r: &Rel<1>| names(out.datums(&m, r).unwrap());
        assert_eq!(got(&neg), want(|x| x.1 == Some(-1)));
        assert_eq!(got(&young), want(|x| x.1.is_some_and(|a| a < 18)));
        assert_eq!(got(&high), want(|x| x.2.is_some_and(|s| s >= 1.5)));
        assert_eq!(got(&low), want(|x| x.2.is_some_and(|s| s < -0.5)));
        assert_eq!(got(&old), want(|x| x.1.is_some_and(|a| a > 60)));
        assert_eq!(got(&grown), want(|x| x.1.is_some_and(|a| a >= 18)));
        assert_eq!(got(&admin), want(|x| x.3 == Some(true)));
        assert_eq!(
            got(&band),
            want(|x| x.1.is_some_and(|a| (-5..18).contains(&a)))
        );
        assert_eq!(out.datums(&m, &ages).unwrap(), vec![[Datum::I64(34)]]);
        let tags: BTreeSet<(String, i64)> = out
            .datums(&m, &tag)
            .unwrap()
            .into_iter()
            .map(|[n, t]| match (n, t) {
                (Datum::Str(n), Datum::I64(t)) => (n, t),
                other => panic!("{other:?}"),
            })
            .collect();
        // a null joins nothing: the second atom meets the first on every column
        let want_tags: BTreeSet<(String, i64)> =
            want(|x| x.3 == Some(false) && x.1.is_some() && x.2.is_some())
                .into_iter()
                .map(|n| (n, -1))
                .collect();
        assert_eq!(tags, want_tags);
    }
}

#[test]
fn a_constant_that_does_not_fit_its_place_is_refused_by_name() {
    let fits = |text: &str| -> Result<(), String> {
        let (mut p, _, person) = db();
        let r = p.derived_typed("r", [Type::Str]);
        let e = p.input::<1>("e");
        let res = match text {
            "float for i64" => datalog!(&mut p => r(N) :- person(N, A, S, B), A == 1.5.).map(drop),
            "negative for u64" => datalog!(&mut p => r(N) :- person(N, A, S, B), e(-1).).map(drop),
            "string for f64" => datalog!(&mut p => r(N) :- person(N, A, S, B), S < "x".).map(drop),
            "number for str" => {
                datalog!(&mut p => r(N) :- person(7, A, S, B), person(N, A, S, B).).map(drop)
            }
            "number for bool" => datalog!(&mut p => r(N) :- person(N, A, S, 1).).map(drop),
            _ => unreachable!(),
        };
        let _ = (r, e);
        res.map_err(|e| e.to_string())
    };
    assert_eq!(
        fits("float for i64").unwrap_err(),
        "program: a float compared with an i64 value"
    );
    assert_eq!(
        fits("negative for u64").unwrap_err(),
        "program: a negative integer compared with a u64 value"
    );
    assert!(
        fits("string for f64")
            .unwrap_err()
            .contains("a string compared with an f64")
    );
    assert!(
        fits("number for str")
            .unwrap_err()
            .contains("an unsigned integer compared with a str")
    );
    assert!(
        fits("number for bool")
            .unwrap_err()
            .contains("compared with a bool")
    );
    // the builder's twin refuses the same
    let mut p = Program::new();
    assert!(p.constant(&Constant::Float(1.5), Type::I64).is_err());
}

/// Function names, some missing, some alike.
fn func_names() -> Vec<Option<&'static str>> {
    vec![
        Some("parse_expr"),
        Some("parse"),
        Some("lex_expr"),
        None,
        Some("expr"),
        Some(""),
        Some("reparse"),
        Some("lexer"),
    ]
}

/// `func(Id, Name)`.
fn funcs() -> (Program, Inputs, Rel<2>) {
    let mut p = Program::new();
    let func = p.input_typed("func", [Type::U64, Type::Str]);
    let ns = func_names();
    let mut inp = Inputs::new();
    inp.columns(
        &func,
        [
            arr(arrow_array::UInt64Array::from_iter_values(
                0..ns.len() as u64,
            )),
            arr(StringArray::from(ns)),
        ],
    );
    (p, inp, func)
}

fn ids(rows: Vec<[Datum; 1]>) -> BTreeSet<u64> {
    rows.into_iter()
        .map(|[d]| match d {
            Datum::U64(x) => x,
            other => panic!("not an id: {other:?}"),
        })
        .collect()
}

fn want_ids(f: impl Fn(&str) -> bool) -> BTreeSet<u64> {
    func_names()
        .iter()
        .enumerate()
        .filter(|(_, n)| n.is_some_and(&f))
        .map(|(i, _)| i as u64)
        .collect()
}

/// The GQL twin, which runs the same core test (`Cond::Text`): kleene-gql
/// tests/typed.rs `text_tests_match_a_plain_loop_in_three_valued_logic`.
#[tokio::test]
async fn string_tests_in_text_equal_the_builder_and_a_plain_loop() {
    // the builder
    let (mut b, inp, func) = funcs();
    let [pre, suf, mid, both] =
        ["pre", "suf", "mid", "both"].map(|n| b.derived_typed(n, [Type::U64]));
    let (i, n) = (b.var("I"), b.var("N"));
    let (parse, expr, ex) = (b.str("parse"), b.str("expr"), b.str("ex"));
    b.rule(pre.at([i]), [func.at([i, n]).into(), starts_with(n, parse)])
        .unwrap();
    b.rule(suf.at([i]), [func.at([i, n]).into(), ends_with(n, expr)])
        .unwrap();
    b.rule(mid.at([i]), [func.at([i, n]).into(), contains(n, ex)])
        .unwrap();
    b.rule(
        both.at([i]),
        [
            func.at([i, n]).into(),
            text(n, TextOp::StartsWith, parse),
            text(n, TextOp::EndsWith, expr),
        ],
    )
    .unwrap();

    // the text, on the same relations; a pattern is a string literal or a string `Term`
    let (mut m, _, func) = funcs();
    let [pre, suf, mid, both] =
        ["pre", "suf", "mid", "both"].map(|n| m.derived_typed(n, [Type::U64]));
    let _ = m.str("parse");
    let tail = m.str("expr");
    let ex = m.str("ex");
    datalog!(&mut m =>
        pre(I)  :- func(I, N), N starts with "parse".
        suf(I)  :- func(I, N), N ends with {tail}.
        mid(I)  :- func(I, N), N contains ex.
        both(I) :- func(I, N), N starts with "parse", N ends with "expr".
    )
    .unwrap();
    assert_eq!(b.rules(), m.rules());

    for threads in [1, 2, 4] {
        let out = engine(threads).run(&m, &inp).await.unwrap();
        let got = |r: &Rel<1>| ids(out.datums(&m, r).unwrap());
        assert_eq!(got(&pre), want_ids(|s| s.starts_with("parse")));
        assert_eq!(got(&suf), want_ids(|s| s.ends_with("expr")));
        assert_eq!(got(&mid), want_ids(|s| s.contains("ex")));
        assert_eq!(
            got(&both),
            want_ids(|s| s.starts_with("parse") && s.ends_with("expr"))
        );
        let ob = engine(threads).run(&b, &inp).await.unwrap();
        for r in [pre, suf, mid, both] {
            assert_eq!(got(&r), ids(ob.datums(&b, &r).unwrap()));
        }
        // a row's proof shows the test
        let why = out.why(&m, &both, [0u64]).expect("a proof").render(&m);
        assert!(
            why.contains("starts with") && why.contains("ends with"),
            "{why}"
        );
    }
}

#[test]
fn a_string_test_of_a_number_or_by_a_number_is_refused() {
    let (mut p, _, func) = funcs();
    let r = p.derived_typed("r", [Type::U64]);
    // the tested value is a string variable
    let e = datalog!(&mut p => r(I) :- func(I, N), I starts with "a".).unwrap_err();
    assert!(e.to_string().contains("tests a string variable"), "{e}");
    // the pattern is a string: a number literal meets a str place
    let e = datalog!(&mut p => r(I) :- func(I, N), N contains 7.).unwrap_err();
    assert!(
        e.to_string()
            .contains("an unsigned integer compared with a str value"),
        "{e}"
    );
    let _ = (r, func);
}

/// (who, amount): repeats, a null, a group of only a null.
fn sales() -> Vec<(&'static str, Option<i64>)> {
    vec![
        ("ann", Some(5)),
        ("ann", Some(5)),
        ("ann", Some(-2)),
        ("ann", None),
        ("bo", Some(7)),
        ("bo", Some(1)),
        ("cy", None),
        ("dee", Some(-4)),
    ]
}

/// `sale(Who, X)`.
fn sale_db() -> (Program, Inputs, Rel<2>) {
    let mut p = Program::new();
    let sale = p.input_typed("sale", [Type::Str, Type::I64]);
    let ss = sales();
    let mut inp = Inputs::new();
    inp.columns(
        &sale,
        [
            arr(StringArray::from_iter_values(ss.iter().map(|x| x.0))),
            arr(Int64Array::from(ss.iter().map(|x| x.1).collect::<Vec<_>>())),
        ],
    );
    (p, inp, sale)
}

/// The value reductions of the text are the builder's `Aggregate::many`, the core path GQL's
/// `RETURN count(..), sum(..), avg(..), min(..), max(..)` takes (kleene-gql tests/cypher.rs
/// `typed_edge_properties_on_a_single_edge`); `X is null` is `is_null` (kleene-gql
/// tests/typed.rs `is_null_counts_a_missing_property_as_null`).
#[tokio::test]
async fn value_reductions_and_null_tests_in_text_equal_the_builder_and_a_plain_loop() {
    let stats_types = [
        Type::Str,
        Type::U64,
        Type::U64,
        Type::I64,
        Type::F64,
        Type::I64,
        Type::I64,
    ];
    // the builder
    let (mut b, inp, sale) = sale_db();
    let tot = b.derived_typed("tot", [Type::Str, Type::I64]);
    let stats = b.derived_typed("stats", stats_types);
    let unk = b.derived_typed("unk", [Type::Str]);
    let known = b.derived_typed("known", [Type::Str]);
    let [w, s, x, n, c, a, l, h] = ["W", "S", "X", "N", "C", "A", "L", "H"].map(|v| b.var(v));
    b.aggregate(
        tot.at([w, s]),
        Aggregate::many([w], [Reduce::sum(x, s)]),
        [sale.at([w, x])],
    )
    .unwrap();
    b.aggregate(
        stats.at([w, n, c, s, a, l, h]),
        Aggregate::many(
            [w],
            [
                Reduce::count(n),
                Reduce::count_of([x], c).distinct(),
                Reduce::sum(x, s),
                Reduce::avg(x, a),
                Reduce::min(x, l),
                Reduce::max(x, h),
            ],
        ),
        [sale.at([w, x])],
    )
    .unwrap();
    b.rule(unk.at([w]), [sale.at([w, x]).into(), is_null(x)])
        .unwrap();
    b.rule(known.at([w]), [sale.at([w, x]).into(), is_not_null(x)])
        .unwrap();

    // the text
    let (mut m, _, sale) = sale_db();
    let tot = m.derived_typed("tot", [Type::Str, Type::I64]);
    let stats = m.derived_typed("stats", stats_types);
    let unk = m.derived_typed("unk", [Type::Str]);
    let known = m.derived_typed("known", [Type::Str]);
    datalog!(&mut m =>
        tot(W, S) :- S = sum(X) by (W): sale(W, X).
        stats(W, N, C, S, A, L, H) :-
            N = count(), C = count(X), S = sum(X), A = avg(X), L = least(X), H = greatest(X)
            by (W): sale(W, X).
        unk(W) :- sale(W, X), X is null.
        known(W) :- sale(W, X), X is not null.
    )
    .unwrap();
    assert_eq!(b.rules(), m.rules());

    // a plain loop over the distinct bindings (W, X)
    let bindings: BTreeSet<(&str, Option<i64>)> = sales().into_iter().collect();
    let whos: BTreeSet<&str> = bindings.iter().map(|b| b.0).collect();
    let vals = |who: &str| -> Vec<i64> {
        bindings
            .iter()
            .filter(|b| b.0 == who)
            .filter_map(|b| b.1)
            .collect()
    };
    let opt_i = |v: Option<i64>| v.map_or(Datum::Null, Datum::I64);
    let want_tot: BTreeSet<String> = whos
        .iter()
        .map(|&who| {
            let v = vals(who);
            let sum = (!v.is_empty()).then(|| v.iter().sum());
            format!("{:?}", vec![Datum::Str(who.into()), opt_i(sum)])
        })
        .collect();
    let want_stats: BTreeSet<String> = whos
        .iter()
        .map(|&who| {
            let v = vals(who);
            let all = bindings.iter().filter(|b| b.0 == who).count() as u64;
            let some = !v.is_empty();
            let row = vec![
                Datum::Str(who.into()),
                Datum::U64(all),
                Datum::U64(v.len() as u64),
                opt_i(some.then(|| v.iter().sum())),
                if some {
                    Datum::F64(v.iter().sum::<i64>() as f64 / v.len() as f64)
                } else {
                    Datum::Null
                },
                opt_i(v.iter().copied().min()),
                opt_i(v.iter().copied().max()),
            ];
            format!("{row:?}")
        })
        .collect();
    for threads in [1, 2, 4] {
        let out = engine(threads).run(&m, &inp).await.unwrap();
        let rows = |r: Vec<Vec<Datum>>| -> BTreeSet<String> {
            r.into_iter().map(|x| format!("{x:?}")).collect()
        };
        let got_tot = rows(
            out.datums(&m, &tot)
                .unwrap()
                .into_iter()
                .map(|r| r.to_vec())
                .collect(),
        );
        assert_eq!(got_tot, want_tot);
        let got_stats = rows(
            out.datums(&m, &stats)
                .unwrap()
                .into_iter()
                .map(|r| r.to_vec())
                .collect(),
        );
        assert_eq!(got_stats, want_stats);
        assert_eq!(
            names(out.datums(&m, &unk).unwrap()),
            sales()
                .iter()
                .filter(|x| x.1.is_none())
                .map(|x| x.0.to_string())
                .collect()
        );
        assert_eq!(
            names(out.datums(&m, &known).unwrap()),
            sales()
                .iter()
                .filter(|x| x.1.is_some())
                .map(|x| x.0.to_string())
                .collect()
        );
    }
}

/// The bag count of the text is `Program::count_rule` on a `counted` relation, the core
/// path GQL's bag rows take (kleene-gql tests/bags.rs `fixed_patterns_return_a_row_per_match`).
#[tokio::test]
async fn the_bag_count_in_text_equals_count_rule_and_a_plain_loop() {
    let edges: Vec<[u64; 2]> = vec![[0, 1], [0, 2], [1, 3], [2, 3], [3, 0], [1, 1], [0, 3]];
    let facts = || Facts::from_rows(2, edges.iter().map(|e| e.to_vec())).unwrap();

    // the builder
    let mut b = Program::new();
    let e = b.input::<2>("e");
    let two = b.derived_counted::<3>("two");
    let [ba, bc, bn, bb] = ["A", "C", "N", "B"].map(|v| b.var(v));
    b.count_rule(two.at([ba, bc, bn]), [e.at([ba, bb]), e.at([bb, bc])])
        .unwrap();

    // the text, a new program with its declarations
    let (m, r) = datalog! {
        input e/2.
        counted two/3.
        two(A, C, N) :- N = count() by (A, C): e(A, B), e(B, C).
    }
    .unwrap();
    assert_eq!(b.rules(), m.rules());
    assert!(m.is_counted(r.two.id()));

    let mut want: BTreeSet<Vec<u64>> = BTreeSet::new();
    for x in &edges {
        for y in &edges {
            if x[1] == y[0] {
                let n = edges
                    .iter()
                    .filter(|z| z[0] == x[0])
                    .filter(|z| edges.contains(&[z[1], y[1]]))
                    .count() as u64;
                want.insert(vec![x[0], y[1], n]);
            }
        }
    }
    for threads in [1, 2, 4] {
        let mut inp = Inputs::new();
        inp.facts(&r.e, facts()).unwrap();
        let out = engine(threads).run(&m, &inp).await.unwrap();
        let got: BTreeSet<Vec<u64>> = out.get(&r.two).unwrap().rows().collect();
        assert_eq!(got, want);
    }
}