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

//! Rules that read several columns of one vertex type by name, one relation per column
//! (`t.a(I, A), t.b(I, B)`), run as ONE scan of the columns side by side
//! ([`Engine::side_by_side`], on by default): the same answers and the same proofs (each atom
//! shows by its own name) as the joins, at 1, 2 and 4 threads; columns with nulls, a value
//! variable two atoms read, a column read twice, recursion and negation around a merged body,
//! and a run continued from a merged one. [`Report::side_by_side`] counts the atoms read in
//! scans.

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

use arrow_array::{ArrayRef, Float64Array, Int64Array, StringArray, UInt64Array};
use kleene_datalog::{Catalog, Engine, Facts, Inputs, Output, Program, Rel, Source, Type, datalog};
use kleene_sparse::{CpuBackend, CpuDevice};

const N: u64 = 60;

fn a(r: u64) -> u64 {
    r * 7 % 10
}
fn b(r: u64) -> u64 {
    r * 3 % 11
}

/// Vertex type `t` with rows `0..N`, its columns over ONE id array: `a`, `b` unsigned, `i`
/// signed, `f` float, `s` string (each of the last three with nulls); `u`'s column `a` over
/// another id array. (An unsigned column with nulls is refused when read today; the pass
/// leaves one out of a scan, for when such a row is left out of its relation.)
fn catalog() -> Catalog {
    let ids: ArrayRef = Arc::new(UInt64Array::from((0..N).collect::<Vec<_>>()));
    let col = |v: ArrayRef| Source::Columns(vec![ids.clone(), v]);
    let mut c = Catalog::new();
    c.label("t", Source::Columns(vec![ids.clone()]));
    c.property(
        "t",
        "a",
        col(Arc::new(UInt64Array::from(
            (0..N).map(a).collect::<Vec<_>>(),
        ))),
    );
    c.property(
        "t",
        "b",
        col(Arc::new(UInt64Array::from(
            (0..N).map(b).collect::<Vec<_>>(),
        ))),
    );
    let i: Int64Array = (0..N)
        .map(|r| (r % 5 != 0).then_some(r as i64 - 20))
        .collect();
    c.typed_property("t", "i", col(Arc::new(i)), Type::I64);
    let f: Float64Array = (0..N)
        .map(|r| (r % 7 != 0).then_some(r as f64 / 4.0))
        .collect();
    c.typed_property("t", "f", col(Arc::new(f)), Type::F64);
    let s: StringArray = (0..N)
        .map(|r| (r % 3 != 0).then(|| ["ann", "bo", "cy"][r as usize % 3]))
        .collect();
    c.typed_property("t", "s", col(Arc::new(s)), Type::Str);
    let other: ArrayRef = Arc::new(UInt64Array::from((0..N).collect::<Vec<_>>()));
    c.label("u", Source::Columns(vec![other.clone()]));
    c.property(
        "u",
        "a",
        Source::Columns(vec![
            other,
            Arc::new(UInt64Array::from((0..N).map(b).collect::<Vec<_>>())),
        ]),
    );
    c
}

/// An edge `e` among the rows: `r -> r + 1` for r below N - 1, and `r -> r * 2 % N`.
fn edges(extra: &[(u64, u64)]) -> Facts {
    let mut rows: Vec<[u64; 2]> = (0..N - 1).map(|r| [r, r + 1]).collect();
    rows.extend((0..N).map(|r| [r, r * 2 % N]));
    rows.extend(extra.iter().map(|&(x, y)| [x, y]));
    Facts::from_rows(2, rows).unwrap()
}

struct Rules {
    p: Program,
    e: Rel<2>,
    out: Vec<(String, kleene_datalog::RelId, usize)>,
}

fn rules(cat: &Catalog) -> Rules {
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let wide = p.derived_typed(
        "wide",
        [Type::U64, Type::U64, Type::U64, Type::I64, Type::F64],
    );
    let r = datalog!(&mut p =>
        input ta/2 from cat "t.a", tb/2 from cat "t.b", ti/2 from cat "t.i".
        input tf/2 from cat "t.f", ts/2 from cat "t.s", ua/2 from cat "u.a".
        derived filtered/2, strings/2, same/2, twice/3, other/3.
        derived start/1, reach/1, outside/1.
        wide(I, A, B, X, F) :- ta(I, A), tb(I, B), ti(I, X), tf(I, F).
        filtered(I, B) :- ta(I, A), tb(I, B), A == 7.
        strings(I, A) :- ta(I, A), ts(I, _S), tb(I, _B).
        same(I, X) :- ta(I, X), tb(I, X).
        twice(I, X, Y) :- ta(I, X), ta(I, Y), tb(I, Y).
        other(I, A, B) :- ta(I, A), ua(I, B).
        start(I) :- ta(I, A), tb(I, B), A == 3.
        reach(I) :- start(I).
        reach(K) :- reach(J), e(J, K), ta(K, A), tb(K, B), A < B.
        outside(I) :- ta(I, A), tb(I, B), A > B, !reach(I).
    )
    .unwrap();
    let out = vec![
        ("wide".to_string(), wide.id(), 5),
        ("filtered".to_string(), r.filtered.id(), 2),
        ("strings".to_string(), r.strings.id(), 2),
        ("same".to_string(), r.same.id(), 2),
        ("twice".to_string(), r.twice.id(), 3),
        ("other".to_string(), r.other.id(), 3),
        ("start".to_string(), r.start.id(), 1),
        ("reach".to_string(), r.reach.id(), 1),
        ("outside".to_string(), r.outside.id(), 1),
    ];
    Rules { p, e, out }
}

fn inputs(rules: &Rules, cat: &Catalog, extra: &[(u64, u64)]) -> Inputs {
    let mut ins = Inputs::new();
    ins.facts(&rules.e, edges(extra)).unwrap();
    ins.bind(&rules.p, cat).unwrap();
    ins
}

/// Every derived row of each relation, with its proof.
type Seen = Vec<(String, BTreeSet<Vec<u64>>, Vec<String>)>;

fn seen(rules: &Rules, out: &Output) -> Seen {
    rules
        .out
        .iter()
        .map(|(name, rel, _)| {
            let rows: BTreeSet<Vec<u64>> = out.get_id(*rel).unwrap().rows().collect();
            let proofs = rows
                .iter()
                .map(|row| format!("{:?}", out.why_id(&rules.p, *rel, row).expect("a proof")))
                .collect();
            (name.clone(), rows, proofs)
        })
        .collect()
}

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

#[tokio::test]
async fn columns_side_by_side_run_as_one_scan_with_the_same_answers_and_proofs() {
    let cat = catalog();
    let rules = rules(&cat);
    let ins = inputs(&rules, &cat, &[]);
    let mut first: Option<Seen> = None;
    for threads in [1, 2, 4] {
        let on = engine(threads, true).run(&rules.p, &ins).await.unwrap();
        let off = engine(threads, false).run(&rules.p, &ins).await.unwrap();
        // wide 4, filtered 2, strings 3, same 0 + twice 2 (a value variable twice, a
        // column twice: one pair each), start 2, reach 2, outside 2; not u's other id
        // array
        assert_eq!(
            on.report.side_by_side,
            4 + 2 + 3 + 2 + 2 + 2 + 2,
            "{threads} threads"
        );
        assert_eq!(off.report.side_by_side, 0);
        let (s_on, s_off) = (seen(&rules, &on), seen(&rules, &off));
        assert_eq!(s_on, s_off, "{threads} threads");
        match &first {
            Some(f) => assert_eq!(&s_on, f, "{threads} threads"),
            None => first = Some(s_on),
        }
    }
    // the plain loop, for the unsigned ones
    let rows = |name: &str| {
        first
            .as_ref()
            .unwrap()
            .iter()
            .find(|s| s.0 == name)
            .unwrap()
            .1
            .clone()
    };
    let want: BTreeSet<Vec<u64>> = (0..N)
        .filter(|&r| a(r) == 7)
        .map(|r| vec![r, b(r)])
        .collect();
    assert_eq!(rows("filtered"), want);
    let want: BTreeSet<Vec<u64>> = (0..N)
        .filter(|&r| a(r) == b(r))
        .map(|r| vec![r, a(r)])
        .collect();
    assert_eq!(rows("same"), want);
    // a null string is a value: every row of t
    assert_eq!(rows("strings").len(), N as usize);
    assert!(!rows("reach").is_empty() && !rows("outside").is_empty());
}

#[tokio::test]
async fn a_run_continued_from_a_merged_run_equals_a_run_from_scratch() {
    let cat = catalog();
    let rules = rules(&cat);
    let ins = inputs(&rules, &cat, &[]);
    let extra = [(5, 41), (41, 13)];
    let ins2 = inputs(&rules, &cat, &extra);
    let mut added = Inputs::new();
    added
        .facts(
            &rules.e,
            Facts::from_rows(2, extra.iter().map(|&(x, y)| [x, y])).unwrap(),
        )
        .unwrap();
    let e = engine(2, true);
    let prev = e.run(&rules.p, &ins).await.unwrap();
    let next = e
        .continue_from(&rules.p, &prev, &ins2, &added)
        .await
        .unwrap();
    let scratch = engine(2, false).run(&rules.p, &ins2).await.unwrap();
    assert_eq!(seen(&rules, &next), seen(&rules, &scratch));
}

/// A rule of the next row by a key (`min(B2) by (I)`, `A < B2`) whose two sides each read two
/// columns of `t` side by side: with both knobs (`side_by_side`, `next_rows`) on and off, with
/// and without proofs, the rows of a plain loop and, with proofs, the same proofs. With proofs
/// kept the plan is not rewritten for the next row, so the merged body (two atoms) is what
/// lets it run as one; without, the next-row rewrite runs first and the columns merge in the
/// rules it leaves.
#[tokio::test]
async fn the_next_row_over_columns_side_by_side() {
    let cat = catalog();
    let mut p = Program::new();
    let r = datalog!(&mut p =>
        input ta/2 from cat "t.a", tb/2 from cat "t.b".
        derived after/2.
        after(I, B2) :- min(B2) by (I): ta(I, A), tb(I, _B), ta(J, _A2), tb(J, B2), A < B2.
    )
    .unwrap();
    let mut ins = Inputs::new();
    ins.bind(&p, &cat).unwrap();
    let want: BTreeSet<Vec<u64>> = (0..N)
        .filter_map(|i| {
            (0..N)
                .map(b)
                .filter(|&y| a(i) < y)
                .min()
                .map(|y| vec![i, y])
        })
        .collect();
    assert!(want.len() > N as usize / 2);
    let mut proofs: Option<Vec<String>> = None;
    for threads in [1, 2, 4] {
        for explain in [false, true] {
            for side in [true, false] {
                for next in [true, false] {
                    let e = Engine::<CpuBackend>::new(CpuDevice::new(threads))
                        .explain(explain)
                        .side_by_side(side)
                        .next_rows(next);
                    let out = e.run(&p, &ins).await.unwrap();
                    let at =
                        format!("{threads} threads, proofs {explain}, side {side}, next {next}");
                    let got: BTreeSet<Vec<u64>> =
                        out.get_id(r.after.id()).unwrap().rows().collect();
                    assert_eq!(got, want, "{at}");
                    let ran: usize = out.report.strata.iter().map(|s| s.next_rows).sum();
                    match (side, explain) {
                        (true, true) => assert_eq!(out.report.side_by_side, 4, "{at}"),
                        (true, false) => assert!(out.report.side_by_side >= 2, "{at}"),
                        (false, _) => assert_eq!(out.report.side_by_side, 0, "{at}"),
                    }
                    // with proofs only the merged body has the next row's shape
                    let shaped = next && (!explain || side);
                    assert_eq!(ran, usize::from(shaped), "{at}");
                    if explain {
                        let ps: Vec<String> = got
                            .iter()
                            .map(|row| {
                                format!("{:?}", out.why_id(&p, r.after.id(), row).expect("a proof"))
                            })
                            .collect();
                        match &proofs {
                            Some(f) => assert_eq!(&ps, f, "{at}"),
                            None => proofs = Some(ps),
                        }
                    }
                }
            }
        }
    }
}