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

//! A run continued from an earlier run's facts (`Engine::continue_from`) derives what a run
//! from scratch on the new inputs derives, relation for relation, with proofs that check:
//! a reach, a closure, a recursion of joins, a count (its counts add), a negation (computed
//! again when what it negates grew, continued when only what it reads grew), the index
//! choice on.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use arrow_array::{ArrayRef, UInt64Array};
use kleene_datalog::{
    Catalog, Engine, External, Facts, How, Inputs, Output, Program, Proof, Rel, RelId, Source,
    Term, Value, lt,
};
use kleene_sparse::{CpuBackend, CpuDevice};

type E = Engine<CpuBackend>;

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

fn ones(xs: &[u32]) -> Facts {
    Facts::from_rows(1, xs.iter().map(|&x| vec![x])).unwrap()
}

/// The program: `r` reached from the seeds `s` (a reach), `tc` the closure of `e`, `p` the
/// pairs of `e` joined with themselves to a fixed point (a recursion of joins, not linear),
/// `free` the reached that are not `blocked` (a negation), `deg(X, N)` the reached
/// successors of each `X` counted.
struct Prog {
    p: Program,
    e: Rel<2>,
    s: Rel<1>,
    blocked: Rel<1>,
    out: Vec<(String, RelId)>,
}

fn program() -> Prog {
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let s = p.input::<1>("s");
    let blocked = p.input::<1>("blocked");
    let r = p.derived::<1>("r");
    let tc = p.derived::<2>("tc");
    let pp = p.derived::<2>("p");
    let free = p.derived::<1>("free");
    let deg = p.derived_counted::<2>("deg");
    let [x, y, z, n] = ["X", "Y", "Z", "N"].map(|v| p.var(v));
    p.rule(r.at([y]), [s.at([y])]).unwrap();
    p.rule(r.at([y]), [r.at([x]), e.at([x, y])]).unwrap();
    p.rule(tc.at([x, y]), [e.at([x, y])]).unwrap();
    p.rule(tc.at([x, z]), [tc.at([x, y]), e.at([y, z])])
        .unwrap();
    p.rule(pp.at([x, y]), [e.at([x, y])]).unwrap();
    p.rule(pp.at([x, z]), [pp.at([x, y]), pp.at([y, z])])
        .unwrap();
    p.rule(free.at([x]), [r.at([x]).into(), !blocked.at([x])])
        .unwrap();
    p.count_rule(deg.at([x, n]), [e.at([x, y]), r.at([y])])
        .unwrap();
    let out = [
        ("r", r.id()),
        ("tc", tc.id()),
        ("p", pp.id()),
        ("free", free.id()),
        ("deg", deg.id()),
    ]
    .map(|(n, id)| (n.to_string(), id))
    .to_vec();
    Prog {
        p,
        e,
        s,
        blocked,
        out,
    }
}

fn inputs(g: &Prog, e: &[(u32, u32)], s: &[u32], blocked: &[u32]) -> Inputs {
    let mut ins = Inputs::new();
    ins.facts(&g.e, pairs(e)).unwrap();
    ins.facts(&g.s, ones(s)).unwrap();
    ins.facts(&g.blocked, ones(blocked)).unwrap();
    ins
}

fn rows(o: &Output, rel: RelId) -> BTreeSet<Vec<u64>> {
    o.get_id(rel)
        .map(|f| f.rows().collect())
        .unwrap_or_default()
}

/// Every derived fact of `o` has a proof whose leaves are input facts of `ins` and whose
/// steps derive facts `o` holds.
fn proofs_check(g: &Prog, o: &Output, ins: &BTreeMap<RelId, BTreeSet<Vec<u64>>>) {
    fn check(g: &Prog, o: &Output, q: &Proof, ins: &BTreeMap<RelId, BTreeSet<Vec<u64>>>) {
        match &q.how {
            How::Input => assert!(ins[&q.rel].contains(&q.tuple), "{}", q.render(&g.p)),
            How::Rule { premises, .. } => {
                assert!(rows(o, q.rel).contains(&q.tuple), "{}", q.render(&g.p));
                for s in premises {
                    check(g, o, s, ins);
                }
            }
            _ => {}
        }
    }
    for (name, rel) in &g.out {
        for t in rows(o, *rel) {
            let q = o
                .why_id(&g.p, *rel, &t)
                .unwrap_or_else(|| panic!("no proof of {name}{t:?}"));
            check(g, o, &q, ins);
            assert!(!o.render(&g.p, &q).is_empty());
        }
    }
}

/// Which strata of `o` continued (by their relations' names).
fn continued(o: &Output) -> BTreeMap<String, bool> {
    o.report
        .strata
        .iter()
        .map(|s| (s.relations.join(","), s.continued))
        .collect()
}

#[tokio::test]
async fn a_continued_run_derives_what_a_run_from_scratch_derives() {
    let g = program();
    let e0 = [(0, 1), (1, 2), (2, 0), (3, 4), (5, 6)];
    let s0 = [0];
    let blocked = [2];
    for explain in [false, true] {
        let engine: E = Engine::new(CpuDevice::new(2)).explain(explain);
        let first = engine
            .run(&g.p, &inputs(&g, &e0, &s0, &blocked))
            .await
            .unwrap();
        // 1: new edges (one from a reached vertex, one between new ones) and a new seed
        let more = [(2, 3), (4, 7), (8, 9)];
        let e1: Vec<_> = e0.iter().chain(&more).copied().collect();
        let s1 = [0, 8];
        let mut added = Inputs::new();
        added.facts(&g.e, pairs(&more)).unwrap();
        added.facts(&g.s, ones(&[8])).unwrap();
        let ins1 = inputs(&g, &e1, &s1, &blocked);
        let next = engine
            .continue_from(&g.p, &first, &ins1, &added)
            .await
            .unwrap();
        let scratch = engine.run(&g.p, &ins1).await.unwrap();
        for (name, rel) in &g.out {
            assert_eq!(rows(&next, *rel), rows(&scratch, *rel), "{name}");
        }
        assert!(rows(&next, g.out[0].1).contains(&vec![9]));
        let c = continued(&next);
        // (explained, the counted `deg` counts again: its proofs keep each rule's rows)
        assert!(
            c.iter().all(|(r, &k)| k != (explain && r == "deg")),
            "every stratum continued: {c:?}"
        );
        // the counts added: 2 -> 3 (reached now) counts once, 4 -> 7 too
        let deg: BTreeSet<Vec<u64>> = rows(&next, g.out[4].1);
        assert!(
            deg.contains(&vec![2, 2]) && deg.contains(&vec![3, 1]),
            "{deg:?}"
        );
        // 2: what the negation reads grew: `free` is computed again, the rest continue
        let ins2 = inputs(&g, &e1, &s1, &[2, 4]);
        let mut added2 = Inputs::new();
        added2.facts(&g.blocked, ones(&[4])).unwrap();
        let again = engine
            .continue_from(&g.p, &next, &ins2, &added2)
            .await
            .unwrap();
        let scratch2 = engine.run(&g.p, &ins2).await.unwrap();
        for (name, rel) in &g.out {
            assert_eq!(rows(&again, *rel), rows(&scratch2, *rel), "{name}");
        }
        let c = continued(&again);
        assert!(!c["free"], "{c:?}");
        // (`deg` read nothing that changed: kept, explained or not)
        assert!(c["r"] && c["tc"] && c["p"] && c["deg"], "{c:?}");
        if explain {
            let facts = |e: &[(u32, u32)], s: &[u32], b: &[u32]| {
                BTreeMap::from([
                    (g.e.id(), pairs(e).rows().collect()),
                    (g.s.id(), ones(s).rows().collect()),
                    (g.blocked.id(), ones(b).rows().collect()),
                ])
            };
            proofs_check(&g, &next, &facts(&e1, &s1, &blocked));
            proofs_check(&g, &again, &facts(&e1, &s1, &[2, 4]));
            // a vertex reached before and one reached only now: proofs of both
            for v in [1u64, 9] {
                assert!(next.why_id(&g.p, g.out[0].1, &[v]).is_some());
            }
        }
    }
}

#[tokio::test]
async fn rows_gone_from_an_input_found_by_comparing() {
    let g = program();
    let engine: E = Engine::new(CpuDevice::new(2));
    let e0 = [(0, 1), (1, 2), (2, 3)];
    let first = engine.run(&g.p, &inputs(&g, &e0, &[0], &[])).await.unwrap();
    // an edge gone (nothing named as added, nothing as removed): found by comparing; the
    // joins and the count continue (deleted and derived again, counts taken off), the
    // reach and the closure run again
    let ins = inputs(&g, &e0[..2], &[0], &[]);
    let next = engine
        .continue_from(&g.p, &first, &ins, &Inputs::new())
        .await
        .unwrap();
    let scratch = engine.run(&g.p, &ins).await.unwrap();
    for (name, rel) in &g.out {
        assert_eq!(rows(&next, *rel), rows(&scratch, *rel), "{name}");
    }
    let c = continued(&next);
    assert!(!c["r"] && !c["tc"] && c["p"] && c["deg"], "{c:?}");
}

/// (lo, hi, id) for the ids below 100 in lo..=hi: an index the choice uses.
#[derive(Debug)]
struct Below;

impl External for Below {
    fn arity(&self) -> usize {
        2
    }
    fn can(&self, bound: u64) -> bool {
        bound & 1 == 1
    }
    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_datalog::Result<()> {
        for (k, &hi) in keys[0].iter().enumerate().take(n) {
            for id in 0..hi.min(100) {
                out(k, &[hi, id]);
            }
        }
        Ok(())
    }
}

#[tokio::test]
async fn the_index_choice_continues_too() {
    let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
    let catalog = |calls: &[(u64, u64)]| {
        let mut c = Catalog::new();
        c.label("func", Source::Columns(vec![u((0..20).collect())]))
            .id_block("func", 0, 20)
            .edge(
                "calls",
                Source::Columns(vec![
                    u(calls.iter().map(|x| x.0).collect()),
                    u(calls.iter().map(|x| x.1).collect()),
                ]),
            );
        c
    };
    let index: Arc<dyn External> = Arc::new(Below);
    let mut p = Program::new();
    let c0 = catalog(&[(0, 1), (1, 2)]);
    let func = p.input_from::<1>(&c0, "func").unwrap();
    let calls = p.input_from::<2>(&c0, "calls").unwrap();
    let below = p.external::<2>("below");
    let low = p.derived::<1>("low");
    let reach = p.derived::<2>("reach");
    let [f, g, h] = ["F", "G", "H"].map(|v| p.var(v));
    p.rule(low.at([f]), [func.at([f]).into(), lt(f, Term::Const(8))])
        .unwrap();
    p.rule(low.at([f]), [below.atom([Term::Const(3), f.into()])])
        .unwrap();
    p.rule(reach.at([f, g]), [low.at([f]), calls.at([f, g])])
        .unwrap();
    p.rule(reach.at([f, h]), [reach.at([f, g]), calls.at([g, h])])
        .unwrap();
    let bind = |c: &Catalog| {
        let mut ins = Inputs::new();
        ins.bind(&p, c).unwrap();
        ins.external(&below, index.clone()).unwrap();
        ins
    };
    for on in [false, true] {
        let engine: E = Engine::new(CpuDevice::new(2))
            .index_choice(on)
            .explain(true);
        let first = engine.run(&p, &bind(&c0)).await.unwrap();
        let more = [(2, 3), (3, 9), (12, 13)];
        let all: Vec<(u64, u64)> = [(0, 1), (1, 2)].into_iter().chain(more).collect();
        let c1 = catalog(&all);
        let mut added = Inputs::new();
        added
            .bind(&p, &catalog(&more))
            .unwrap()
            .external(&below, index.clone())
            .unwrap();
        let next = engine
            .continue_from(&p, &first, &bind(&c1), &added)
            .await
            .unwrap();
        let scratch = engine.run(&p, &bind(&c1)).await.unwrap();
        for rel in [low.id(), reach.id()] {
            assert_eq!(rows(&next, rel), rows(&scratch, rel), "choice {on}");
        }
        assert!(rows(&next, reach.id()).contains(&vec![0, 9]));
        assert!(
            next.report.strata.iter().any(|s| s.continued),
            "choice {on}"
        );
        let q = next.why_id(&p, reach.id(), &[0, 9]).expect("a proof");
        assert!(q.steps() >= 3, "{}", next.render(&p, &q));
    }
}