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

//! `datalog!` against the builder: each program written both ways gives the same plan, the
//! same facts and the same rendered why of every fact.

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

use kleene_datalog::{
    Aggregate, DatalogError, Engine, Expr, Facts, Inputs, Literal as L, Part, Producer, Program,
    RelId, Stratum, Term, Value, Var, compute, datalog, eq, ge, gt, le, lt, ne, plan, within,
};
use kleene_sparse::{CpuBackend, CpuDevice};

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

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

fn c(x: u64) -> Term {
    Term::Const(x)
}

fn v(x: Var) -> Term {
    Term::Var(x)
}

/// The same relations, rules (variables by number and name), rounds and strata.
fn same_plan(a: &Program, b: &Program) {
    assert_eq!(
        format!("{:?}", a.relations()),
        format!("{:?}", b.relations())
    );
    assert_eq!(a.rules(), b.rules());
    // the variables' names, as the rules print them
    let show = |p: &Program| -> Vec<String> {
        p.rules()
            .iter()
            .map(|r| {
                let atoms = std::iter::once(&r.head).chain(&r.body).chain(&r.negated);
                let mut s: Vec<String> = atoms
                    .flat_map(|a| a.terms.iter().map(|t| p.show_term(*t)))
                    .collect();
                s.extend(r.conds.iter().map(|c| p.show_cond(c)));
                s.extend(r.agg.iter().map(|g| p.show_agg(&g.agg)));
                s.join(" ")
            })
            .collect()
    };
    assert_eq!(show(a), show(b));
    assert_eq!(a.round_groups(), b.round_groups());
    assert_eq!(plan(a).unwrap(), plan(b).unwrap());
}

/// Both programs run on the same inputs (their relations have the same numbers) give the
/// same facts and the same rendered proof of every fact; returns the proofs.
async fn same_run(a: &Program, b: &Program, inputs: &Inputs) -> Vec<String> {
    let oa = engine().run(a, inputs).await.unwrap();
    let ob = engine().run(b, inputs).await.unwrap();
    let mut proofs = Vec::new();
    let heads: BTreeSet<RelId> = a.rules().iter().map(|r| r.head.rel).collect();
    for id in heads {
        let r = a.relation_info(id);
        let fa: BTreeSet<Vec<Value>> = oa
            .get_id(id)
            .map(|f| f.rows().collect())
            .unwrap_or_default();
        let fb: BTreeSet<Vec<Value>> = ob
            .get_id(id)
            .map(|f| f.rows().collect())
            .unwrap_or_default();
        assert_eq!(fa, fb, "facts of {}", r.name);
        for t in &fa {
            let pa = oa.why_id(a, id, t).expect("a proof").render(a);
            let pb = ob.why_id(b, id, t).expect("a proof").render(b);
            assert_eq!(pa, pb);
            proofs.push(pa);
        }
    }
    assert!(!proofs.is_empty(), "the programs derived nothing");
    proofs
}

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

fn edge_facts() -> Facts {
    Facts::from_rows(2, edges().iter().map(|e| e.to_vec())).unwrap()
}

#[tokio::test]
async fn reach_as_a_bfs() {
    let (m, r) = datalog! {
        input entry/1, calls/2.
        derived reach/1.
        reach(F) :- entry(F).
        reach(G) :- reach(F), calls(F, G).
    }
    .unwrap();
    let mut b = Program::new();
    let entry = b.input::<1>("entry");
    let calls = b.input::<2>("calls");
    let reach = b.derived::<1>("reach");
    let (f, g) = (b.var("F"), b.var("G"));
    b.rule(reach.at([f]), [entry.at([f])]).unwrap();
    b.rule(reach.at([g]), [reach.at([f]), calls.at([f, g])])
        .unwrap();
    same_plan(&m, &b);
    assert!(matches!(plan(&m).unwrap()[..], [Stratum::Reach { .. }]));
    assert_eq!(
        (r.entry.id(), r.calls.id(), r.reach.id()),
        (entry.id(), calls.id(), reach.id())
    );
    let mut inputs = Inputs::new();
    inputs.facts(&r.entry, facts(1, &[&[7]])).unwrap();
    inputs.facts(&r.calls, edge_facts()).unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    assert!(
        proofs
            .iter()
            .any(|p| p.contains("reach(G) :- reach(F), calls(F, G)."))
    );
}

#[tokio::test]
async fn a_two_column_closure_as_masked_products() {
    let (m, r) = datalog! {
        input e/2.
        derived t/2 as "path".
        t(X, Y) :- e(X, Y).
        t(X, Z) :- t(X, Y), e(Y, Z).
    }
    .unwrap();
    let mut b = Program::new();
    let e = b.input::<2>("e");
    let t = b.derived::<2>("path");
    let (x, y, z) = (b.var("X"), b.var("Y"), b.var("Z"));
    b.rule(t.at([x, y]), [e.at([x, y])]).unwrap();
    b.rule(t.at([x, z]), [t.at([x, y]), e.at([y, z])]).unwrap();
    same_plan(&m, &b);
    assert!(matches!(plan(&m).unwrap()[..], [Stratum::Closure { .. }]));
    let mut inputs = Inputs::new();
    inputs.facts(&r.e, edge_facts()).unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    assert!(proofs.iter().any(|p| p.starts_with("path(0, 4)")));
}

mod kind {
    pub const CALL: u64 = 1;
}

fn code(n: u32) -> u64 {
    u64::from(n) * 10
}

/// Negation, every comparison, a range, constants from Rust (a literal, a path, a call, a
/// braced local and a braced `Var` of the caller), `_`, field relations, mixed with
/// builder rules on one program.
#[tokio::test]
async fn negation_comparisons_and_constants_beside_builder_rules() {
    struct T {
        site: kleene_datalog::Rel<3>,
        callee: kleene_datalog::Rel<2>,
    }
    let lo = 2u32;
    let build = |with_macro: bool| -> (Program, Vec<RelId>) {
        let mut p = Program::new();
        let t = T {
            site: p.input::<3>("site"),
            callee: p.input::<2>("callee"),
        };
        let bad = p.input::<1>("bad");
        let ok = p.derived::<2>("ok");
        // a builder rule first, in both
        let (s, f, k) = (p.var("S"), p.var("F"), p.var("K"));
        p.rule(ok.at([s, f]), [L::from(t.site.at([s, f, k])), !bad.at([f])])
            .unwrap();
        if with_macro {
            let held = p.var("H");
            let r = datalog!(&mut p =>
                derived calls/2, low/1, mid/1 as "r_mid", other/2.
                calls(S, G) :- t.site(S, F, kind::CALL), t.callee(S, G), !bad(G), F != G.
                low(S) :- ok(S, F), F < 5, F <= lo, S == S.
                mid(S) :- t.site(S, F, _), F > 1, F >= {code(0)}, F in {lo}..8, !t.callee(S, F).
                other(S, K) :- t.site(S, held, K), K == 7u32, t.callee(S, _).
                other(S, K) :- t.site(S, F, K), K == {code(1)}, ok(_, F).
            )
            .unwrap();
            // a builder rule after, on a relation the macro declared
            let x = p.var("X");
            p.rule(ok.at([x, x]), [r.low.at([x])]).unwrap();
            let ids = vec![ok.id(), r.calls.id(), r.low.id(), r.mid.id(), r.other.id()];
            (p, ids)
        } else {
            let held = p.var("H");
            let calls = p.derived::<2>("calls");
            let low = p.derived::<1>("low");
            let mid = p.derived::<1>("r_mid");
            let other = p.derived::<2>("other");
            // the macro's variables: one per name, in the order first written; `_` each
            let (s2, g, f2) = (p.var("S"), p.var("G"), p.var("F"));
            p.rule(
                calls.at([s2, g]),
                [
                    L::from(t.site.atom([v(s2), v(f2), c(kind::CALL)])),
                    L::from(t.callee.at([s2, g])),
                    !bad.at([g]),
                    ne(f2, g),
                ],
            )
            .unwrap();
            p.rule(
                low.at([s2]),
                [
                    L::from(ok.at([s2, f2])),
                    lt(f2, 5u64),
                    le(f2, lo),
                    eq(s2, s2),
                ],
            )
            .unwrap();
            let w1 = p.var("_");
            p.rule(
                mid.at([s2]),
                [
                    L::from(t.site.at([s2, f2, w1])),
                    gt(f2, 1u64),
                    ge(f2, code(0)),
                    within(f2, lo, 8u64),
                    !t.callee.at([s2, f2]),
                ],
            )
            .unwrap();
            let k2 = p.var("K");
            let w2 = p.var("_");
            p.rule(
                other.at([s2, k2]),
                [
                    L::from(t.site.atom([v(s2), v(held), v(k2)])),
                    eq(k2, 7u32),
                    L::from(t.callee.at([s2, w2])),
                ],
            )
            .unwrap();
            let w3 = p.var("_");
            p.rule(
                other.at([s2, k2]),
                [
                    L::from(t.site.at([s2, f2, k2])),
                    eq(k2, code(1)),
                    L::from(ok.at([w3, f2])),
                ],
            )
            .unwrap();
            let x = p.var("X");
            p.rule(ok.at([x, x]), [low.at([x])]).unwrap();
            let ids = vec![ok.id(), calls.id(), low.id(), mid.id(), other.id()];
            (p, ids)
        }
    };
    let (m, mi) = build(true);
    let (b, bi) = build(false);
    assert_eq!(mi, bi);
    same_plan(&m, &b);
    // the inputs by the builder's handles: both programs number them alike
    let mut tmp = Program::new();
    let site = tmp.input::<3>("site");
    let callee = tmp.input::<2>("callee");
    let bad = tmp.input::<1>("bad");
    let mut inputs = Inputs::new();
    inputs
        .facts(
            &site,
            facts(
                3,
                &[
                    &[1, 3, 1],
                    &[2, 4, 1],
                    &[3, 2, 2],
                    &[4, 6, 7],
                    &[5, 1, 10],
                    &[6, 2, 10],
                ],
            ),
        )
        .unwrap();
    inputs
        .facts(
            &callee,
            facts(2, &[&[1, 5], &[1, 3], &[2, 9], &[3, 2], &[4, 4], &[6, 1]]),
        )
        .unwrap();
    inputs.facts(&bad, facts(1, &[&[9], &[6]])).unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    assert!(proofs.iter().any(|p| p.contains("[absent]")), "{proofs:#?}");
    assert!(proofs.iter().any(|p| p.contains("[holds]")), "{proofs:#?}");
    assert!(
        proofs.iter().any(|p| p.contains("site(S, F, 1)")),
        "{proofs:#?}"
    );
}

#[tokio::test]
async fn aggregates_count_min_max_exactly_one() {
    let (m, r) = datalog! {
        input e/3.
        derived fan/2, all/1, first/3, last/2, one/2.
        fan(X, N) :- N = count(Y) by (X): e(X, Y, _).
        all(N) :- N = count(X, Y): e(X, Y, W), W > 0.
        first(X, Y, W) :- min(W, Y) by (X): e(X, Y, W).
        last(X, Y) :- max(Y): e(X, Y, _).
        one(X, W) :- exactly_one(W) by (X): e(X, _, W).
    }
    .unwrap();
    let mut b = Program::new();
    let e = b.input::<3>("e");
    let fan = b.derived::<2>("fan");
    let all = b.derived::<1>("all");
    let first = b.derived::<3>("first");
    let last = b.derived::<2>("last");
    let one = b.derived::<2>("one");
    let (x, n, y) = (b.var("X"), b.var("N"), b.var("Y"));
    let w0 = b.var("_");
    b.aggregate(
        fan.at([x, n]),
        Aggregate::count([x], [y], n),
        [e.at([x, y, w0])],
    )
    .unwrap();
    let w = b.var("W");
    b.aggregate(
        all.at([n]),
        Aggregate::count([], [x, y], n),
        [L::from(e.at([x, y, w])), gt(w, 0u64)],
    )
    .unwrap();
    b.aggregate(
        first.at([x, y, w]),
        Aggregate::min_by([x], [w, y]),
        [e.at([x, y, w])],
    )
    .unwrap();
    let w1 = b.var("_");
    b.aggregate(
        last.at([x, y]),
        Aggregate::max_by([], [y]),
        [e.at([x, y, w1])],
    )
    .unwrap();
    let w2 = b.var("_");
    b.aggregate(
        one.at([x, w]),
        Aggregate::exactly_one([x], [w]),
        [e.at([x, w2, w])],
    )
    .unwrap();
    same_plan(&m, &b);
    let mut inputs = Inputs::new();
    inputs
        .facts(
            &r.e,
            facts(
                3,
                &[
                    &[1, 2, 5],
                    &[1, 3, 5],
                    &[1, 4, 2],
                    &[2, 1, 0],
                    &[3, 3, 9],
                    &[3, 1, 9],
                ],
            ),
        )
        .unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    for agg in [
        "N = count (Y) by (X)",
        "min (W, Y) by (X)",
        "max (Y) by ()",
        "exactly one (W) by (X)",
    ] {
        assert!(proofs.iter().any(|p| p.contains(agg)), "{agg}: {proofs:#?}");
    }
}

#[tokio::test]
async fn an_external_relation_positive_and_negated() {
    let (m, r) = datalog! {
        input s/1.
        external near/2 as "near_ix".
        derived hit/2, miss/1.
        hit(X, Y) :- s(X), near(X, Y).
        miss(X) :- s(X), !near(X, 0).
    }
    .unwrap();
    let mut b = Program::new();
    let s = b.input::<1>("s");
    let near = b.external::<2>("near_ix");
    let hit = b.derived::<2>("hit");
    let miss = b.derived::<1>("miss");
    let (x, y) = (b.var("X"), b.var("Y"));
    b.rule(hit.at([x, y]), [s.at([x]), near.at([x, y])])
        .unwrap();
    b.rule(miss.at([x]), [L::from(s.at([x])), !near.atom([v(x), c(0)])])
        .unwrap();
    same_plan(&m, &b);
    let mut inputs = Inputs::new();
    inputs.facts(&r.s, facts(1, &[&[1], &[2], &[3]])).unwrap();
    inputs
        .external(
            &r.near,
            Arc::new(Producer::new(2, |out: &mut dyn FnMut(&[Value])| {
                for row in [[1, 0], [1, 5], [3, 7]] {
                    out(&row);
                }
                Ok(())
            })),
        )
        .unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    assert!(
        proofs.iter().any(|p| p.contains("[external]")),
        "{proofs:#?}"
    );
}

#[tokio::test]
async fn a_stratum_of_rounds() {
    let (m, r) = datalog! {
        input e/2, s/1.
        derived ev/1, od/1, n/1.
        ev(X) :- s(X).
        od(Y) :- ev(X), e(X, Y), !ev(Y).
        ev(Y) :- od(X), e(X, Y), !od(Y).
        n(K) :- K = count(X): od(X).
        rounds ev: keep, od: keep, n: fresh.
    }
    .unwrap();
    let mut b = Program::new();
    let e = b.input::<2>("e");
    let s = b.input::<1>("s");
    let ev = b.derived::<1>("ev");
    let od = b.derived::<1>("od");
    let n = b.derived::<1>("n");
    let (x, y, k) = (b.var("X"), b.var("Y"), b.var("K"));
    b.rule(ev.at([x]), [s.at([x])]).unwrap();
    b.rule(
        od.at([y]),
        [L::from(ev.at([x])), L::from(e.at([x, y])), !ev.at([y])],
    )
    .unwrap();
    b.rule(
        ev.at([y]),
        [L::from(od.at([x])), L::from(e.at([x, y])), !od.at([y])],
    )
    .unwrap();
    b.aggregate(n.at([k]), Aggregate::count([], [x], k), [od.at([x])])
        .unwrap();
    b.rounds([
        (ev.id(), Part::Keep),
        (od.id(), Part::Keep),
        (n.id(), Part::Fresh),
    ])
    .unwrap();
    same_plan(&m, &b);
    assert!(
        plan(&m)
            .unwrap()
            .iter()
            .any(|s| matches!(s, Stratum::Rounds { .. }))
    );
    let mut inputs = Inputs::new();
    inputs.facts(&r.s, facts(1, &[&[0]])).unwrap();
    inputs.facts(&r.e, edge_facts()).unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    assert!(proofs.iter().any(|p| p.contains("[round ")), "{proofs:#?}");
}

/// What the builder refuses at run time comes back from the macro as the same error.
#[test]
fn run_time_refusals_are_returned() {
    let mut p = Program::new();
    let given = p.input::<1>("given");
    let e = p.input::<2>("e");
    let err = datalog!(&mut p => given(X) :- e(X, _).).unwrap_err();
    let mut q = Program::new();
    let given2 = q.input::<1>("given");
    let e2 = q.input::<2>("e");
    let (x, w) = (q.var("X"), q.var("_"));
    let want = q.rule(given2.at([x]), [e2.at([x, w])]).unwrap_err();
    assert_eq!(err.to_string(), want.to_string());
    assert!(matches!(err, DatalogError::Program(_)));

    // rounds of a relation twice: refused, and the rules before it stay
    let mut p = Program::new();
    let e = p.input::<2>("e");
    let err = datalog!(&mut p =>
        derived r/1.
        r(X) :- e(X, _).
        rounds r: keep, r: fresh.
    )
    .unwrap_err();
    assert!(err.to_string().contains("twice"), "{err}");
    assert_eq!(p.rules().len(), 1);
}

#[tokio::test]
async fn computed_values_and_expressions_in_conditions() {
    let mask = 4u64;
    let (m, r) = datalog! {
        input st/2, ix/2, flags/2.
        derived off/2, ended/1, inside/2.
        off(S, O) :- st(S, LO), ix(S, I), O = LO + I * 2 - 1.
        ended(L) :- flags(L, F), !F & {mask} == 0.
        inside(S, I) :- st(S, LO), ix(S, I), I + 1 in LO..(LO << 1) + 3.
    }
    .unwrap();
    let mut b = Program::new();
    let st = b.input::<2>("st");
    let ix = b.input::<2>("ix");
    let flags = b.input::<2>("flags");
    let off = b.derived::<2>("off");
    let ended = b.derived::<1>("ended");
    let inside = b.derived::<2>("inside");
    let [s, o, lo, i, l, f] = ["S", "O", "LO", "I", "L", "F"].map(|n| b.var(n));
    b.rule(
        off.at([s, o]),
        [
            st.at([s, lo]).into(),
            ix.at([s, i]).into(),
            compute(o, Expr::from(lo) + Expr::from(i) * 2u64 - 1u64),
        ],
    )
    .unwrap();
    b.rule(
        ended.at([l]),
        [flags.at([l, f]).into(), eq(!Expr::from(f) & mask, 0u64)],
    )
    .unwrap();
    b.rule(
        inside.at([s, i]),
        [
            st.at([s, lo]).into(),
            ix.at([s, i]).into(),
            within(Expr::from(i) + 1u64, lo, (Expr::from(lo) << 1u64) + 3u64),
        ],
    )
    .unwrap();
    same_plan(&m, &b);
    let mut inputs = Inputs::new();
    inputs
        .facts(&r.st, facts(2, &[&[1, 3], &[2, 10], &[3, 0]]))
        .unwrap();
    inputs
        .facts(&r.ix, facts(2, &[&[1, 4], &[2, 9], &[2, 30], &[3, 0]]))
        .unwrap();
    inputs
        .facts(&r.flags, facts(2, &[&[7, 5], &[8, 2], &[9, 4]]))
        .unwrap();
    let proofs = same_run(&m, &b, &inputs).await;
    assert!(
        proofs
            .iter()
            .any(|p| p.contains("O = LO + I * 2 - 1 = 3 + 4 * 2 - 1 = 10  [computed]")),
        "{proofs:?}"
    );
    assert!(
        proofs
            .iter()
            .any(|p| p.contains("ended(L) :- flags(L, F), !F & 4 == 0.")),
        "{proofs:?}"
    );
}