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

//! A value between two ends from the other side of a join (`A in LO..HI` beside equal keys,
//! `LO <= A, A < HI` and its strict and flipped forms) runs as a sort and a search: the same
//! facts as a plain loop over the same rows, at every thread count, and the same proof of
//! every fact as the run with the sort and search off (a hash join or a cross product cut
//! by the conditions).

use std::collections::BTreeSet;

use kleene_datalog::{Engine, Facts, Inputs, Program, RelId, Value, datalog};
use kleene_sparse::{CpuBackend, CpuDevice};

/// 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
    }

    fn below(&mut self, m: u64) -> u64 {
        self.next() % m
    }
}

/// The rows: points `ksite(K, A)`, overlapping and nested pieces `piece(C, LO, HI)`, line
/// rows `line(R, F, L, A)` and scopes `scope(S, F, L, LO, HI)` (few files and lines, so
/// each key has many rows).
struct Data {
    ksite: Vec<[u64; 2]>,
    piece: Vec<[u64; 3]>,
    line: Vec<[u64; 4]>,
    scope: Vec<[u64; 5]>,
}

fn data(seed: u64) -> Data {
    let mut r = Lcg(seed);
    let ksite = (0..400).map(|k| [k, r.below(1000)]).collect();
    let mut piece: Vec<[u64; 3]> = Vec::new();
    for c in 0..150 {
        let lo = r.below(1000);
        // empty, one wide, nested inside the one before, plain
        let hi = match c % 4 {
            0 => lo,
            1 => lo + r.below(600),
            2 if c > 0 => {
                let [_, plo, phi] = piece[c as usize - 1];
                piece.push([c, plo, phi]);
                continue;
            }
            _ => lo + 1 + r.below(60),
        };
        piece.push([c, lo, hi]);
    }
    // nested: a piece inside each of the first ten
    for i in 0..10 {
        let [_, lo, hi] = piece[i];
        piece.push([1000 + i as u64, lo + (hi - lo) / 4, lo + (hi - lo) / 2 + 1]);
    }
    let line = (0..500)
        .map(|k| [k, r.below(3), r.below(4), r.below(300)])
        .collect();
    let scope = (0..120)
        .map(|s| {
            let lo = r.below(300);
            [s, r.below(3), r.below(4), lo, lo + r.below(120)]
        })
        .collect();
    Data {
        ksite,
        piece,
        line,
        scope,
    }
}

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

/// The facts of every relation of `ids` and the rendered proof of each, and the join steps
/// run as a sort and a search.
async fn run(
    p: &Program,
    inputs: &Inputs,
    ids: &[RelId],
    threads: usize,
    on: bool,
) -> (Vec<BTreeSet<Vec<Value>>>, Vec<String>, usize) {
    let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads))
        .explain(true)
        .range_joins(on);
    let out = e.run(p, inputs).await.unwrap();
    let mut all = Vec::new();
    let mut proofs = Vec::new();
    for &id in ids {
        let f: BTreeSet<Vec<Value>> = out
            .get_id(id)
            .map(|f| f.rows().collect())
            .unwrap_or_default();
        for t in &f {
            proofs.push(out.why_id(p, id, t).expect("a proof").render(p));
        }
        all.push(f);
    }
    let n = out.report.strata.iter().map(|s| s.range_joins).sum();
    (all, proofs, n)
}

#[tokio::test]
async fn a_value_between_two_ends_joins_by_a_sort_and_a_search_like_a_loop() {
    for seed in [1, 7, 42] {
        let d = data(seed);
        let mut p = Program::new();
        let ksite = p.input::<2>("ksite");
        let piece = p.input::<3>("piece");
        let line = p.input::<4>("line");
        let scope = p.input::<5>("scope");
        // few points and few line rows: the side of the value is the smaller, joined first
        let spot = p.input::<2>("spot");
        let probe = p.input::<4>("probe");
        let r = datalog!(&mut p =>
            derived at/2, held/1, crow/2, near/1, past/2, cover/2, lrow/2.
            at(K, C) :- ksite(K, A), piece(C, LO, HI), LO <= A, A < HI.
            held(C) :- ksite(K, A), piece(C, LO, HI), A >= LO, HI > A.
            crow(R, S) :- line(R, F, L, A), scope(S, F, L, LO, HI), A in LO..HI.
            near(R) :- line(R, F, L, A), scope(S, F, L, LO, HI), LO < A, A <= HI.
            past(C, K) :- piece(C, LO, HI), ksite(K, A), HI >= A, A > LO, K != C.
            cover(K, C) :- spot(K, A), piece(C, LO, HI), LO <= A, A < HI.
            lrow(R, S) :- probe(R, F, L, A), scope(S, F, L, LO, HI), A in LO..HI.
        )
        .unwrap();
        let mut inputs = Inputs::new();
        inputs
            .facts(&ksite, facts(&d.ksite))
            .unwrap()
            .facts(&piece, facts(&d.piece))
            .unwrap()
            .facts(&line, facts(&d.line))
            .unwrap()
            .facts(&scope, facts(&d.scope))
            .unwrap()
            .facts(&spot, facts(&d.ksite[..30]))
            .unwrap()
            .facts(&probe, facts(&d.line[..40]))
            .unwrap();
        let ids = [
            r.at.id(),
            r.held.id(),
            r.crow.id(),
            r.near.id(),
            r.past.id(),
            r.cover.id(),
            r.lrow.id(),
        ];

        // the plain reference
        let mut want: Vec<BTreeSet<Vec<Value>>> = vec![BTreeSet::new(); 7];
        for (i, &[k, a]) in d.ksite.iter().enumerate() {
            for &[c, lo, hi] in &d.piece {
                if lo <= a && a < hi {
                    want[0].insert(vec![k, c]);
                    want[1].insert(vec![c]);
                    if i < 30 {
                        want[5].insert(vec![k, c]);
                    }
                }
                if lo < a && a <= hi && k != c {
                    want[4].insert(vec![c, k]);
                }
            }
        }
        for (i, &[r, f, l, a]) in d.line.iter().enumerate() {
            for &[s, sf, sl, lo, hi] in &d.scope {
                if (f, l) != (sf, sl) {
                    continue;
                }
                if lo <= a && a < hi {
                    want[2].insert(vec![r, s]);
                    if i < 40 {
                        want[6].insert(vec![r, s]);
                    }
                }
                if lo < a && a <= hi {
                    want[3].insert(vec![r]);
                }
            }
        }
        assert!(want.iter().all(|w| w.len() > 5), "every rule finds rows");

        let (off, off_proofs, n_off) = run(&p, &inputs, &ids, 1, false).await;
        assert_eq!(off, want);
        assert_eq!(n_off, 0);
        for threads in [1, 2, 8] {
            let (got, proofs, n) = run(&p, &inputs, &ids, threads, true).await;
            assert_eq!(got, want, "seed {seed}, {threads} threads");
            assert_eq!(proofs, off_proofs, "seed {seed}, {threads} threads");
            assert_eq!(n, 7, "every rule joined by a sort and a search");
        }
    }
}