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

//! Joins that project a variable away: the bindings a rule carries are made one where they
//! differ only in variables no longer needed, and the why keeps one derivation row per
//! fact, not one per binding (the engine's counters [`StratumReport::peak_rows`] and
//! [`StratumReport::proof_rows`]).

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

use kleene_plan::{
    Atom, Cmp, Cond, Engine, External, Facts, Inputs, Literal, Output, Plan, RelId, StratumReport,
    Term, Value, Var,
};
use kleene_sparse::{CpuBackend, CpuDevice};

fn atom<const K: usize>(rel: RelId, terms: [Var; K]) -> Atom {
    Atom {
        rel,
        terms: terms.iter().map(|&v| Term::Var(v)).collect(),
    }
}

fn report<'a>(out: &'a Output, name: &str) -> &'a StratumReport {
    out.report
        .strata
        .iter()
        .find(|s| s.relations.iter().any(|r| r == name))
        .expect("the stratum")
}

/// `jret(R, A, S, CT) :- up(R, A, S, G), taken(G), blind(G), holes(CT).`: each (R, A, S)
/// of `up` holds `per` values of G, so the join holds `per` bindings for each fact; a
/// stratum whose rule does not read its own relation. Returns the plan, its inputs, the
/// head, and the number of rows of the largest input.
fn jret(rows: u32, per: u32, holes: u32) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let up = p.input("up", 4);
    let taken = p.input("taken", 1);
    let blind = p.input("blind", 1);
    let hole = p.input("holes", 1);
    let jret = p.derived("jret", 4);
    let [r, a, s, g, ct] = ["R", "A", "S", "G", "CT"].map(|n| p.var(n));
    p.rule(
        atom(jret, [r, a, s, ct]),
        [
            atom(up, [r, a, s, g]),
            atom(taken, [g]),
            atom(blind, [g]),
            atom(hole, [ct]),
        ],
    )
    .unwrap();
    let gs = rows * per + 7;
    let up_rows: Vec<[u32; 4]> = (0..rows)
        .flat_map(|x| (0..per).map(move |k| [x, x % 7, x % 3, (x * per + k) % gs]))
        .collect();
    let mut inputs = Inputs::new();
    inputs
        .facts(up, Facts::from_rows(4, up_rows).unwrap())
        .facts(taken, Facts::from_rows(1, (0..gs).map(|x| [x])).unwrap())
        .facts(blind, Facts::from_rows(1, (0..gs).map(|x| [x])).unwrap())
        .facts(
            hole,
            Facts::from_rows(1, (0..holes).map(|x| [1000 + x])).unwrap(),
        );
    let largest = (gs as usize).max(holes as usize);
    (p, inputs, jret, largest)
}

/// `ret(R, NX) :- up(R, G), dcall(G, NX).`: the variable dropped by the last join step,
/// many G of each R calling into a few return addresses.
fn dcall(rows: u32, per: u32, calls: u32, targets: u32) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let up = p.input("up", 2);
    let dcall = p.input("dcall", 2);
    let ret = p.derived("ret", 2);
    let [r, g, nx] = ["R", "G", "NX"].map(|n| p.var(n));
    p.rule(atom(ret, [r, nx]), [atom(up, [r, g]), atom(dcall, [g, nx])])
        .unwrap();
    let gs = 997u32;
    let up_rows: Vec<[u32; 2]> = (0..rows)
        .flat_map(|x| (0..per).map(move |k| [x, (x * 31 + k * 17) % gs]))
        .collect();
    let calls_rows: Vec<[u32; 2]> = (0..gs)
        .flat_map(|g| (0..calls).map(move |k| [g, (g + k * 5) % targets]))
        .collect();
    let largest = up_rows.len().max(calls_rows.len());
    let mut inputs = Inputs::new();
    inputs
        .facts(up, Facts::from_rows(2, up_rows).unwrap())
        .facts(dcall, Facts::from_rows(2, calls_rows).unwrap());
    (p, inputs, ret, largest)
}

/// `walked(R, X) :- start(R, X).  walked(R, Y) :- walked(R, X), step(X, G, Y).`: a
/// recursion whose step projects the edge's middle column away (many G per hop).
fn walked(starts: u32, nodes: u32, per: u32) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let start = p.input("start", 2);
    let step = p.input("step", 3);
    let walked = p.derived("walked", 2);
    let [r, x, g, y] = ["R", "X", "G", "Y"].map(|n| p.var(n));
    p.rule(atom(walked, [r, x]), [atom(start, [r, x])]).unwrap();
    p.rule(
        atom(walked, [r, y]),
        [atom(walked, [r, x]), atom(step, [x, g, y])],
    )
    .unwrap();
    let step_rows: Vec<[u32; 3]> = (0..nodes)
        .flat_map(|x| {
            (0..per).flat_map(move |k| [[x, k, (x + 1) % nodes], [x, k + per, (x * 3) % nodes]])
        })
        .collect();
    let largest = step_rows.len();
    let mut inputs = Inputs::new();
    inputs
        .facts(
            start,
            Facts::from_rows(2, (0..starts).map(|s| [s, s % nodes])).unwrap(),
        )
        .facts(step, Facts::from_rows(3, step_rows).unwrap());
    (p, inputs, walked, largest)
}

fn pos<const K: usize>(rel: RelId, terms: [Var; K]) -> Literal {
    Literal::Pos(atom(rel, terms))
}

fn neg<const K: usize>(rel: RelId, terms: [Var; K]) -> Literal {
    Literal::Neg(atom(rel, terms))
}

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

/// Two columns answered by Rust code by the first column bound (or listed whole).
#[derive(Debug)]
struct ByFirst(Vec<[Value; 2]>);

impl External for ByFirst {
    fn arity(&self) -> usize {
        2
    }

    fn can(&self, bound: u64) -> bool {
        bound & 1 == 1 || bound == 0
    }

    #[allow(clippy::needless_range_loop)]
    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        for k in 0..n {
            for r in &self.0 {
                if bound & 1 == 0 || r[0] == keys[0][k] {
                    out(k, r);
                }
            }
        }
        Ok(())
    }
}

/// `place(A, F, L) :- need(A), at(A, X), row(X, F, L).` with `at` external: the two atoms
/// read from facts share no variable, the external ties them.
fn place(needs: u64, rows: u64) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let need = p.input("need", 1);
    let at = p.external("at", 2);
    let row = p.input("row", 3);
    let place = p.derived("place", 3);
    let [a, x, f, l] = ["A", "X", "F", "L"].map(|n| p.var(n));
    p.rule(
        atom(place, [a, f, l]),
        [atom(need, [a]), atom(at, [a, x]), atom(row, [x, f, l])],
    )
    .unwrap();
    let xs = rows / 2;
    let at_rows: Vec<[Value; 2]> = (0..needs)
        .flat_map(|a| [[a, (a * 7) % xs], [a, (a * 7 + 1) % xs]])
        .collect();
    let mut inputs = Inputs::new();
    inputs
        .facts(need, Facts::from_rows(1, (0..needs).map(|a| [a])).unwrap())
        .facts(
            row,
            Facts::from_rows(3, (0..rows).map(|i| [i % xs, i, 5000 + i / 3])).unwrap(),
        )
        .external(at, Arc::new(ByFirst(at_rows)));
    (p, inputs, place, rows as usize)
}

/// `fail(H) :- ok(H, F), cl(F, I), reached(I), !body(I).`: the head's variable comes from
/// the first atom alone, the closure of each function joined after it.
fn failed(holes: u64, funcs: u64, per: u64) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let ok = p.input("ok", 2);
    let cl = p.input("cl", 2);
    let reached = p.input("reached", 1);
    let body = p.input("body", 1);
    let fail = p.derived("fail", 1);
    let [h, f, i] = ["H", "F", "I"].map(|n| p.var(n));
    p.rule(
        atom(fail, [h]),
        [
            pos(ok, [h, f]),
            pos(cl, [f, i]),
            pos(reached, [i]),
            neg(body, [i]),
        ],
    )
    .unwrap();
    let insts = funcs * per;
    let cl_rows: Vec<[u64; 2]> = (0..funcs)
        .flat_map(|f| (0..per).map(move |k| [f, (f * 3 + k * 11) % insts]))
        .collect();
    let largest = cl_rows.len().max(insts as usize);
    let mut inputs = Inputs::new();
    inputs
        .facts(
            ok,
            Facts::from_rows(2, (0..holes).map(|h| [h, h % funcs])).unwrap(),
        )
        .facts(cl, Facts::from_rows(2, cl_rows).unwrap())
        .facts(
            reached,
            Facts::from_rows(1, (0..insts).map(|i| [i])).unwrap(),
        )
        .facts(
            body,
            Facts::from_rows(1, (0..insts).filter(|i| i % 97 != 0).map(|i| [i])).unwrap(),
        );
    (p, inputs, fail, largest)
}

/// `loose(S) :- ret(S, R), pair(E, S, R), pair(E, A, S), A != S, A != R, aft(S, E, X),
/// !pair(E, A, X).`: two variables bound by two atoms, read together only by the negation.
fn loose(sites: u64, before: u64, after: u64) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let ret = p.input("ret", 2);
    let pair = p.input("pair", 3);
    let aft = p.input("aft", 3);
    let loose = p.derived("loose", 1);
    let [s, r, e, a, x] = ["S", "R", "E", "A", "X"].map(|n| p.var(n));
    p.rule(
        atom(loose, [s]),
        [
            pos(ret, [s, r]),
            pos(pair, [e, s, r]),
            pos(pair, [e, a, s]),
            cmp(a, Cmp::Ne, s),
            cmp(a, Cmp::Ne, r),
            pos(aft, [s, e, x]),
            neg(pair, [e, a, x]),
        ],
    )
    .unwrap();
    // site s returns at 1_000_000 + s, in entry e = s; `before` sites lead into it and
    // `after` sites follow its return; of the pairs from before to after only a few
    let mut pairs: Vec<[u64; 3]> = Vec::new();
    let mut afts: Vec<[u64; 3]> = Vec::new();
    for s in 0..sites {
        let (e, r) = (s, 1_000_000 + s);
        pairs.push([e, s, r]);
        for b in 0..before {
            let a = 2_000_000 + s * before + b;
            pairs.push([e, a, s]);
            for k in 0..after {
                let x = 3_000_000 + s * after + k;
                if k == 0 && s % 2 == 0 {
                    pairs.push([e, a, x]);
                }
            }
        }
        for k in 0..after {
            afts.push([s, e, 3_000_000 + s * after + k]);
        }
    }
    let largest = pairs.len();
    let mut inputs = Inputs::new();
    inputs
        .facts(
            ret,
            Facts::from_rows(2, (0..sites).map(|s| [s, 1_000_000 + s])).unwrap(),
        )
        .facts(pair, Facts::from_rows(3, pairs).unwrap())
        .facts(aft, Facts::from_rows(3, afts).unwrap());
    (p, inputs, loose, largest)
}

/// `fscope(F, SC) :- hf(F, FS, FE), scope(SC, 0), srange(SC, LO, HI), LO < FE, FS < HI.`:
/// the conditions that tie the function to a scope read the third atom, and the second
/// shares nothing with the first.
fn fscope(funcs: u64, tops: u64, nested: u64) -> (Plan, Inputs, RelId, usize) {
    let mut p = Plan::new();
    let hf = p.input("hf", 3);
    let scope = p.input("scope", 2);
    let srange = p.input("srange", 3);
    let fscope = p.derived("fscope", 2);
    let [f, fs, fe, sc, lo, hi] = ["F", "FS", "FE", "SC", "LO", "HI"].map(|n| p.var(n));
    p.rule(
        atom(fscope, [f, sc]),
        [
            pos(hf, [f, fs, fe]),
            Literal::Pos(Atom {
                rel: scope,
                terms: vec![Term::Var(sc), Term::Const(0)],
            }),
            pos(srange, [sc, lo, hi]),
            cmp(lo, Cmp::Lt, fe),
            cmp(fs, Cmp::Lt, hi),
        ],
    )
    .unwrap();
    let scope_rows: Vec<[u64; 2]> = (0..tops)
        .map(|s| [s, 0])
        .chain((0..nested).map(|s| [tops + s, 1 + s % tops]))
        .collect();
    let range_rows: Vec<[u64; 3]> = (0..tops)
        .map(|s| [s, (s % funcs) * 10, (s % funcs) * 10 + 5])
        .chain((0..nested).map(|s| [tops + s, 100_000 + s * 10, 100_000 + s * 10 + 5]))
        .collect();
    let largest = range_rows.len();
    let mut inputs = Inputs::new();
    inputs
        .facts(
            hf,
            Facts::from_rows(3, (0..funcs).map(|f| [f, f * 10, f * 10 + 10])).unwrap(),
        )
        .facts(scope, Facts::from_rows(2, scope_rows).unwrap())
        .facts(srange, Facts::from_rows(3, range_rows).unwrap());
    (p, inputs, fscope, largest)
}

async fn run(p: &Plan, inputs: &Inputs, threads: usize, explain: bool) -> Output {
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads)).explain(explain);
    engine.run(p, inputs).await.unwrap()
}

/// The rows of `rel`, and the counters of its stratum, at 1 and 4 threads, explained or
/// not: the facts the same everywhere, the bindings carried never more than the facts or
/// the largest input, one derivation row per fact.
async fn check(p: &Plan, inputs: &Inputs, rel: RelId, name: &str, largest: usize) {
    let mut want: Option<BTreeSet<Vec<u64>>> = None;
    for threads in [1, 4] {
        for explain in [false, true] {
            let out = run(p, inputs, threads, explain).await;
            let facts: BTreeSet<Vec<u64>> = out.get(rel).unwrap().rows().collect();
            match &want {
                Some(w) => assert_eq!(&facts, w),
                None => want = Some(facts.clone()),
            }
            let r = report(&out, name);
            let bound = facts.len().max(largest);
            assert!(
                r.peak_rows <= bound,
                "{name}: {} rows carried, past {bound} (facts {}, largest input {largest}); \
                 threads {threads}, explain {explain}",
                r.peak_rows,
                facts.len()
            );
            if explain {
                assert_eq!(
                    r.proof_rows,
                    facts.len(),
                    "{name}: derivation rows written against facts; threads {threads}"
                );
                for t in &facts {
                    assert!(out.why(p, rel, t).is_some(), "{name}: no why of {t:?}");
                }
            } else {
                assert_eq!(r.proof_rows, 0);
            }
        }
    }
}

#[tokio::test]
async fn a_join_that_projects_a_variable_away_carries_and_proves_each_fact_once() {
    let (p, inputs, rel, largest) = jret(50, 20, 1200);
    check(&p, &inputs, rel, "jret", largest).await;
}

#[tokio::test]
async fn a_last_step_that_drops_a_variable_carries_each_fact_once() {
    let (p, inputs, rel, largest) = dcall(400, 30, 40, 50);
    check(&p, &inputs, rel, "ret", largest).await;
}

#[tokio::test]
async fn a_recursion_that_projects_a_variable_away_carries_each_fact_once() {
    let (p, inputs, rel, largest) = walked(300, 200, 25);
    check(&p, &inputs, rel, "walked", largest).await;
}

#[tokio::test]
async fn an_external_that_ties_two_atoms_is_asked_before_they_would_cross() {
    let (p, inputs, rel, largest) = place(60, 2000);
    check(&p, &inputs, rel, "place", largest).await;
}

#[tokio::test]
async fn a_variable_only_the_head_reads_joins_after_the_atoms_that_cut_the_rows() {
    let (p, inputs, rel, largest) = failed(2000, 20, 200);
    check(&p, &inputs, rel, "fail", largest).await;
}

#[tokio::test]
async fn a_negation_cuts_the_rows_where_its_variables_are_bound() {
    let (p, inputs, rel, largest) = loose(40, 30, 30);
    check(&p, &inputs, rel, "loose", largest).await;
}

#[tokio::test]
async fn an_atom_tied_by_conditions_comes_before_an_atom_tied_by_nothing() {
    let (p, inputs, rel, largest) = fscope(300, 400, 3600);
    check(&p, &inputs, rel, "fscope", largest).await;
}

/// `walk(Y) :- start(Y).`, `walk(Z) :- walk(Y), big(Y, Z).`, `big(X, Y) :- e(X, Y).`,
/// `big(X, Y) :- walk(X), e(X, Y).`: one stratum (big and walk read each other) whose
/// relation `big` holds most of its rows from the first round, while `walk` grows by one
/// node a round along a chain of `steps` nodes; `noise` more edges far from the chain.
fn grows(steps: u32, noise: u32) -> (Plan, Inputs, RelId, RelId) {
    let mut p = Plan::new();
    let start = p.input("start", 1);
    let e = p.input("e", 2);
    let walk = p.derived("walk", 1);
    let big = p.derived("big", 2);
    let [x, y, z] = ["X", "Y", "Z"].map(|n| p.var(n));
    p.rule(atom(walk, [y]), [atom(start, [y])]).unwrap();
    p.rule(atom(walk, [z]), [atom(walk, [y]), atom(big, [y, z])])
        .unwrap();
    p.rule(atom(big, [x, y]), [atom(e, [x, y])]).unwrap();
    p.rule(atom(big, [x, y]), [atom(walk, [x]), atom(e, [x, y])])
        .unwrap();
    let far = 1_000_000;
    let edges: Vec<[u32; 2]> = (0..steps)
        .map(|k| [k, k + 1])
        .chain((0..noise).map(|k| [far + k, far + (k * 7 + 1) % noise]))
        .collect();
    let mut inputs = Inputs::new();
    inputs
        .facts(start, Facts::from_rows(1, [[0u32]]).unwrap())
        .facts(e, Facts::from_rows(2, edges).unwrap());
    (p, inputs, walk, big)
}

#[tokio::test]
async fn a_relation_read_whole_as_it_grows_is_indexed_once_not_every_round() {
    let (steps, noise) = (100, 5000);
    let (p, inputs, walk, big) = grows(steps, noise);
    let mut want: Option<BTreeSet<Vec<u64>>> = None;
    for threads in [1, 4] {
        for explain in [false, true] {
            let out = run(&p, &inputs, threads, explain).await;
            let facts: BTreeSet<Vec<u64>> = out.get(walk).unwrap().rows().collect();
            assert_eq!(facts.len(), steps as usize + 1);
            match &want {
                Some(w) => assert_eq!(&facts, w),
                None => want = Some(facts.clone()),
            }
            let r = report(&out, "walk");
            assert!(r.rounds >= steps, "{} rounds", r.rounds);
            let held = out.get(big).unwrap().len() + facts.len() + (steps + noise) as usize;
            assert!(
                r.indexed_rows <= 6 * held,
                "{} rows indexed over {} rounds, past 6 x {held}; threads {threads}, explain \
                 {explain}",
                r.indexed_rows,
                r.rounds
            );
        }
    }
}