crates/kleene-plan/src/eval/same_why.rs
//! The bindings made distinct and the heads added by batch keep each fact's derivation: the
//! why of every fact of generated programs, at several thread counts, equals the why the
//! tests' reference gives (rules run row by row as before, one thread).
use std::sync::Arc;
use kleene_sparse::{CpuBackend, CpuDevice};
use super::Engine;
use crate::facts::{Facts, Inputs};
use crate::rules::{Atom, Cmp, Cond, Literal, Plan, RelId, Term, Value, Var};
use crate::{External, Output, Result};
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, m: u64) -> u64 {
self.next() % m
}
}
fn atom(rel: RelId, terms: &[Var]) -> Atom {
Atom {
rel,
terms: terms.iter().map(|&v| Term::Var(v)).collect(),
}
}
fn pos(rel: RelId, terms: &[Var]) -> Literal {
Literal::Pos(atom(rel, terms))
}
/// Two columns answered by Rust code: by the first column bound, or listed whole. Keys in
/// rising order, rows of a key in stored order.
#[derive(Debug)]
struct Pairs2(Vec<[Value; 2]>);
impl External for Pairs2 {
fn arity(&self) -> usize {
2
}
fn can(&self, bound: u64) -> bool {
bound == 0 || bound == 1
}
#[allow(clippy::needless_range_loop)]
fn lookup(
&self,
bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()> {
for k in 0..n {
for r in &self.0 {
if bound == 0 || r[0] == keys[0][k] {
out(k, r);
}
}
}
Ok(())
}
}
/// A generated program and its inputs: the input relations `e`, `f` (two columns), `h`
/// (three), `g`, `k` (one), the external `x`, and rules of the shapes the batch touches.
/// `n` rows per input, values below `d` (small: many repeats).
fn program(seed: u64, n: usize, d: u64) -> (Plan, Inputs, Inputs, Inputs, Vec<RelId>) {
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let mut p = Plan::new();
let e = p.input("e", 2);
let f = p.input("f", 2);
let h = p.input("h", 3);
let g = p.input("g", 1);
let k = p.input("k", 1);
let x = p.external("x", 2);
let [vx, vy, vz, vg, vw, vr] = ["X", "Y", "Z", "G", "W", "R"].map(|s| p.var(s));
let mut heads = Vec::new();
let mut derived = |p: &mut Plan, name: &str, arity: usize| {
let r = p.derived(name, arity);
heads.push(r);
r
};
// projecting joins, a stratum reading none of its relations (two rules, one head)
let pj = derived(&mut p, "pj", 2);
p.rule(atom(pj, &[vx, vz]), [pos(e, &[vx, vy]), pos(f, &[vy, vz])])
.unwrap();
p.rule(atom(pj, &[vx, vz]), [pos(h, &[vx, vg, vz]), pos(g, &[vg])])
.unwrap();
// the dropped variable before a join of no shared variable
let jr = derived(&mut p, "jr", 2);
p.rule(
atom(jr, &[vr, vw]),
[pos(h, &[vr, vy, vg]), pos(g, &[vg]), pos(k, &[vw])],
)
.unwrap();
// a recursion projecting the middle column away
let wk = derived(&mut p, "wk", 2);
p.rule(atom(wk, &[vr, vy]), [pos(e, &[vr, vy])]).unwrap();
p.rule(
atom(wk, &[vr, vy]),
[pos(wk, &[vr, vx]), pos(h, &[vx, vg, vy])],
)
.unwrap();
// conditions: a comparison, and a range (no pass before it is checked)
let cd = derived(&mut p, "cd", 2);
p.rule(
atom(cd, &[vx, vz]),
[
pos(e, &[vx, vy]),
pos(f, &[vy, vz]),
Literal::Cond(Cond::Cmp {
left: Term::Var(vx),
op: Cmp::Lt,
right: Term::Var(vz),
}),
],
)
.unwrap();
let rg = derived(&mut p, "rg", 2);
p.rule(
atom(rg, &[vx, vw]),
[
pos(e, &[vx, vy]),
pos(k, &[vw]),
Literal::Cond(Cond::Within {
x: Term::Var(vw),
lo: Term::Var(vx),
hi: Term::Var(vy),
}),
],
)
.unwrap();
// negation of a variable no longer needed by the head
let ng = derived(&mut p, "ng", 2);
p.rule(
atom(ng, &[vx, vz]),
[
pos(e, &[vx, vy]),
pos(f, &[vy, vz]),
Literal::Neg(atom(g, &[vy])),
],
)
.unwrap();
// externals: asked by a bound column, then a variable they bind dropped
let xt = derived(&mut p, "xt", 2);
p.rule(atom(xt, &[vx, vw]), [pos(e, &[vx, vy]), pos(x, &[vy, vw])])
.unwrap();
let xg = derived(&mut p, "xg", 1);
p.rule(
atom(xg, &[vx]),
[pos(e, &[vx, vy]), pos(x, &[vy, vw]), pos(g, &[vw])],
)
.unwrap();
// an external that ties two atoms sharing no variable (asked with both bound, or
// between them)
let tie = derived(&mut p, "tie", 2);
p.rule(
atom(tie, &[vr, vz]),
[pos(g, &[vr]), pos(x, &[vr, vx]), pos(f, &[vx, vz])],
)
.unwrap();
// the head's variable from one atom, the rows cut by the others and a negation
let fl = derived(&mut p, "fl", 1);
p.rule(
atom(fl, &[vr]),
[
pos(e, &[vr, vy]),
pos(f, &[vy, vx]),
pos(k, &[vx]),
Literal::Neg(atom(g, &[vx])),
],
)
.unwrap();
// two variables of two atoms read together only by a negation
let lo = derived(&mut p, "lo", 1);
p.rule(
atom(lo, &[vx]),
[
pos(e, &[vx, vy]),
pos(f, &[vy, vz]),
pos(h, &[vy, vw, vg]),
Literal::Cond(Cond::Cmp {
left: Term::Var(vz),
op: Cmp::Ne,
right: Term::Var(vx),
}),
Literal::Neg(atom(f, &[vz, vw])),
],
)
.unwrap();
// an atom tied to the first by conditions, another tied by nothing
let fs = derived(&mut p, "fs", 2);
p.rule(
atom(fs, &[vr, vw]),
[
pos(e, &[vr, vy]),
pos(k, &[vw]),
pos(f, &[vw, vz]),
Literal::Cond(Cond::Cmp {
left: Term::Var(vy),
op: Cmp::Lt,
right: Term::Var(vz),
}),
],
)
.unwrap();
// a value between two ends from the other side: two comparisons (a sort and a search),
// beside an equal key, and between parts linked by the comparisons alone (the ends'
// part joined first)
let cmp = |a: Var, op: Cmp, b: Var| {
Literal::Cond(Cond::Cmp {
left: Term::Var(a),
op,
right: Term::Var(b),
})
};
let bd = derived(&mut p, "bd", 1);
p.rule(
atom(bd, &[vx]),
[
pos(e, &[vx, vy]),
pos(h, &[vw, vz, vg]),
cmp(vz, Cmp::Le, vy),
cmp(vg, Cmp::Gt, vy),
],
)
.unwrap();
let bk = derived(&mut p, "bk", 2);
p.rule(
atom(bk, &[vx, vg]),
[
pos(e, &[vx, vy]),
pos(h, &[vx, vz, vg]),
cmp(vz, Cmp::Lt, vy),
cmp(vy, Cmp::Le, vg),
],
)
.unwrap();
let bw = derived(&mut p, "bw", 1);
p.rule(
atom(bw, &[vw]),
[
pos(f, &[vw, vy]),
pos(h, &[vw, vz, vg]),
Literal::Cond(Cond::Within {
x: Term::Var(vy),
lo: Term::Var(vz),
hi: Term::Var(vg),
}),
],
)
.unwrap();
let bc = derived(&mut p, "bc", 2);
p.rule(
atom(bc, &[vx, vr]),
[
pos(g, &[vx]),
pos(e, &[vx, vy]),
pos(k, &[vr]),
pos(h, &[vr, vz, vg]),
cmp(vy, Cmp::Ge, vz),
cmp(vy, Cmp::Lt, vg),
],
)
.unwrap();
// a recursion reading a projecting relation of a lower stratum
let up = derived(&mut p, "up", 2);
p.rule(atom(up, &[vx, vz]), [pos(pj, &[vx, vz])]).unwrap();
p.rule(
atom(up, &[vx, vz]),
[pos(up, &[vx, vy]), pos(pj, &[vy, vz]), pos(g, &[vy])],
)
.unwrap();
let mut rows = |arity: usize, n: usize| -> Vec<Vec<Value>> {
(0..n)
.map(|_| (0..arity).map(|_| rng.below(d)).collect())
.collect()
};
let facts = |r: Vec<Vec<Value>>, arity: usize| Facts::from_rows(arity, r).unwrap();
let (re, rf, rh) = (rows(2, n), rows(2, n), rows(3, n));
let (rg_, rk) = (rows(1, n / 4 + 1), rows(1, n / 8 + 1));
let rx: Vec<[Value; 2]> = rows(2, n).into_iter().map(|r| [r[0], r[1]]).collect();
let more = rows(2, n / 5 + 1);
let mut inputs = Inputs::new();
inputs
.facts(e, facts(re.clone(), 2))
.facts(f, facts(rf, 2))
.facts(h, facts(rh, 3))
.facts(g, facts(rg_, 1))
.facts(k, facts(rk, 1))
.external(x, Arc::new(Pairs2(rx)));
// the run to continue from: `e` grown by `more`
let mut added = Inputs::new();
added.facts(e, facts(more.clone(), 2));
let mut grown = inputs.clone();
let mut all = re;
all.extend(more);
grown.facts(e, facts(all, 2));
(p, inputs, grown, added, heads)
}
fn engine(threads: usize, reference: bool, choice: bool) -> Engine<CpuBackend> {
engine_as(threads, reference, choice, true)
}
fn engine_as(threads: usize, reference: bool, choice: bool, explain: bool) -> Engine<CpuBackend> {
let e = Engine::new(CpuDevice::new(threads))
.explain(explain)
.index_choice(choice);
if reference { e.with_reference() } else { e }
}
/// Every fact of `heads` and its why, as `out` has them.
fn whys(p: &Plan, out: &Output, heads: &[RelId]) -> Vec<(RelId, Vec<Value>, String)> {
let mut v = Vec::new();
for &r in heads {
let Some(f) = out.get(r) else { continue };
for t in f.rows() {
let w = out.why(p, r, &t).expect("a why of every fact");
v.push((r, t, format!("{w:?}")));
}
}
v
}
/// Every fact of `heads`, as `out` has them.
fn facts_of(out: &Output, heads: &[RelId]) -> Vec<(RelId, Vec<Vec<Value>>)> {
heads
.iter()
.map(|&r| (r, out.get(r).map_or_else(Vec::new, |f| f.rows().collect())))
.collect()
}
async fn compare(seed: u64, n: usize, d: u64) {
let (p, inputs, grown, added, heads) = program(seed, n, d);
for choice in [true, false] {
let want = engine(1, true, choice).run(&p, &inputs).await.unwrap();
let want_whys = whys(&p, &want, &heads);
assert!(!want_whys.is_empty());
let want_c = engine(1, true, choice)
.continue_from(&p, &want, &grown, &added)
.await
.unwrap();
let want_cw = whys(&p, &want_c, &heads);
for threads in [1, 3, 8] {
let got = engine(threads, false, choice)
.run(&p, &inputs)
.await
.unwrap();
let got_whys = whys(&p, &got, &heads);
assert_eq!(got_whys.len(), want_whys.len(), "seed {seed}: facts");
for (w, g) in want_whys.iter().zip(&got_whys) {
assert_eq!(w, g, "seed {seed}, {threads} threads, choice {choice}");
}
// continued from a run of each kind, with `e` grown
let got_c = engine(threads, false, choice)
.continue_from(&p, &got, &grown, &added)
.await
.unwrap();
assert_eq!(
want_cw,
whys(&p, &got_c, &heads),
"seed {seed}, {threads} threads, continued"
);
// without the why: the same facts (bags made distinct as they double)
let plain = engine_as(threads, false, choice, false)
.run(&p, &inputs)
.await
.unwrap();
assert_eq!(facts_of(&plain, &heads), facts_of(&want, &heads));
}
}
}
#[tokio::test]
async fn the_why_of_every_fact_is_the_reference_one_at_any_thread_count() {
for seed in 1..=6 {
compare(seed, 60 + 30 * seed as usize, 4 + seed).await;
}
}
#[tokio::test]
async fn the_why_is_the_reference_one_on_tables_split_over_the_workers() {
compare(7, 900, 40).await;
}