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

//! The next row by a key (`next(A, B) :- min(B) by (A): bound(A), bound(B), A < B.`, `max`
//! with `>`, more keys in `by (...)`) runs as a sort and one search per row: 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 cross product reduced per group).

use std::collections::{BTreeMap, 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 below(&mut self, m: u64) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (self.0 >> 11) % m
    }
}

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`, the rendered proof of each, and the rules run as
/// the next row.
async fn run(
    p: &Program,
    inputs: &Inputs,
    ids: &[RelId],
    threads: usize,
    on: bool,
    explain: bool,
) -> (Vec<BTreeSet<Vec<Value>>>, Vec<String>, usize) {
    let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads))
        .explain(explain)
        .next_rows(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();
        if explain {
            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.next_rows).sum();
    (all, proofs, n)
}

#[tokio::test]
async fn the_next_row_by_a_key_is_a_sort_and_a_search_like_a_loop() {
    for seed in [3, 11, 29] {
        let mut r = Lcg(seed);
        // boundaries with repeats, sections of boundaries, boundaries with a tag (ties)
        let bound: Vec<[u64; 1]> = (0..300).map(|_| [r.below(2000)]).collect();
        let sbound: Vec<[u64; 2]> = (0..300).map(|_| [r.below(4), r.below(500)]).collect();
        let wbound: Vec<[u64; 2]> = (0..300).map(|_| [r.below(400), r.below(3)]).collect();
        let mut p = Program::new();
        let b1 = p.input::<1>("bound");
        let b2 = p.input::<2>("sbound");
        let b3 = p.input::<2>("wbound");
        let x = datalog!(&mut p =>
            derived next/2, prev/2, nexts/3, upto/2, nextw/3.
            next(A, B) :- min(B) by (A): b1(A), b1(B), A < B.
            prev(A, B) :- max(B) by (A): b1(A), b1(B), A > B.
            nexts(S, A, B) :- min(B) by (S, A): b2(S, A), b2(S, B), A < B.
            upto(A, B) :- min(B) by (A): b1(A), b1(B), B >= A.
            nextw(A, B, W) :- min(B) by (A): b1(A), b3(B, W), A < B.
        )
        .unwrap();
        let mut inputs = Inputs::new();
        inputs
            .facts(&b1, facts(&bound))
            .unwrap()
            .facts(&b2, facts(&sbound))
            .unwrap()
            .facts(&b3, facts(&wbound))
            .unwrap();
        let ids = [
            x.next.id(),
            x.prev.id(),
            x.nexts.id(),
            x.upto.id(),
            x.nextw.id(),
        ];

        // the plain reference
        let mut want: Vec<BTreeSet<Vec<Value>>> = vec![BTreeSet::new(); 5];
        let vals: BTreeSet<u64> = bound.iter().map(|r| r[0]).collect();
        for &a in &vals {
            if let Some(&b) = vals.range(a + 1..).next() {
                want[0].insert(vec![a, b]);
            }
            if let Some(&b) = vals.range(..a).next_back() {
                want[1].insert(vec![a, b]);
            }
            want[3].insert(vec![a, a]);
            // the least B past A; of equal B the least W (the head's values break ties)
            if let Some(&[b, w]) = wbound.iter().filter(|r| r[0] > a).min() {
                want[4].insert(vec![a, b, w]);
            }
        }
        let mut sections: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
        for &[s, a] in &sbound {
            sections.entry(s).or_default().insert(a);
        }
        for (&s, vs) in &sections {
            for &a in vs {
                if let Some(&b) = vs.range(a + 1..).next() {
                    want[2].insert(vec![s, a, b]);
                }
            }
        }
        assert!(want.iter().all(|w| w.len() > 50), "every rule finds rows");

        let (off, off_proofs, n_off) = run(&p, &inputs, &ids, 1, false, true).await;
        assert_eq!(off, want, "seed {seed}");
        assert_eq!(n_off, 0);
        for threads in [1, 2, 8] {
            for explain in [true, false] {
                let (got, proofs, n) = run(&p, &inputs, &ids, threads, true, explain).await;
                assert_eq!(got, want, "seed {seed}, {threads} threads");
                if explain {
                    assert_eq!(proofs, off_proofs, "seed {seed}, {threads} threads");
                }
                assert_eq!(n, 5, "every rule run as the next row");
            }
        }
    }
}