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

//! Stratified negation and the why of every fact.

use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};

use kleene_datalog::{
    DatalogError, Engine, Facts, How, Inputs, Output, Program, Proof, RelId, RelKind, Side,
    Stratum, instantiate, plan,
};
use kleene_sparse::{BoolOrAnd, CpuBackend, CpuDevice, Csr};

type E = Engine<CpuBackend>;

fn engine() -> E {
    Engine::new(CpuDevice::new(2)).explain(true)
}

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

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

fn rows(f: &Facts) -> BTreeSet<Vec<u64>> {
    f.rows().collect()
}

fn edges() -> Vec<(u32, u32)> {
    vec![
        (0, 1),
        (1, 2),
        (2, 0),
        (2, 3),
        (3, 4),
        (5, 6),
        (6, 5),
        (7, 3),
        (4, 8),
        (9, 9),
        (1, 3),
    ]
}

/// Every fact of every derived relation has a proof, and every proof checks: each rule
/// node's head and premises are its rule's atoms under its binding, input leaves are input
/// facts, derived premises are derived facts, absent facts are absent.
fn check_all(
    p: &Program,
    out: &Output,
    rels: &[RelId],
    inputs: &HashMap<RelId, BTreeSet<Vec<u64>>>,
) {
    let derived: HashMap<RelId, HashSet<Vec<u64>>> = rels
        .iter()
        .map(|&id| {
            (
                id,
                out.get_id(id)
                    .map(|f| f.rows().collect())
                    .unwrap_or_default(),
            )
        })
        .collect();
    let holds = |rel: RelId, t: &Vec<u64>| match p.relation_info(rel).kind {
        RelKind::Input | RelKind::External => inputs.get(&rel).is_some_and(|s| s.contains(t)),
        RelKind::Derived => derived[&rel].contains(t),
    };
    fn check(p: &Program, q: &Proof, holds: &dyn Fn(RelId, &Vec<u64>) -> bool) {
        assert!(holds(q.rel, &q.tuple), "{} does not hold", q.render(p));
        if let How::Rule {
            rule,
            binding,
            premises,
            absent,
        } = &q.how
        {
            let r = p.rule_at(*rule);
            assert_eq!(r.head.rel, q.rel);
            assert_eq!(instantiate(&r.head, binding), q.tuple);
            assert!(r.conds_hold(binding), "{}", q.render(p));
            assert_eq!(premises.len(), r.body.len());
            for (a, s) in r.body.iter().zip(premises) {
                assert_eq!((a.rel, instantiate(a, binding)), (s.rel, s.tuple.clone()));
                check(p, s, holds);
            }
            for (a, (rel, t)) in r.negated.iter().zip(absent) {
                assert_eq!((a.rel, instantiate(a, binding)), (*rel, t.clone()));
                assert!(!holds(*rel, t), "{} is not absent", q.render(p));
            }
        } else {
            assert_eq!(p.relation_info(q.rel).kind, RelKind::Input);
        }
    }
    for (&rel, facts) in &derived {
        for t in facts {
            let q = out
                .why_id(p, rel, t)
                .unwrap_or_else(|| panic!("no proof of {} {t:?}", p.relation_info(rel).name));
            check(p, &q, &holds);
        }
    }
}

fn levels(edges: &[(u32, u32)], seeds: &[u32]) -> HashMap<u32, usize> {
    let mut l: HashMap<u32, usize> = seeds.iter().map(|&s| (s, 0)).collect();
    let mut q: VecDeque<u32> = seeds.iter().copied().collect();
    while let Some(v) = q.pop_front() {
        for &(a, b) in edges {
            if a == v && !l.contains_key(&b) {
                l.insert(b, l[&v] + 1);
                q.push_back(b);
            }
        }
    }
    l
}

#[tokio::test]
async fn negation_after_a_reach_keeps_what_is_not_reached() {
    // reach(F) :- entry(F).  reach(G) :- reach(F), calls(F, G).
    // dead(F) :- func(F), !reach(F).
    let mut p = Program::new();
    let entry = p.input::<1>("entry");
    let calls = p.input::<2>("calls");
    let func = p.input::<1>("func");
    let reach = p.derived::<1>("reach");
    let dead = p.derived::<1>("dead");
    let (f, g) = (p.var("F"), p.var("G"));
    p.rule(reach.at([f]), [entry.at([f])]).unwrap();
    p.rule(reach.at([g]), [reach.at([f]), calls.at([f, g])])
        .unwrap();
    p.rule(dead.at([f]), [func.at([f]).into(), !reach.at([f])])
        .unwrap();
    let strata = plan(&p).unwrap();
    assert!(matches!(
        strata[..],
        [Stratum::Reach { .. }, Stratum::Joins { .. }]
    ));
    let e = edges();
    let mut inputs = Inputs::new();
    inputs.facts(&entry, ones(&[7])).unwrap();
    inputs.facts(&calls, pairs(&e)).unwrap();
    inputs
        .facts(&func, ones(&(0..10).collect::<Vec<_>>()))
        .unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let reached: BTreeSet<u32> = levels(&e, &[7]).into_keys().collect();
    let want: BTreeSet<Vec<u64>> = (0..10)
        .filter(|v| !reached.contains(v))
        .map(|v| vec![v as u64])
        .collect();
    assert_eq!(rows(out.get(&dead).unwrap()), want);
    let given = HashMap::from([
        (entry.id(), rows(&ones(&[7]))),
        (calls.id(), rows(&pairs(&e))),
        (func.id(), rows(&ones(&(0..10).collect::<Vec<_>>()))),
    ]);
    check_all(&p, &out, &[reach.id(), dead.id()], &given);
    // A reach proof is a shortest chain: its depth is the BFS level.
    for (v, l) in levels(&e, &[7]) {
        assert_eq!(
            out.why(&p, &reach, [v]).unwrap().depth(),
            l + 1,
            "vertex {v}"
        );
    }
    let q = out.why(&p, &dead, [0u64]).unwrap();
    assert!(
        q.render(&p).contains("!reach(0)  [absent]"),
        "{}",
        q.render(&p)
    );
    assert!(out.why(&p, &dead, [3u64]).is_none());
}

#[tokio::test]
async fn negation_inside_joins_and_through_datafusion() {
    // two(X, Z) :- e(X, Y), e(Y, Z), !e(X, Z).   oneway(X, Y) :- e(X, Y), !back(X, Y).
    // back(X, Y) :- e(Y, X).
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let two = p.derived::<2>("two");
    let back = p.derived::<2>("back");
    let oneway = p.derived::<2>("oneway");
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    p.rule(
        two.at([x, z]),
        [e.at([x, y]).into(), e.at([y, z]).into(), !e.at([x, z])],
    )
    .unwrap();
    p.rule(back.at([x, y]), [e.at([y, x])]).unwrap();
    p.rule(oneway.at([x, y]), [e.at([x, y]).into(), !back.at([x, y])])
        .unwrap();
    let es = edges();
    let set: BTreeSet<(u32, u32)> = es.iter().copied().collect();
    let mut inputs = Inputs::new();
    inputs.facts(&e, pairs(&es)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let mut want_two = BTreeSet::new();
    for &(a, b) in &es {
        for &(c, d) in &es {
            if b == c && !set.contains(&(a, d)) {
                want_two.insert(vec![a as u64, d as u64]);
            }
        }
    }
    assert_eq!(rows(out.get(&two).unwrap()), want_two);
    let want_one: BTreeSet<Vec<u64>> = es
        .iter()
        .filter(|&&(a, b)| !set.contains(&(b, a)))
        .map(|&(a, b)| vec![a as u64, b as u64])
        .collect();
    assert_eq!(rows(out.get(&oneway).unwrap()), want_one);
    check_all(
        &p,
        &out,
        &[two.id(), back.id(), oneway.id()],
        &HashMap::from([(e.id(), rows(&pairs(&es)))]),
    );
}

#[tokio::test]
async fn a_negation_inside_its_own_recursion_is_refused() {
    let mut p = Program::new();
    let q = p.input::<1>("q");
    let a = p.derived::<1>("a");
    let b = p.derived::<1>("b");
    let x = p.var("X");
    p.rule(a.at([x]), [q.at([x]).into(), !b.at([x])]).unwrap();
    p.rule(b.at([x]), [a.at([x])]).unwrap();
    assert!(matches!(plan(&p), Err(DatalogError::Program(_))));
    let mut inputs = Inputs::new();
    inputs.facts(&q, ones(&[1])).unwrap();
    assert!(engine().run(&p, &inputs).await.is_err());
}

#[tokio::test]
async fn closures_reaches_on_graphs_and_joins_all_explain_every_fact() {
    let es = edges();
    let given = |e: RelId| HashMap::from([(e, rows(&pairs(&es)))]);
    for side in [Side::Right, Side::Left] {
        let mut p = Program::new();
        let e = p.input::<2>("e");
        let t = p.derived::<2>("t");
        let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
        p.rule(t.at([x, y]), [e.at([x, y])]).unwrap();
        match side {
            Side::Right => p.rule(t.at([x, z]), [t.at([x, y]), e.at([y, z])]).unwrap(),
            Side::Left => p.rule(t.at([x, z]), [e.at([x, y]), t.at([y, z])]).unwrap(),
        };
        let mut inputs = Inputs::new();
        inputs.facts(&e, pairs(&es)).unwrap();
        let out = engine().run(&p, &inputs).await.unwrap();
        assert!(out.get(&t).unwrap().len() > es.len());
        check_all(&p, &out, &[t.id()], &given(e.id()));
        assert!(out.why(&p, &t, [8u64, 0]).is_none());
    }
    // Non-linear: semi-naive joins keep the first derivation of each fact.
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let t = p.derived::<2>("t");
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    p.rule(t.at([x, y]), [e.at([x, y])]).unwrap();
    p.rule(t.at([x, z]), [t.at([x, y]), t.at([y, z])]).unwrap();
    let mut inputs = Inputs::new();
    inputs.facts(&e, pairs(&es)).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    check_all(&p, &out, &[t.id()], &given(e.id()));
    // Reach both ways over a shared graph.
    let (src, dst): (Vec<u32>, Vec<u32>) = es.iter().copied().unzip();
    let m = Csr::<u8>::from_edges(10, 10, &src, &dst, None, BoolOrAnd).unwrap();
    for backward in [false, true] {
        let mut p = Program::new();
        let seed = p.input::<1>("seed");
        let calls = p.input::<2>("calls");
        let r = p.derived::<1>("r");
        let (f, g) = (p.var("F"), p.var("G"));
        p.rule(r.at([f]), [seed.at([f])]).unwrap();
        if backward {
            p.rule(r.at([f]), [calls.at([f, g]), r.at([g])]).unwrap();
        } else {
            p.rule(r.at([g]), [r.at([f]), calls.at([f, g])]).unwrap();
        }
        let mut inputs = Inputs::new();
        inputs.facts(&seed, ones(&[3])).unwrap();
        inputs.graph(&calls, m.clone(), None);
        let out = engine().run(&p, &inputs).await.unwrap();
        let mut gv = given(calls.id());
        gv.insert(seed.id(), rows(&ones(&[3])));
        check_all(&p, &out, &[r.id()], &gv);
        let flipped: Vec<(u32, u32)> = es.iter().map(|&(a, b)| (b, a)).collect();
        let want = levels(if backward { &flipped } else { &es }, &[3]);
        for (v, l) in want {
            assert_eq!(out.why(&p, &r, [v]).unwrap().depth(), l + 1);
        }
    }
}

#[tokio::test]
async fn no_why_unless_asked() {
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let t = p.derived::<2>("t");
    let (x, y) = (p.var("X"), p.var("Y"));
    p.rule(t.at([y, x]), [e.at([x, y])]).unwrap();
    let mut inputs = Inputs::new();
    inputs.facts(&e, pairs(&[(1, 2)])).unwrap();
    let out = Engine::<CpuBackend>::new(CpuDevice::new(1))
        .run(&p, &inputs)
        .await
        .unwrap();
    assert!(out.why(&p, &t, [2u64, 1]).is_none());
    let out = engine().run(&p, &inputs).await.unwrap();
    let q = out.why(&p, &t, [2u64, 1]).unwrap();
    assert_eq!((q.steps(), q.depth()), (1, 1));
    assert_eq!(
        q.render(&p),
        "t(2, 1)  [t(Y, X) :- e(X, Y).]\n  e(1, 2)  [input]\n"
    );
}