crates/kleene-datalog/tests/continue_with.rs
//! A run continued from an earlier run on inputs that lost rows as well as gained them
//! (`Engine::continue_with`) derives what a run from scratch on the new inputs derives,
//! relation for relation, with proofs that check against the new inputs: joins and
//! recursions of joins delete what the lost rows derived and derive again what still has a
//! proof, counts subtract the counts of the lost bindings, a negation over a relation that
//! lost rows continues when what it negates is as it was; a reach and a closure that lost
//! rows run again. Many random changes against the run from scratch, the index choice on.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use arrow_array::{ArrayRef, UInt64Array};
use kleene_datalog::{
Catalog, Engine, Facts, How, Inputs, Output, Program, Proof, Rel, RelId, Source, Term, lt,
};
use kleene_sparse::{CpuBackend, CpuDevice};
type E = Engine<CpuBackend>;
fn pairs(e: &[(u32, u32)]) -> Facts {
Facts::from_rows(2, e.iter().map(|&(a, b)| vec![a, b])).unwrap()
}
fn ones(xs: &[u32]) -> Facts {
Facts::from_rows(1, xs.iter().map(|&x| vec![x])).unwrap()
}
/// `r` reached from the seeds `s` (a reach), `tc` the closure of `e`, `p` the pairs of `e`
/// joined with themselves to a fixed point (a recursion of joins, not linear), `path` the
/// a linear recursion from the seeds (`path(S, Y)`: `Y` reached from seed `S`, a blocked
/// vertex not passed into but by the first edge),
/// `hop` the pairs two edges apart (a join), `free` the `p` sources that are not `blocked`
/// (a negation), `deg(X, N)` the successors of each `X` in `p`, counted, `fan(X, N)` the
/// edges out of each `X`, counted.
struct Prog {
p: Program,
e: Rel<2>,
s: Rel<1>,
blocked: Rel<1>,
out: Vec<(String, RelId)>,
}
fn program() -> Prog {
let mut p = Program::new();
let e = p.input::<2>("e");
let s = p.input::<1>("s");
let blocked = p.input::<1>("blocked");
let r = p.derived::<1>("r");
let tc = p.derived::<2>("tc");
let pp = p.derived::<2>("p");
let path = p.derived::<2>("path");
let hop = p.derived::<2>("hop");
let free = p.derived::<1>("free");
let deg = p.derived_counted::<2>("deg");
let fan = p.derived_counted::<2>("fan");
let [x, y, z, n] = ["X", "Y", "Z", "N"].map(|v| p.var(v));
p.rule(r.at([y]), [s.at([y])]).unwrap();
p.rule(r.at([y]), [r.at([x]), e.at([x, y])]).unwrap();
p.rule(tc.at([x, y]), [e.at([x, y])]).unwrap();
p.rule(tc.at([x, z]), [tc.at([x, y]), e.at([y, z])])
.unwrap();
p.rule(pp.at([x, y]), [e.at([x, y])]).unwrap();
p.rule(pp.at([x, z]), [pp.at([x, y]), pp.at([y, z])])
.unwrap();
p.rule(path.at([x, y]), [s.at([x]), e.at([x, y])]).unwrap();
p.rule(
path.at([x, z]),
[
path.at([x, y]).into(),
e.at([y, z]).into(),
!blocked.at([z]),
],
)
.unwrap();
p.rule(hop.at([x, z]), [e.at([x, y]), e.at([y, z])])
.unwrap();
p.rule(free.at([x]), [pp.at([x, y]).into(), !blocked.at([x])])
.unwrap();
p.count_rule(deg.at([x, n]), [pp.at([x, y])]).unwrap();
p.count_rule(fan.at([x, n]), [e.at([x, y])]).unwrap();
let out = [
("r", r.id()),
("tc", tc.id()),
("p", pp.id()),
("path", path.id()),
("hop", hop.id()),
("free", free.id()),
("deg", deg.id()),
("fan", fan.id()),
]
.map(|(n, id)| (n.to_string(), id))
.to_vec();
Prog {
p,
e,
s,
blocked,
out,
}
}
fn inputs(g: &Prog, e: &[(u32, u32)], s: &[u32], blocked: &[u32]) -> Inputs {
let mut ins = Inputs::new();
ins.facts(&g.e, pairs(e)).unwrap();
ins.facts(&g.s, ones(s)).unwrap();
ins.facts(&g.blocked, ones(blocked)).unwrap();
ins
}
fn rows(o: &Output, rel: RelId) -> BTreeSet<Vec<u64>> {
o.get_id(rel)
.map(|f| f.rows().collect())
.unwrap_or_default()
}
/// Every derived fact of `o` has a proof whose leaves are input facts of `ins` and whose
/// steps derive facts `o` holds.
fn proofs_check(g: &Prog, o: &Output, ins: &BTreeMap<RelId, BTreeSet<Vec<u64>>>) {
fn check(g: &Prog, o: &Output, q: &Proof, ins: &BTreeMap<RelId, BTreeSet<Vec<u64>>>) {
match &q.how {
How::Input => assert!(ins[&q.rel].contains(&q.tuple), "{}", q.render(&g.p)),
How::Rule { premises, .. } => {
assert!(rows(o, q.rel).contains(&q.tuple), "{}", q.render(&g.p));
for s in premises {
check(g, o, s, ins);
}
}
_ => {}
}
}
for (name, rel) in &g.out {
for t in rows(o, *rel) {
let q = o
.why_id(&g.p, *rel, &t)
.unwrap_or_else(|| panic!("no proof of {name}{t:?}"));
check(g, o, &q, ins);
assert!(!o.render(&g.p, &q).is_empty());
}
}
}
fn facts(g: &Prog, e: &[(u32, u32)], s: &[u32], b: &[u32]) -> BTreeMap<RelId, BTreeSet<Vec<u64>>> {
BTreeMap::from([
(g.e.id(), pairs(e).rows().collect()),
(g.s.id(), ones(s).rows().collect()),
(g.blocked.id(), ones(b).rows().collect()),
])
}
/// Which strata of `o` continued (by their relations' names).
fn continued(o: &Output) -> BTreeMap<String, bool> {
o.report
.strata
.iter()
.map(|s| (s.relations.join(","), s.continued))
.collect()
}
/// The inputs as rows: what `to` has that `from` lacks, and the other way round.
type Pairs = Vec<(u32, u32)>;
fn moved(from: &[(u32, u32)], to: &[(u32, u32)]) -> (Pairs, Pairs) {
let (a, b): (BTreeSet<_>, BTreeSet<_>) = (from.iter().collect(), to.iter().collect());
(
b.difference(&a).map(|x| **x).collect(),
a.difference(&b).map(|x| **x).collect(),
)
}
/// A run continued from `before` on `(e1, s1, b1)`, the change given as rows gained and
/// lost, equals the run from scratch there; proofs check when the engine explains.
#[allow(clippy::too_many_arguments)]
async fn step(
g: &Prog,
engine: &E,
before: &Output,
(e0, s0, b0): (&[(u32, u32)], &[u32], &[u32]),
(e1, s1, b1): (&[(u32, u32)], &[u32], &[u32]),
explain: bool,
) -> Output {
let (ea, er) = moved(e0, e1);
let one = |x: &[u32]| x.iter().map(|&v| (v, 0)).collect::<Vec<_>>();
let (sa, sr) = moved(&one(s0), &one(s1));
let (ba, br) = moved(&one(b0), &one(b1));
let firsts = |v: Vec<(u32, u32)>| v.into_iter().map(|x| x.0).collect::<Vec<u32>>();
let mut added = Inputs::new();
let mut removed = Inputs::new();
added.facts(&g.e, pairs(&ea)).unwrap();
added.facts(&g.s, ones(&firsts(sa))).unwrap();
added.facts(&g.blocked, ones(&firsts(ba))).unwrap();
removed.facts(&g.e, pairs(&er)).unwrap();
removed.facts(&g.s, ones(&firsts(sr))).unwrap();
removed.facts(&g.blocked, ones(&firsts(br))).unwrap();
let ins = inputs(g, e1, s1, b1);
let next = engine
.continue_with(&g.p, before, &ins, &added, &removed)
.await
.unwrap();
let scratch = engine.run(&g.p, &ins).await.unwrap();
for (name, rel) in &g.out {
assert_eq!(
rows(&next, *rel),
rows(&scratch, *rel),
"{name}: from {e0:?} {s0:?} {b0:?} to {e1:?} {s1:?} {b1:?}"
);
}
if explain {
proofs_check(g, &next, &facts(g, e1, s1, b1));
}
next
}
#[tokio::test]
async fn a_run_continued_on_rows_lost_derives_what_a_run_from_scratch_derives() {
let g = program();
let e0 = [
(0, 1),
(1, 2),
(2, 0),
(2, 3),
(3, 4),
(5, 6),
(6, 7),
(1, 7),
];
let s0 = [0, 5];
let b0 = [2];
for explain in [false, true] {
let engine: E = Engine::new(CpuDevice::new(2)).explain(explain);
let first = engine.run(&g.p, &inputs(&g, &e0, &s0, &b0)).await.unwrap();
// 1: an edge of the circle and a bridge lost, one edge gained
let e1 = [
(0, 1),
(2, 0),
(2, 3),
(3, 4),
(5, 6),
(6, 7),
(1, 7),
(4, 8),
];
let next = step(
&g,
&engine,
&first,
(&e0, &s0, &b0),
(&e1, &s0, &b0),
explain,
)
.await;
let c = continued(&next);
assert!(
!c["r"] && !c["tc"],
"a reach and a closure that lost rows run again: {c:?}"
);
for k in ["p", "path", "hop", "free", "deg", "fan"] {
// (explained, the counted `deg` and `fan` count again: their proofs keep each
// rule's rows)
let counted = k == "deg" || k == "fan";
assert!(c[k] != (explain && counted), "{k} continues: {c:?}");
}
// what was derived through the lost edge (1, 2) and has no other proof is gone; what
// has another proof stays
let p = rows(&next, g.out[2].1);
assert!(!p.contains(&vec![1, 2]) && !p.contains(&vec![1, 0]));
assert!(p.contains(&vec![2, 1]) && p.contains(&vec![2, 4]));
// 2: a seed lost: `path` derives again only what the other seed reaches
let s2 = [5];
let next2 = step(
&g,
&engine,
&next,
(&e1, &s0, &b0),
(&e1, &s2, &b0),
explain,
)
.await;
let paths = rows(&next2, g.out[3].1);
assert!(paths.iter().all(|t| t[0] == 5), "{paths:?}");
assert!(continued(&next2)["path"]);
// 3: what the negation negates lost a row: `free` runs again, the rest continue
let b3: [u32; 0] = [];
let next3 = step(
&g,
&engine,
&next2,
(&e1, &s2, &b0),
(&e1, &s2, &b3),
explain,
)
.await;
let c = continued(&next3);
// (explained, a counted relation is kept or counts again)
assert!(
!c["free"] && !c["path"] && c["p"] && (c["deg"] || explain),
"{c:?}"
);
// 4: everything lost
step(
&g,
&engine,
&next3,
(&e1, &s2, &b3),
(&[], &[], &[]),
explain,
)
.await;
}
}
/// A small deterministic stream of numbers below `m`.
fn numbers(seed: u64, len: usize, m: u32) -> Vec<u32> {
let mut x = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x % u64::from(m)) as u32
})
.collect()
}
#[tokio::test]
async fn many_random_changes_continue_as_runs_from_scratch() {
let g = program();
for explain in [false, true] {
let engine: E = Engine::new(CpuDevice::new(2)).explain(explain);
for seed in 0..12u64 {
let n = 14;
let a = numbers(seed, 24, n);
let b = numbers(seed + 50, 24, n);
let mut e: Vec<(u32, u32)> = a.iter().copied().zip(b.iter().copied()).collect();
let mut s = vec![numbers(seed + 7, 1, n)[0]];
let mut bl = numbers(seed + 9, 2, n);
let mut out = engine.run(&g.p, &inputs(&g, &e, &s, &bl)).await.unwrap();
for round in 0..4u64 {
let k = seed * 10 + round;
// lose about a fifth of the edges, gain a few, move a seed and a block
let drop = numbers(k + 100, 5, e.len().max(1) as u32);
let mut e1: Vec<(u32, u32)> = e
.iter()
.enumerate()
.filter(|(i, _)| !drop.contains(&(*i as u32)))
.map(|(_, x)| *x)
.collect();
let na = numbers(k + 200, 3, n);
let nb = numbers(k + 300, 3, n);
e1.extend(na.into_iter().zip(nb));
e1.sort_unstable();
e1.dedup();
let s1 = if round % 2 == 0 {
vec![s[0], numbers(k, 1, n)[0]]
} else {
vec![s[0]]
};
let bl1 = if round == 2 { Vec::new() } else { bl.clone() };
out = step(&g, &engine, &out, (&e, &s, &bl), (&e1, &s1, &bl1), explain).await;
(e, s, bl) = (e1, s1, bl1);
}
}
}
}
#[tokio::test]
async fn the_index_choice_continues_on_rows_lost() {
let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
let catalog = |calls: &[(u64, u64)]| {
let mut c = Catalog::new();
c.label("func", Source::Columns(vec![u((0..20).collect())]))
.id_block("func", 0, 20)
.edge(
"calls",
Source::Columns(vec![
u(calls.iter().map(|x| x.0).collect()),
u(calls.iter().map(|x| x.1).collect()),
]),
);
c
};
let mut p = Program::new();
let c0 = catalog(&[(0, 1), (1, 2), (2, 3), (3, 9), (12, 13)]);
let func = p.input_from::<1>(&c0, "func").unwrap();
let calls = p.input_from::<2>(&c0, "calls").unwrap();
let low = p.derived::<1>("low");
let reach = p.derived::<2>("reach");
let two = p.derived::<2>("two");
let [f, g, h] = ["F", "G", "H"].map(|v| p.var(v));
p.rule(low.at([f]), [func.at([f]).into(), lt(f, Term::Const(8))])
.unwrap();
p.rule(reach.at([f, g]), [low.at([f]), calls.at([f, g])])
.unwrap();
p.rule(reach.at([f, h]), [reach.at([f, g]), calls.at([g, h])])
.unwrap();
// a join over the graph input (deleted and derived again, the graph read at the rows
// the deleted facts name)
p.rule(two.at([f, h]), [calls.at([f, g]), calls.at([g, h])])
.unwrap();
let bind = |c: &Catalog| {
let mut ins = Inputs::new();
ins.bind(&p, c).unwrap();
ins
};
for on in [false, true] {
let engine: E = Engine::new(CpuDevice::new(2))
.index_choice(on)
.explain(true);
let first = engine.run(&p, &bind(&c0)).await.unwrap();
let now = [(0, 1), (2, 3), (3, 9), (12, 13), (1, 3)];
let c1 = catalog(&now);
let next = engine
.continue_with(
&p,
&first,
&bind(&c1),
&bind(&catalog(&[(1, 3)])),
&bind(&catalog(&[(1, 2)])),
)
.await
.unwrap();
let scratch = engine.run(&p, &bind(&c1)).await.unwrap();
for rel in [low.id(), reach.id(), two.id()] {
assert_eq!(rows(&next, rel), rows(&scratch, rel), "choice {on}");
}
assert!(!rows(&next, reach.id()).contains(&vec![0, 2]));
assert!(rows(&next, reach.id()).contains(&vec![0, 9]));
let t = rows(&next, two.id());
assert_eq!(t, BTreeSet::from([vec![0, 3], vec![1, 9], vec![2, 9]]));
assert!(
next.report
.strata
.iter()
.any(|s| s.relations == ["two"] && s.continued),
"choice {on}"
);
for row in &t {
let q = next.why_id(&p, two.id(), row).expect("a proof");
assert!(!next.render(&p, &q).is_empty());
}
assert!(
next.report.strata.iter().any(|s| s.continued),
"choice {on}"
);
let q = next.why_id(&p, reach.id(), &[0, 9]).expect("a proof");
assert!(q.steps() >= 3, "{}", next.render(&p, &q));
}
}