crates/kleene-datalog/tests/set_numbers.rs
//! A number for each distinct set, in the rule text and the builder: `sets state/2 limit
//! 1000.` declares a table of sets, `N = set(X) by (K) in state` numbers each key's set in
//! it. The order's state machine (the subset construction over labelled edges and edges
//! without a label), the plain form, the limit, the proofs and the build errors; each answer
//! checked against a plain loop over the same rows, at 1 and 8 threads and twice in a row.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use arrow_array::{ArrayRef, StringArray, UInt64Array};
use kleene_datalog::{
Aggregate, DEFAULT_SET_LIMIT, DatalogError, Datum, Engine, Facts, Inputs, Output, Part,
Program, Rel, RuleId, Value, datalog, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};
fn engine(threads: usize) -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(threads)).explain(true)
}
/// The order's graph: `edge(X, Label, Z)`, `eps(X, Z)` (an edge without a label),
/// `start(K, X)`.
const EDGES: [(u64, &str, u64); 4] = [(1, "a", 2), (1, "a", 3), (3, "b", 1), (4, "b", 4)];
const EPS: [(u64, u64); 1] = [(2, 4)];
const STARTS: [(u64, u64); 1] = [(0, 1)];
/// The relations of the order's program, the labels as text.
#[derive(Clone, Copy)]
struct Machine {
edge: Rel<3>,
eps: Rel<2>,
start: Rel<2>,
step: Rel<3>,
state: Rel<2>,
first: Rel<2>,
}
/// The relations given in Rust (the label column is a string): the same in both twins.
fn given(p: &mut Program) -> (Rel<3>, Rel<2>, Rel<2>, Rel<3>) {
use kleene_datalog::Type::{Str, U64};
let edge = p.input_typed("edge", [U64, Str, U64]);
let eps = p.input::<2>("eps");
let start = p.input::<2>("start");
let step = p.derived_typed("step", [U64, Str, U64]);
(edge, eps, start, step)
}
/// The order's rules in the text, the table's limit `$limit`.
macro_rules! machine_text {
($limit:tt) => {{
let mut p = Program::new();
let (edge, eps, start, step) = given(&mut p);
let r = datalog!(&mut p =>
sets state/2 limit $limit.
derived clo/2, first/2.
clo(X, X) :- start(_, X).
clo(Z, Z) :- edge(_, _, Z).
clo(X, Z) :- clo(X, Y), eps(Y, Z).
first(K, N) :- N = set(X) by (K) in state: start(K, S), clo(S, X).
step(P, A, N) :- N = set(Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).
rounds first: keep, step: keep, state: keep.
)
.unwrap();
let m = Machine {
edge,
eps,
start,
step,
state: r.state,
first: r.first,
};
(p, m)
}};
}
/// The same program through the builder, its variables made in the order the text first
/// writes them; with the ids of its rules.
fn machine_builder() -> (Program, Machine, Vec<RuleId>) {
let mut p = Program::new();
let (edge, eps, start, step) = given(&mut p);
let x = p.var("X");
let w1 = p.var("_");
let z = p.var("Z");
let (w2, w3) = (p.var("_"), p.var("_"));
let y = p.var("Y");
let (k, n, s) = (p.var("K"), p.var("N"), p.var("S"));
let (pp, a) = (p.var("P"), p.var("A"));
let state = p.sets::<2>("state", Some(1000));
let clo = p.derived::<2>("clo");
let first = p.derived::<2>("first");
let rules = vec![
p.rule(clo.at([x, x]), [start.at([w1, x])]).unwrap(),
p.rule(clo.at([z, z]), [edge.at([w2, w3, z])]).unwrap(),
p.rule(clo.at([x, z]), [clo.at([x, y]), eps.at([y, z])])
.unwrap(),
p.aggregate(
first.at([k, n]),
Aggregate::set_number([k], [x], n, state.id()),
[start.at([k, s]), clo.at([s, x])],
)
.unwrap(),
p.aggregate(
step.at([pp, a, n]),
Aggregate::set_number([pp, a], [y], n, state.id()),
[state.at([pp, x]), edge.at([x, a, z]), clo.at([z, y])],
)
.unwrap(),
];
p.rounds([
(first.id(), Part::Keep),
(step.id(), Part::Keep),
(state.id(), Part::Keep),
])
.unwrap();
let m = Machine {
edge,
eps,
start,
step,
state,
first,
};
(p, m, rules)
}
fn inputs(m: &Machine) -> Inputs {
let mut inp = Inputs::new();
let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
inp.columns(
&m.edge,
[
u(EDGES.iter().map(|e| e.0).collect()),
Arc::new(StringArray::from_iter_values(EDGES.iter().map(|e| e.1))),
u(EDGES.iter().map(|e| e.2).collect()),
],
);
inp.facts(
&m.eps,
Facts::from_rows(2, EPS.map(|e| [e.0, e.1])).unwrap(),
)
.unwrap();
inp.facts(
&m.start,
Facts::from_rows(2, STARTS.map(|e| [e.0, e.1])).unwrap(),
)
.unwrap();
inp
}
/// A state machine: the sets by number, the steps `(state, label, state)`, the starts
/// `(key, state)`.
type Answer = (
BTreeMap<u64, BTreeSet<u64>>,
BTreeSet<(u64, String, u64)>,
BTreeSet<(u64, u64)>,
);
fn rows<const N: usize>(out: &Output, rel: &Rel<N>) -> BTreeSet<Vec<Value>> {
out.get(rel).map(|f| f.rows().collect()).unwrap_or_default()
}
fn answer(p: &Program, m: &Machine, out: &Output) -> Answer {
let mut sets: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
for r in rows(out, &m.state) {
sets.entry(r[0]).or_default().insert(r[1]);
}
let steps = out
.datums(p, &m.step)
.unwrap_or_default()
.into_iter()
.map(|[a, l, b]| match (a, l, b) {
(Datum::U64(a), Datum::Str(l), Datum::U64(b)) => (a, l, b),
other => panic!("not a step: {other:?}"),
})
.collect();
let firsts = rows(out, &m.first)
.into_iter()
.map(|r| (r[0], r[1]))
.collect();
(sets, steps, firsts)
}
/// The subset construction as a plain loop: each round numbers its new sets in rising order
/// of their sorted members, from the count so far.
fn reference() -> Answer {
let clo = |x: u64| {
let mut c = BTreeSet::from([x]);
loop {
let more: Vec<u64> = EPS
.iter()
.filter(|e| c.contains(&e.0) && !c.contains(&e.1))
.map(|e| e.1)
.collect();
if more.is_empty() {
return c;
}
c.extend(more);
}
};
let mut numbers: BTreeMap<BTreeSet<u64>, u64> = BTreeMap::new();
let number_new = |found: Vec<BTreeSet<u64>>, numbers: &mut BTreeMap<_, u64>| {
let new: BTreeSet<BTreeSet<u64>> = found
.into_iter()
.filter(|s| !numbers.contains_key(s))
.collect();
let mut fresh = Vec::new();
for s in new {
let n = numbers.len() as u64;
numbers.insert(s, n);
fresh.push(n);
}
fresh
};
let starts: Vec<(u64, BTreeSet<u64>)> = STARTS.iter().map(|&(k, x)| (k, clo(x))).collect();
let mut frontier = number_new(starts.iter().map(|s| s.1.clone()).collect(), &mut numbers);
let firsts = starts.iter().map(|(k, s)| (*k, numbers[s])).collect();
let mut steps = BTreeSet::new();
while !frontier.is_empty() {
let mut found: BTreeMap<(u64, &str), BTreeSet<u64>> = BTreeMap::new();
for &q in &frontier {
let members = numbers
.iter()
.find(|e| *e.1 == q)
.expect("numbered")
.0
.clone();
for &(x, l, z) in &EDGES {
if members.contains(&x) {
found.entry((q, l)).or_default().extend(clo(z));
}
}
}
frontier = number_new(found.values().cloned().collect(), &mut numbers);
for ((q, l), s) in found {
steps.insert((q, l.to_string(), numbers[&s]));
}
}
let sets = numbers.into_iter().map(|(s, n)| (n, s)).collect();
(sets, steps, firsts)
}
/// a. The order's test in the rule text: 4 states, 5 steps, the same numbers at 1 and 8
/// threads and twice in a row.
#[tokio::test]
async fn the_order_state_machine_in_the_text() {
let (p, m) = machine_text!(1000);
let inp = inputs(&m);
let want: Answer = (
BTreeMap::from([
(0, BTreeSet::from([1])),
(1, BTreeSet::from([2, 3, 4])),
(2, BTreeSet::from([1, 4])),
(3, BTreeSet::from([4])),
]),
BTreeSet::from([
(0, "a".to_string(), 1),
(1, "b".to_string(), 2),
(2, "a".to_string(), 1),
(2, "b".to_string(), 3),
(3, "b".to_string(), 3),
]),
BTreeSet::from([(0, 0)]),
);
assert_eq!(reference(), want);
for threads in [1, 8, 1, 8] {
let out = engine(threads).run(&p, &inp).await.unwrap();
assert_eq!(answer(&p, &m, &out), want, "at {threads} threads");
}
}
/// b. The builder twin: the same relations, rules, variables, rounds and strata; the rules
/// print as the text writes them; the same facts and proofs.
#[tokio::test]
async fn the_builder_gives_the_plan_of_the_text() {
let (a, ma) = machine_text!(1000);
let (b, mb, rules) = machine_builder();
assert_eq!(
format!("{:?}", a.relations()),
format!("{:?}", b.relations())
);
assert_eq!(a.rules(), b.rules());
assert_eq!(a.round_groups(), b.round_groups());
assert_eq!(a.set_limit(ma.state.id()), Some(1000));
assert_eq!(b.set_limit(mb.state.id()), Some(1000));
assert_eq!(plan(&a).unwrap(), plan(&b).unwrap());
let shown: Vec<String> = rules.iter().map(|&r| a.show_rule(r)).collect();
assert_eq!(
shown,
[
"clo(X, X) :- start(_, X).",
"clo(Z, Z) :- edge(_, _, Z).",
"clo(X, Z) :- clo(X, Y), eps(Y, Z).",
"first(K, N) :- N = set (X) by (K) in state: start(K, S), clo(S, X).",
"step(P, A, N) :- N = set (Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).",
]
);
let shown_b: Vec<String> = rules.iter().map(|&r| b.show_rule(r)).collect();
assert_eq!(shown, shown_b);
let inp = inputs(&ma);
let oa = engine(2).run(&a, &inp).await.unwrap();
let ob = engine(2).run(&b, &inp).await.unwrap();
assert_eq!(answer(&a, &ma, &oa), answer(&b, &mb, &ob));
for (sa, sb) in rows(&oa, &ma.state).iter().zip(rows(&ob, &mb.state).iter()) {
let pa = oa.why_id(&a, ma.state.id(), sa).expect("a proof");
let pb = ob.why_id(&b, mb.state.id(), sb).expect("a proof");
assert_eq!(oa.render(&a, &pa), ob.render(&b, &pb));
}
}
/// c. The plain form: no recursion, no `rounds` line; equal sets share a number, the table
/// read back as `sets(N, E)`.
#[tokio::test]
async fn equal_sets_share_a_number() {
let (p, r) = datalog! {
input member/2.
sets sets/2.
derived id/2, back/2.
id(K, N) :- N = set(E) by (K) in sets: member(K, E).
back(N, E) :- sets(N, E).
}
.unwrap();
assert_eq!(p.set_limit(r.sets.id()), Some(DEFAULT_SET_LIMIT));
let member: [[u64; 2]; 7] = [
[10, 1],
[10, 2],
[11, 2],
[11, 1],
[12, 3],
[13, 1],
[13, 1],
];
let mut inp = Inputs::new();
inp.facts(&r.member, Facts::from_rows(2, member).unwrap())
.unwrap();
// the plain loop: each key's set, the distinct sets numbered by their sorted members
let mut of: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
for [k, e] in member {
of.entry(k).or_default().insert(e);
}
let distinct: BTreeSet<&BTreeSet<u64>> = of.values().collect();
let number = |s: &BTreeSet<u64>| distinct.iter().position(|d| *d == s).unwrap() as u64;
let want_id: BTreeSet<Vec<Value>> = of.iter().map(|(k, s)| vec![*k, number(s)]).collect();
let want_sets: BTreeSet<Vec<Value>> = distinct
.iter()
.flat_map(|s| s.iter().map(|&e| vec![number(s), e]))
.collect();
assert_eq!(
want_id,
BTreeSet::from([vec![10, 1], vec![11, 1], vec![12, 2], vec![13, 0]])
);
for threads in [1, 8, 1] {
let out = engine(threads).run(&p, &inp).await.unwrap();
assert_eq!(rows(&out, &r.id), want_id);
assert_eq!(rows(&out, &r.sets), want_sets);
assert_eq!(rows(&out, &r.back), want_sets);
}
}
/// d. The limit: the order's graph needs 4 sets; a table of 3 stops the run by name.
#[tokio::test]
async fn over_the_limit_the_run_stops() {
let (p, m) = machine_text!(3);
assert_eq!(p.set_limit(m.state.id()), Some(3));
for threads in [1, 8] {
let e = engine(threads)
.run(&p, &inputs(&m))
.await
.expect_err("4 sets need a limit of 4");
match &e {
DatalogError::SetLimit { table, limit } => {
assert_eq!((table.as_str(), *limit), ("state", 3));
}
other => panic!("not SetLimit: {other}"),
}
assert_eq!(e.to_string(), "sets `state`: more than 3 sets");
}
let (p4, m4) = machine_text!(4);
assert!(engine(2).run(&p4, &inputs(&m4)).await.is_ok());
}
/// e. The proofs: a step shows its key's member rows, each proven, and the set's number; a
/// row of the table shows the numbered fact that first gave its set.
#[tokio::test]
async fn the_proofs_show_the_members_and_the_first() {
let (p, m) = machine_text!(1000);
let out = engine(2).run(&p, &inputs(&m)).await.unwrap();
let rendered = |d: [Datum; 3]| {
let q = out.why_of(&p, &m.step, d).expect("a proof");
out.render(&p, &q)
};
// the first step: its key (0, "a") has three member rows, each proven
assert_eq!(
rendered([Datum::U64(0), Datum::Str("a".into()), Datum::U64(1)]),
"\
step(0, \"a\", 1) [step(P, A, N) :- N = set (Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).] (set 1 of `state`, 3 members) [round 1]
- P=0 X=1 A=\"a\" Z=2 Y=2
state(0, 1) [set 0, first given by]
first(0, 0) [first(K, N) :- N = set (X) by (K) in state: start(K, S), clo(S, X).] (set 0 of `state`, 1 member) [round 1]
- K=0 S=1 X=1
start(0, 1) [input]
clo(1, 1) [clo(X, X) :- start(_, X).]
start(0, 1) [input]
edge(1, \"a\", 2) [input]
clo(2, 2) [clo(Z, Z) :- edge(_, _, Z).]
edge(1, \"a\", 2) [input]
- P=0 X=1 A=\"a\" Z=2 Y=4
state(0, 1) [set 0, first given by]
first(0, 0) [first(K, N) :- N = set (X) by (K) in state: start(K, S), clo(S, X).] (set 0 of `state`, 1 member) [round 1]
- K=0 S=1 X=1
start(0, 1) [input]
clo(1, 1) [clo(X, X) :- start(_, X).]
start(0, 1) [input]
edge(1, \"a\", 2) [input]
clo(2, 4) [clo(X, Z) :- clo(X, Y), eps(Y, Z).]
clo(2, 2) [clo(Z, Z) :- edge(_, _, Z).]
edge(1, \"a\", 2) [input]
eps(2, 4) [input]
- P=0 X=1 A=\"a\" Z=3 Y=3
state(0, 1) [set 0, first given by]
first(0, 0) [first(K, N) :- N = set (X) by (K) in state: start(K, S), clo(S, X).] (set 0 of `state`, 1 member) [round 1]
- K=0 S=1 X=1
start(0, 1) [input]
clo(1, 1) [clo(X, X) :- start(_, X).]
start(0, 1) [input]
edge(1, \"a\", 3) [input]
clo(3, 3) [clo(Z, Z) :- edge(_, _, Z).]
edge(1, \"a\", 3) [input]
"
);
// a later step: its member's state row goes back to the step that first gave it
let later = rendered([Datum::U64(2), Datum::Str("b".into()), Datum::U64(3)]);
assert!(
later.starts_with(
"\
step(2, \"b\", 3) [step(P, A, N) :- N = set (Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).] (set 3 of `state`, 1 member) [round 3]
- P=2 X=4 A=\"b\" Z=4 Y=4
state(2, 4) [set 2, first given by]
step(1, \"b\", 2) [step(P, A, N) :- N = set (Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).] (set 2 of `state`, 2 members) [round 2]
"
),
"{later}"
);
let set = out.why(&p, &m.state, [0u64, 1]).expect("a proof");
assert_eq!(
out.render(&p, &set),
"\
state(0, 1) [set 0, first given by]
first(0, 0) [first(K, N) :- N = set (X) by (K) in state: start(K, S), clo(S, X).] (set 0 of `state`, 1 member) [round 1]
- K=0 S=1 X=1
start(0, 1) [input]
clo(1, 1) [clo(X, X) :- start(_, X).]
start(0, 1) [input]
"
);
}
/// f. The build errors the core gives where the text cannot see the table (a program in
/// hand): numbering into a relation that is not a table of sets, a table as a rule's head,
/// a table as a `fresh` part. The text's own build errors are pinned in the macro crate's
/// tests and in the reference (`compile_fail`).
#[test]
fn the_core_refuses_by_name() {
let mut p = Program::new();
let member = p.input::<2>("member");
let other = p.derived::<2>("other");
let table = p.sets::<2>("table", None);
let message = |e: DatalogError| e.to_string();
let e = datalog!(&mut p =>
derived id/2.
id(K, N) :- N = set(X) by (K) in other: member(K, X).
)
.unwrap_err();
assert_eq!(
message(e),
"program: `id` numbers into `other`, which is not a table of sets (Plan::sets)"
);
let e = datalog!(&mut p => table(K, X) :- member(K, X).).unwrap_err();
assert_eq!(
message(e),
"program: `table` is a table of sets: no rule derives it; rules number into it (set number)"
);
let e = datalog!(&mut p =>
derived id2/2.
id2(K, N) :- N = set(X) by (K) in table: member(K, X), table(_, X).
rounds id2: keep, table: fresh.
)
.unwrap_err();
assert_eq!(
message(e),
"program: `table` is a table of sets: it keeps every set it numbered, so its part is keep, not fresh"
);
}
/// Recursion through the table without its `rounds` line: the plan is refused, and the
/// error names the line (the heads in the order the relations were declared: `step` is
/// declared in Rust before the text declares `first`).
#[test]
fn recursion_through_the_table_needs_its_rounds_line() {
let mut p = Program::new();
let (edge, eps, start, step) = given(&mut p);
datalog!(&mut p =>
sets state/2.
derived clo/2, first/2.
clo(X, X) :- start(_, X).
clo(Z, Z) :- edge(_, _, Z).
clo(X, Z) :- clo(X, Y), eps(Y, Z).
first(K, N) :- N = set(X) by (K) in state: start(K, S), clo(S, X).
step(P, A, N) :- N = set(Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).
)
.unwrap();
assert_eq!(
plan(&p).unwrap_err().to_string(),
"program: the recursion through the table of sets `state` runs as a group of rounds \
(Plan::rounds); it needs the line: rounds step: keep, first: keep, state: keep."
);
}
/// The core's helper through the builder (`Program::state_machine`): the same rows as the
/// order's rules in the text, and each state once.
#[tokio::test]
async fn the_helper_gives_the_rows_of_the_text() {
let (tp, tm) = machine_text!(1000);
let want = answer(&tp, &tm, &engine(2).run(&tp, &inputs(&tm)).await.unwrap());
let mut p = Program::new();
let (edge, eps, start, _) = given(&mut p);
let h = p
.state_machine("nfa", &edge, Some(&eps), &start, Some(1000))
.unwrap();
assert_eq!(p.relation_info(h.step.id()).name, "nfa.step");
assert_eq!(p.set_limit(h.member.id()), Some(1000));
let m = Machine {
edge,
eps,
start,
step: h.step,
state: h.member,
first: h.start,
};
for threads in [1, 8] {
let out = engine(threads).run(&p, &inputs(&m)).await.unwrap();
assert_eq!(answer(&p, &m, &out), want);
let states: BTreeSet<Vec<Value>> = rows(&out, &h.state);
assert_eq!(states, (0..4).map(|n| vec![n]).collect());
}
}