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

//! A body atom whose own variable only the head reads is joined first for its shared
//! columns alone and joined whole at the end. When what is checked after the join steps (an
//! external asked last, a condition or a negation on what it answers) leaves no row, the
//! rule finds nothing: the head is never short of a variable. Each rule's facts against a
//! plain loop over the same rows, at 1, 2 and 4 threads, with the why kept and without, in
//! plain and in recursive rules, and through a continued run.

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

use kleene_datalog::{
    Engine, External, Facts, Inputs, Output, Program, Rel, RelId, Result, Term, Value, lt,
};
use kleene_sparse::{CpuBackend, CpuDevice};

type E = Engine<CpuBackend>;
type Set = BTreeSet<Vec<u64>>;

/// `(y, z)`: asked with `y` bound, it answers `z = y % 4` where `y % 3 != 0` (`all`), or
/// never (not `all`).
#[derive(Debug)]
struct Look {
    all: bool,
}

fn look(all: bool, y: u64) -> Option<u64> {
    (all && !y.is_multiple_of(3)).then_some(y % 4)
}

impl External for Look {
    fn arity(&self) -> usize {
        2
    }
    fn can(&self, bound: u64) -> bool {
        bound & 1 != 0
    }
    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> Result<()> {
        for (k, &y) in keys[0].iter().enumerate().take(n) {
            if let Some(z) = look(self.all, y)
                && (bound & 2 == 0 || keys[1][k] == z)
            {
                out(k, &[y, z]);
            }
        }
        Ok(())
    }
}

/// The input rows.
struct Rows {
    a: Vec<(u64, u64)>,
    b: Vec<(u64, u64)>,
    c: Vec<(u64, u64)>,
    n: Vec<u64>,
}

fn rows_of(extra: bool) -> Rows {
    let mut a: Vec<(u64, u64)> = (0..30u64).map(|x| (x, (x * 7 + 3) % 30)).collect();
    a.extend((0..30u64).step_by(4).map(|x| (x, (x * 11 + 1) % 30)));
    if extra {
        a.extend([(1, 29), (29, 2), (5, 17)]);
    }
    let b = (0..30u64).map(|y| (y, (y * 7 + 1) % 30)).collect();
    let c = (0..30u64)
        .flat_map(|x| [(x, 100 + x % 7), (x, 200 + x % 5)])
        .collect();
    let n = vec![1];
    Rows { a, b, c, n }
}

/// What the extra rows of [`rows_of`] add to `a`.
fn extra_a() -> Vec<(u64, u64)> {
    vec![(1, 29), (29, 2), (5, 17)]
}

struct Prog {
    p: Program,
    a: Rel<2>,
    b: Rel<2>,
    c: Rel<2>,
    n: Rel<1>,
    ext: Rel<2>,
    nil: Rel<2>,
    out: Vec<(&'static str, RelId)>,
}

fn program() -> Prog {
    let mut p = Program::new();
    let a = p.input::<2>("a");
    let b = p.input::<2>("b");
    let c = p.input::<2>("c");
    let n = p.input::<1>("n");
    let ext = p.external::<2>("ext");
    let nil = p.external::<2>("nil");
    let h1 = p.derived::<2>("h1");
    let h2 = p.derived::<2>("h2");
    let h3 = p.derived::<4>("h3");
    let h4 = p.derived::<1>("h4");
    let r1 = p.derived::<2>("r1");
    let r2 = p.derived::<2>("r2");
    let r3 = p.derived::<2>("r3");
    let [x, y, w, z, e] = ["X", "Y", "W", "Z", "E"].map(|v| p.var(v));
    let k = |v: u32| Term::Const(v as Value);
    // the atom first; an external that never answers leaves no row
    p.rule(h1.at([x, e]), [c.at([x, e]), a.at([x, y]), nil.at([y, z])])
        .unwrap();
    // in the middle; a condition on what the external answers
    p.rule(
        h2.at([x, e]),
        [
            a.at([x, y]).into(),
            c.at([x, e]).into(),
            b.at([y, w]).into(),
            ext.at([w, z]).into(),
            lt(z, k(1)),
        ],
    )
    .unwrap();
    // last; a constant in the head and the variable named twice; a negation on the answer
    p.rule(
        h3.atom([k(7), x.into(), e.into(), e.into()]),
        [
            a.at([x, y]).into(),
            b.at([y, w]).into(),
            ext.at([w, z]).into(),
            !n.at([z]),
            c.at([x, e]).into(),
        ],
    )
    .unwrap();
    // the head holds that variable alone
    p.rule(
        h4.at([e]),
        [
            a.at([x, y]).into(),
            ext.at([y, z]).into(),
            c.at([x, e]).into(),
            lt(z, k(2)),
        ],
    )
    .unwrap();
    // recursive: a condition on the answer
    p.rule(r1.at([x, y]), [a.at([x, y])]).unwrap();
    p.rule(
        r1.at([x, e]),
        [
            r1.at([x, y]).into(),
            b.at([y, w]).into(),
            c.at([y, e]).into(),
            ext.at([w, z]).into(),
            lt(z, k(2)),
        ],
    )
    .unwrap();
    // recursive: an external that never answers
    p.rule(r2.at([x, y]), [a.at([x, y])]).unwrap();
    p.rule(r2.at([x, e]), [r2.at([x, y]), c.at([y, e]), nil.at([y, z])])
        .unwrap();
    // recursive: a negation on the answer, the atom first
    p.rule(r3.at([x, y]), [a.at([x, y])]).unwrap();
    p.rule(
        r3.at([x, e]),
        [
            c.at([y, e]).into(),
            r3.at([x, y]).into(),
            b.at([y, w]).into(),
            ext.at([w, z]).into(),
            !n.at([z]),
        ],
    )
    .unwrap();
    let out = vec![
        ("h1", h1.id()),
        ("h2", h2.id()),
        ("h3", h3.id()),
        ("h4", h4.id()),
        ("r1", r1.id()),
        ("r2", r2.id()),
        ("r3", r3.id()),
    ];
    Prog {
        p,
        a,
        b,
        c,
        n,
        ext,
        nil,
        out,
    }
}

fn pairs(e: &[(u64, u64)]) -> Facts {
    Facts::from_rows(2, e.iter().map(|&(a, b)| vec![a, b])).unwrap()
}

fn inputs(g: &Prog, r: &Rows) -> Inputs {
    let mut ins = Inputs::new();
    ins.facts(&g.a, pairs(&r.a)).unwrap();
    ins.facts(&g.b, pairs(&r.b)).unwrap();
    ins.facts(&g.c, pairs(&r.c)).unwrap();
    ins.facts(
        &g.n,
        Facts::from_rows(1, r.n.iter().map(|&v| vec![v])).unwrap(),
    )
    .unwrap();
    ins.external(&g.ext, Arc::new(Look { all: true })).unwrap();
    ins.external(&g.nil, Arc::new(Look { all: false })).unwrap();
    ins
}

/// The facts of every derived relation, by plain loops over the same rows.
fn reference(r: &Rows) -> Vec<Set> {
    let ext = |y: u64| look(true, y);
    let cs = |x: u64| r.c.iter().filter(move |c| c.0 == x).map(|c| c.1);
    let mut h2 = Set::new();
    let mut h3 = Set::new();
    let mut h4 = Set::new();
    for &(x, y) in &r.a {
        for &(_, w) in r.b.iter().filter(|b| b.0 == y) {
            if let Some(z) = ext(w) {
                for e in cs(x) {
                    if z < 1 {
                        h2.insert(vec![x, e]);
                    }
                    if !r.n.contains(&z) {
                        h3.insert(vec![7, x, e, e]);
                    }
                }
            }
        }
        if let Some(z) = ext(y)
            && z < 2
        {
            h4.extend(cs(x).map(|e| vec![e]));
        }
    }
    // the recursions to a fixed point
    let grow = |step: &dyn Fn(u64, u64) -> Vec<u64>| {
        let mut s: Set = r.a.iter().map(|&(x, y)| vec![x, y]).collect();
        loop {
            let mut more = Vec::new();
            for t in &s {
                for e in step(t[0], t[1]) {
                    more.push(vec![t[0], e]);
                }
            }
            let n = s.len();
            s.extend(more);
            if s.len() == n {
                return s;
            }
        }
    };
    let via = |y: u64, keep: &dyn Fn(u64) -> bool| -> Vec<u64> {
        let ok =
            r.b.iter()
                .filter(|b| b.0 == y)
                .any(|b| ext(b.1).is_some_and(keep));
        if ok { cs(y).collect() } else { Vec::new() }
    };
    let r1 = grow(&|_, y| via(y, &|z| z < 2));
    let r2 = grow(&|_, _| Vec::new());
    let r3 = grow(&|_, y| via(y, &|z| !r.n.contains(&z)));
    vec![Set::new(), h2, h3, h4, r1, r2, r3]
}

fn got(out: &Output, rel: RelId) -> Set {
    out.get_id(rel)
        .map(|f| f.rows().collect())
        .unwrap_or_default()
}

fn check(g: &Prog, out: &Output, want: &[Set], explain: bool, what: &str) {
    for ((name, rel), w) in g.out.iter().zip(want) {
        let have = got(out, *rel);
        assert_eq!(&have, w, "{name} ({what})");
        if explain {
            for t in &have {
                assert!(
                    out.why_id(&g.p, *rel, t).is_some(),
                    "{name} {t:?} has a proof ({what})"
                );
            }
        }
    }
}

#[tokio::test]
async fn a_late_check_that_leaves_no_row_finds_nothing_and_the_head_lacks_no_variable() {
    let g = program();
    let r = rows_of(false);
    let want = reference(&r);
    // the shapes are not empty where the external answers
    for (i, name) in ["h2", "h3", "h4"].iter().enumerate() {
        assert!(!want[i + 1].is_empty(), "{name} finds rows");
    }
    assert!(want[4].len() > r.a.len() && want[6].len() > want[4].len());
    for threads in [1, 2, 4] {
        for explain in [false, true] {
            let engine = E::new(CpuDevice::new(threads)).explain(explain);
            let out = engine.run(&g.p, &inputs(&g, &r)).await.unwrap();
            let what = format!("{threads} threads, why {explain}");
            check(&g, &out, &want, explain, &what);
        }
    }
}

#[tokio::test]
async fn the_same_through_a_continued_run() {
    let g = program();
    let (r0, r1) = (rows_of(false), rows_of(true));
    let want = reference(&r1);
    for threads in [1, 2, 4] {
        for explain in [false, true] {
            let engine = E::new(CpuDevice::new(threads)).explain(explain);
            let first = engine.run(&g.p, &inputs(&g, &r0)).await.unwrap();
            let mut added = Inputs::new();
            added.facts(&g.a, pairs(&extra_a())).unwrap();
            let next = engine
                .continue_from(&g.p, &first, &inputs(&g, &r1), &added)
                .await
                .unwrap();
            let what = format!("continued, {threads} threads, why {explain}");
            check(&g, &next, &want, explain, &what);
        }
    }
}