Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/tests/columns.rs

//! The rule layer on columns: joins on packed multi-column keys, anti-joins, ranges,
//! dedupe, recursion and aggregates, checked fact for fact against a plain evaluator
//! written here (nested loops over sets of rows, rounds until nothing new); the why of
//! every joined fact checked against the same sets; Arrow columns used in place.

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

use arrow_array::{Array, UInt64Array};
use arrow_buffer::ScalarBuffer;
use kleene_plan::{
    Agg, Aggregate, Atom, Cmp, Column, Cond, Engine, Facts, How, Inputs, Literal, Plan, RelId,
    RelKind, Rule, Term, Value, Var, instantiate, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};

type Set = BTreeSet<Vec<Value>>;
type Binding = Vec<(Var, Value)>;
type E = Engine<CpuBackend>;

fn atom(rel: RelId, terms: &[Term]) -> Atom {
    Atom {
        rel,
        terms: terms.to_vec(),
    }
}

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

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

fn cmp(left: Term, op: Cmp, right: Term) -> Literal {
    Literal::Cond(Cond::Cmp { left, op, right })
}

/// A small deterministic generator.
struct Lcg(u64);

impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0 >> 33
    }

    fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }
}

/// Values over 32 bits, so 64-bit columns are joined too.
const WIDE: Value = 1 << 40;

fn random_set(g: &mut Lcg, rows: usize, domains: &[(u64, Value)]) -> Set {
    (0..rows)
        .map(|_| domains.iter().map(|&(n, base)| base + g.below(n)).collect())
        .collect()
}

fn facts_of(arity: usize, s: &Set, twice: bool) -> Facts {
    // Input facts may hold a row more than once; the rules see each once.
    let rows = s.iter().chain(s.iter().filter(|_| twice));
    Facts::from_rows(arity, rows).unwrap()
}

/// One binding of `rule`'s positive body over `db`, extended atom by atom.
fn extend(
    atoms: &[Atom],
    db: &BTreeMap<RelId, Set>,
    cur: &mut Vec<(Var, Value)>,
    out: &mut Vec<Vec<(Var, Value)>>,
) {
    let Some((a, rest)) = atoms.split_first() else {
        out.push(cur.clone());
        return;
    };
    for row in &db[&a.rel] {
        let mark = cur.len();
        let fits = a.terms.iter().zip(row).all(|(t, &x)| match *t {
            Term::Const(k) => k == x,
            Term::Var(w) => match cur.iter().find(|b| b.0 == w) {
                Some(b) => b.1 == x,
                None => {
                    cur.push((w, x));
                    true
                }
            },
        });
        if fits {
            extend(rest, db, cur, out);
        }
        cur.truncate(mark);
    }
}

/// The distinct bindings of `rule`'s variables (in [`Rule::vars`] order) that satisfy its
/// positive atoms, conditions and negated atoms.
fn bindings(rule: &Rule, db: &BTreeMap<RelId, Set>) -> Vec<Vec<(Var, Value)>> {
    let mut all = Vec::new();
    extend(&rule.body, db, &mut Vec::new(), &mut all);
    let vars = rule.vars();
    let mut seen = BTreeSet::new();
    all.into_iter()
        .filter(|b| rule.conds_hold(b))
        .filter(|b| {
            rule.negated
                .iter()
                .all(|n| !db[&n.rel].contains(&instantiate(n, b)))
        })
        .map(|b| {
            vars.iter()
                .map(|&w| (w, b.iter().find(|x| x.0 == w).unwrap().1))
                .collect::<Vec<_>>()
        })
        .filter(|b| seen.insert(b.clone()))
        .collect()
}

fn values(b: &[(Var, Value)], vs: &[Var]) -> Vec<Value> {
    vs.iter()
        .map(|w| b.iter().find(|x| x.0 == *w).unwrap().1)
        .collect()
}

/// The head facts of `rule` over `db`.
fn apply(rule: &Rule, db: &BTreeMap<RelId, Set>) -> Set {
    let bs = bindings(rule, db);
    let Some(a) = &rule.agg else {
        return bs.iter().map(|b| instantiate(&rule.head, b)).collect();
    };
    let mut groups: BTreeMap<Vec<Value>, Vec<&Binding>> = BTreeMap::new();
    for b in &bs {
        groups.entry(values(b, &a.group)).or_default().push(b);
    }
    let head_vars: Vec<Var> = rule.head.vars().collect();
    let all_vars = rule.vars();
    let mut out = Set::new();
    if bs.is_empty() && a.group.is_empty() {
        if let Agg::Count { out: o, .. } = &a.agg {
            out.insert(instantiate(&rule.head, &[(*o, 0)]));
        }
        return out;
    }
    for (g, members) in groups {
        let mut hb: Vec<(Var, Value)> = a.group.iter().copied().zip(g).collect();
        match &a.agg {
            Agg::Count { of, out: o } => {
                let distinct: BTreeSet<Vec<Value>> =
                    members.iter().map(|b| values(b, of)).collect();
                hb.push((*o, distinct.len() as Value));
                out.insert(instantiate(&rule.head, &hb));
            }
            Agg::One { of } => {
                let distinct: BTreeSet<Vec<Value>> =
                    members.iter().map(|b| values(b, of)).collect();
                if distinct.len() == 1 {
                    out.insert(instantiate(&rule.head, members[0]));
                }
            }
            Agg::Min { key } | Agg::Max { key } => {
                let max = matches!(a.agg, Agg::Max { .. });
                let best = members
                    .iter()
                    .min_by(|x, y| {
                        let o = values(x, key).cmp(&values(y, key));
                        let o = if max { o.reverse() } else { o };
                        o.then_with(|| values(x, &head_vars).cmp(&values(y, &head_vars)))
                            .then_with(|| values(x, &all_vars).cmp(&values(y, &all_vars)))
                    })
                    .unwrap();
                out.insert(instantiate(&rule.head, best));
            }
            other => unreachable!("an aggregate the reference does not know: {other:?}"),
        }
    }
    out
}

/// The plain evaluator: the planner's strata in order, each one's rules applied over sets
/// of rows until a round adds nothing.
fn plain(p: &Plan, given: &BTreeMap<RelId, Set>) -> BTreeMap<RelId, Set> {
    let mut db = given.clone();
    for s in plan(p).unwrap() {
        let rels = s.relations();
        for r in &rels {
            db.entry(*r).or_default();
        }
        let rules: Vec<&Rule> = p
            .rules()
            .iter()
            .filter(|r| rels.contains(&r.head.rel))
            .collect();
        loop {
            let mut grew = false;
            for rule in &rules {
                for row in apply(rule, &db) {
                    grew |= db.get_mut(&rule.head.rel).unwrap().insert(row);
                }
            }
            if !grew {
                break;
            }
        }
    }
    db
}

/// Every derived fact's why: a proof whose head is the fact, whose conditions hold, whose
/// premises are facts and whose absent facts are not.
fn check_why(p: &Plan, out: &kleene_plan::Output, db: &BTreeMap<RelId, Set>, rel: RelId) {
    for t in &db[&rel] {
        let proof = out
            .why(p, rel, t)
            .unwrap_or_else(|| panic!("no why for {}{t:?}", p.relation_info(rel).name));
        assert_eq!(&proof.tuple, t);
        match &proof.how {
            How::Rule {
                rule,
                binding,
                premises,
                absent,
            } => {
                let r = p.rule_at(*rule);
                assert_eq!(r.head.rel, rel);
                assert_eq!(&instantiate(&r.head, binding), t);
                assert!(r.conds_hold(binding), "{}", proof.render(p));
                for pr in premises {
                    assert!(db[&pr.rel].contains(&pr.tuple), "{}", proof.render(p));
                }
                for (a, x) in absent {
                    assert!(!db[a].contains(x), "{}", proof.render(p));
                }
            }
            How::Aggregate {
                rule,
                binding,
                members,
                ..
            } => {
                let r = p.rule_at(*rule);
                assert_eq!(&instantiate(&r.head, binding), t);
                for m in members {
                    for pr in &m.premises {
                        assert!(db[&pr.rel].contains(&pr.tuple), "{}", proof.render(p));
                    }
                }
            }
            How::Input | How::External => panic!("a derived fact proven as given"),
            other => panic!("a proof the check does not know: {other:?}"),
        }
    }
}

#[tokio::test]
async fn rules_on_columns_equal_a_plain_evaluator() {
    for seed in [1u64, 7, 42] {
        let mut g = Lcg(seed);
        let mut p = Plan::new();
        let a = p.input("a", 3);
        let b = p.input("b", 3);
        let s = p.input("s", 1);
        let t = p.input("t", 1);
        let addr = p.input("addr", 1);
        let rng = p.input("rng", 3);
        let e = p.input("e", 2);
        let bad = p.input("bad", 1);
        let j = p.derived("j", 3);
        let n = p.derived("n", 2);
        let w = p.derived("w", 2);
        let x = p.derived("x", 2);
        let h = p.derived("h", 2);
        let p3 = p.derived("p3", 3);
        let ev = p.derived("ev", 2);
        let od = p.derived("od", 2);
        let cnt = p.derived("cnt", 2);
        let lo1 = p.derived("lo1", 2);
        let hi1 = p.derived("hi1", 2);
        let one = p.derived("one", 2);
        let none = p.derived("none", 1);
        let [vx, vy, vz, vk, vd, va, vf, vl, vh, vn] =
            ["X", "Y", "Z", "K", "D", "A", "F", "L", "H", "N"].map(|s| p.var(s));
        // j(X, Y, Z) :- a(X, Y, K), b(K, Z, Y), X != Z.   (a two-column key, 64-bit K)
        p.rule(
            atom(j, &[v(vx), v(vy), v(vz)]),
            [
                Literal::Pos(atom(a, &[v(vx), v(vy), v(vk)])),
                Literal::Pos(atom(b, &[v(vk), v(vz), v(vy)])),
                cmp(v(vx), Cmp::Ne, v(vz)),
            ],
        )
        .unwrap();
        // n(X, Z) :- j(X, Y, Z), !bad(Y), !j(Z, Y, X).   (negation on input and derived)
        p.rule(
            atom(n, &[v(vx), v(vz)]),
            [
                Literal::Pos(atom(j, &[v(vx), v(vy), v(vz)])),
                Literal::Neg(atom(bad, &[v(vy)])),
                Literal::Neg(atom(j, &[v(vz), v(vy), v(vx)])),
            ],
        )
        .unwrap();
        // w(A, F) :- addr(A), rng(F, L, H), A in [L, H).   (a range join)
        p.rule(
            atom(w, &[v(va), v(vf)]),
            [
                Literal::Pos(atom(addr, &[v(va)])),
                Literal::Pos(atom(rng, &[v(vf), v(vl), v(vh)])),
                Literal::Cond(Cond::Within {
                    x: v(va),
                    lo: v(vl),
                    hi: v(vh),
                }),
            ],
        )
        .unwrap();
        // x(A, B) :- s(A), t(B), A < B.   (no shared variable)
        p.rule(
            atom(x, &[v(va), v(vf)]),
            [
                Literal::Pos(atom(s, &[v(va)])),
                Literal::Pos(atom(t, &[v(vf)])),
                cmp(v(va), Cmp::Lt, v(vf)),
            ],
        )
        .unwrap();
        // h(X, 7) :- a(X, X, K), K >= WIDE + 2.   h(X, 9) :- a(X, 3, K).
        p.rule(
            atom(h, &[v(vx), c(7)]),
            [
                Literal::Pos(atom(a, &[v(vx), v(vx), v(vk)])),
                cmp(v(vk), Cmp::Ge, c(WIDE + 2)),
            ],
        )
        .unwrap();
        p.rule(
            atom(h, &[v(vx), c(9)]),
            [Literal::Pos(atom(a, &[v(vx), c(3), v(vk)]))],
        )
        .unwrap();
        // p3(X, Y, D) :- a(X, Y, D).   p3(X, Z, D) :- p3(X, Y, D), a(Y, Z, D).
        p.rule(
            atom(p3, &[v(vx), v(vy), v(vd)]),
            [Literal::Pos(atom(a, &[v(vx), v(vy), v(vd)]))],
        )
        .unwrap();
        p.rule(
            atom(p3, &[v(vx), v(vz), v(vd)]),
            [
                Literal::Pos(atom(p3, &[v(vx), v(vy), v(vd)])),
                Literal::Pos(atom(a, &[v(vy), v(vz), v(vd)])),
            ],
        )
        .unwrap();
        // ev(X, Y) :- e(X, Y).   od(X, Z) :- ev(X, Y), e(Y, Z).   ev(X, Z) :- od(X, Y), e(Y, Z).
        p.rule(
            atom(ev, &[v(vx), v(vy)]),
            [Literal::Pos(atom(e, &[v(vx), v(vy)]))],
        )
        .unwrap();
        p.rule(
            atom(od, &[v(vx), v(vz)]),
            [
                Literal::Pos(atom(ev, &[v(vx), v(vy)])),
                Literal::Pos(atom(e, &[v(vy), v(vz)])),
            ],
        )
        .unwrap();
        p.rule(
            atom(ev, &[v(vx), v(vz)]),
            [
                Literal::Pos(atom(od, &[v(vx), v(vy)])),
                Literal::Pos(atom(e, &[v(vy), v(vz)])),
            ],
        )
        .unwrap();
        // cnt(X, N) :- N = count (Z) by X: j(X, Y, Z).
        p.aggregate(
            atom(cnt, &[v(vx), v(vn)]),
            Aggregate::count([vx], [vz], vn),
            [Literal::Pos(atom(j, &[v(vx), v(vy), v(vz)]))],
        )
        .unwrap();
        // lo1 / hi1: the least / greatest Y by X over p3, ties by the head then the rest.
        p.aggregate(
            atom(lo1, &[v(vx), v(vy)]),
            Aggregate::min_by([vx], [vd]),
            [Literal::Pos(atom(p3, &[v(vx), v(vy), v(vd)]))],
        )
        .unwrap();
        p.aggregate(
            atom(hi1, &[v(vx), v(vy)]),
            Aggregate::max_by([vx], [vd]),
            [Literal::Pos(atom(p3, &[v(vx), v(vy), v(vd)]))],
        )
        .unwrap();
        // one(X, Z) :- exactly one Z by X: n(X, Z).
        p.aggregate(
            atom(one, &[v(vx), v(vz)]),
            Aggregate::exactly_one([vx], [vz]),
            [Literal::Pos(atom(n, &[v(vx), v(vz)]))],
        )
        .unwrap();
        // none(N) :- N = count (X): x(X, X).   (an empty body still counts 0)
        p.aggregate(
            atom(none, &[v(vn)]),
            Aggregate::count([], [vx], vn),
            [Literal::Pos(atom(x, &[v(vx), v(vx)]))],
        )
        .unwrap();

        let small = 12;
        let mut given = BTreeMap::new();
        given.insert(
            a,
            random_set(&mut g, 160, &[(small, 0), (small, 0), (4, WIDE)]),
        );
        given.insert(
            b,
            random_set(&mut g, 160, &[(4, WIDE), (small, 0), (small, 0)]),
        );
        given.insert(s, random_set(&mut g, 30, &[(60, WIDE)]));
        given.insert(t, random_set(&mut g, 30, &[(60, WIDE)]));
        given.insert(addr, random_set(&mut g, 200, &[(1000, WIDE)]));
        let ranges: Set = (0..40)
            .map(|f| {
                let lo = WIDE + g.below(1000);
                vec![f, lo, lo + g.below(80)]
            })
            .collect();
        given.insert(rng, ranges);
        given.insert(e, random_set(&mut g, 40, &[(30, 0), (30, 0)]));
        given.insert(bad, random_set(&mut g, 4, &[(small, 0)]));
        let mut inputs = Inputs::new();
        for (&r, set) in &given {
            let arity = p.relation_info(r).arity;
            inputs.facts(r, facts_of(arity, set, r == a || r == addr));
        }
        let engine: E = Engine::new(CpuDevice::new(4)).explain(true);
        let out = engine.run(&p, &inputs).await.unwrap();
        let want = plain(&p, &given);
        let derived = [j, n, w, x, h, p3, ev, od, cnt, lo1, hi1, one, none];
        assert_eq!(
            derived.len(),
            p.relations()
                .iter()
                .filter(|i| i.kind == RelKind::Derived)
                .count()
        );
        for rel in derived {
            let name = &p.relation_info(rel).name;
            let got: Set = out.get(rel).unwrap().rows().collect();
            assert_eq!(got, want[&rel], "seed {seed}: {name}");
            assert_eq!(
                out.get(rel).unwrap().len(),
                got.len(),
                "seed {seed}: {name} holds each fact once"
            );
        }
        for rel in [j, n, w, x, h, ev, od, cnt, lo1, hi1, one, none] {
            check_why(&p, &out, &want, rel);
        }
        let joins: Vec<&str> = out.report.strata.iter().map(|s| s.kind).collect();
        assert!(
            joins.contains(&"joins (column kernels)"),
            "the joins run on column kernels: {joins:?}"
        );
        assert!(!want[&j].is_empty() && !want[&w].is_empty() && !want[&cnt].is_empty());
    }
}

#[test]
fn columns_from_arrow_are_used_in_place() {
    let buf = ScalarBuffer::from(vec![WIDE, 2, 3]);
    let f = Facts::from_columns(vec![Column::from(buf.clone())]).unwrap();
    let arr = f.to_arrow(0);
    let arr = arr.as_any().downcast_ref::<UInt64Array>().unwrap();
    assert_eq!(arr.values().as_ptr(), buf.as_ptr(), "no copy out");
    let g = f.clone();
    assert_eq!(
        g.column(0).as_u64().unwrap().as_ptr(),
        buf.as_ptr(),
        "a clone shares the values"
    );
    assert_eq!(arr.len(), 3);
}