crates/kleene-plan/tests/index_choice.rs
//! The index choice: a rule's comparisons with constants on an input with an index become a
//! lookup of the index ([`Lookup::choose`], applied by the engine to every rule). Every
//! rewritten shape against the same plan with the choice off (the same answers), the
//! lookups counted; a rule with the index lookup written by hand and the plain rule give
//! the same plan and the same cost (lookups, rows the index hands, facts derived).
use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use arrow_array::{ArrayRef, Int64Array, StringArray, UInt64Array};
use kleene_plan::{
Atom, Bound, Choice, Cmp, Cond, Engine, External, Index, Inputs, Key, Literal, Lookup,
NameIndex, On, Plan, RelId, Source, Term, Type, Value, Var, choose_indexes,
};
use kleene_sparse::{CpuBackend, CpuDevice};
const N: u64 = 200;
fn age(i: u64) -> i64 {
(i as i64 * 37) % 90 - 5
}
fn size(i: u64) -> u64 {
(i * 13) % 50
}
fn name(i: u64) -> String {
format!("f{}", i % 17)
}
/// (lo, hi, id) for the ids whose value lies in lo..=hi, asked with lo and hi bound;
/// counts its lookups and the rows it hands out.
#[derive(Debug)]
struct Range {
pairs: Vec<(Value, u64)>,
asked: Arc<AtomicUsize>,
handed: Arc<AtomicUsize>,
}
impl External for Range {
fn arity(&self) -> usize {
3
}
fn can(&self, bound: u64) -> bool {
bound & 0b11 == 0b11
}
fn lookup(
&self,
_bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> kleene_plan::Result<()> {
for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
self.asked.fetch_add(1, Ordering::Relaxed);
for &(v, id) in &self.pairs {
if (lo..=hi).contains(&v) {
self.handed.fetch_add(1, Ordering::Relaxed);
out(k, &[lo, hi, id]);
}
}
}
Ok(())
}
}
#[derive(Debug)]
struct Names(Arc<AtomicUsize>);
impl NameIndex for Names {
fn nodes(&self, s: &str, out: &mut dyn FnMut(u32)) -> kleene_plan::Result<()> {
self.0.fetch_add(1, Ordering::Relaxed);
for i in 0..N {
if name(i) == s {
out((BASE + i) as u32);
}
}
Ok(())
}
}
fn u(v: impl IntoIterator<Item = u64>) -> ArrayRef {
Arc::new(UInt64Array::from_iter_values(v))
}
fn at(rel: RelId, terms: Vec<Term>) -> Atom {
Atom { rel, terms }
}
fn cmp(x: Var, op: Cmp, c: Value) -> Literal {
Literal::Cond(Cond::Cmp {
left: Term::Var(x),
op,
right: Term::Const(c),
})
}
/// Persons 0..N (ids 1000.. in an id space: a block) with a signed age and a string name,
/// funcs with an unsigned size; the counters of the indexes.
struct World {
plan: Plan,
inputs: Inputs,
person: RelId,
age: RelId,
name: RelId,
size: RelId,
asked: Arc<AtomicUsize>,
handed: Arc<AtomicUsize>,
named: Arc<AtomicUsize>,
size_index: Source,
}
const BASE: u64 = 1000;
fn world() -> World {
let mut plan = Plan::new();
let person = plan.input("person", 1);
let r_age = plan.input_typed("person.age", &[Type::U64, Type::I64]);
let r_name = plan.input_typed("person.name", &[Type::U64, Type::Str]);
let r_size = plan.input("person.size", 2);
let ids = u((0..N).map(|i| BASE + i));
let mut inputs = Inputs::new();
inputs
.columns(person, vec![ids.clone()])
.columns(
r_age,
vec![
ids.clone(),
Arc::new(Int64Array::from_iter_values((0..N).map(age_of))),
],
)
.columns(
r_name,
vec![
ids.clone(),
Arc::new(StringArray::from_iter_values((0..N).map(name_of))),
],
)
.columns(r_size, vec![ids, u((0..N).map(size_of))]);
let (asked, handed, named) = (
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicUsize::new(0)),
);
let ranged = |pairs: Vec<(Value, u64)>| -> Source {
Source::External(Arc::new(Range {
pairs,
asked: asked.clone(),
handed: handed.clone(),
}))
};
let age_codes: Vec<(Value, u64)> = (0..N)
.map(|i| {
(
Type::I64
.encode(&kleene_plan::Datum::I64(age_of(i)), None)
.unwrap(),
BASE + i,
)
})
.collect();
let size_index = ranged((0..N).map(|i| (size_of(i), BASE + i)).collect());
inputs
.index(
r_age,
Index::Range {
lookup: ranged(age_codes),
within: Some("person".into()),
},
)
.index(
r_size,
Index::Range {
lookup: size_index.clone(),
within: Some("person".into()),
},
)
.index(
r_name,
Index::Names {
index: Arc::new(Names(named.clone())),
within: Some("person".into()),
},
)
.index(person, Index::Blocks(vec![(BASE, N)]));
World {
plan,
inputs,
person,
age: r_age,
name: r_name,
size: r_size,
asked,
handed,
named,
size_index,
}
}
fn age_of(i: u64) -> i64 {
age(i)
}
fn size_of(i: u64) -> u64 {
size(i)
}
fn name_of(i: u64) -> String {
name(i)
}
fn engine(on: bool) -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(2)).index_choice(on)
}
/// The rows of `rel`, with the choice on and off (equal), and the lookups asked with it on.
async fn both(w: &World, rel: RelId) -> (BTreeSet<Vec<u64>>, usize, usize) {
let off = engine(false).run(&w.plan, &w.inputs).await.unwrap();
let want: BTreeSet<Vec<u64>> = off.get(rel).unwrap().rows().collect();
let (a0, n0) = (
w.asked.load(Ordering::Relaxed),
w.named.load(Ordering::Relaxed),
);
assert_eq!((a0, n0), (0, 0), "no lookup with the choice off");
let on = engine(true).run(&w.plan, &w.inputs).await.unwrap();
let got: BTreeSet<Vec<u64>> = on.get(rel).unwrap().rows().collect();
assert_eq!(got, want);
let asked = (
w.asked.swap(0, Ordering::Relaxed),
w.named.swap(0, Ordering::Relaxed),
);
w.handed.store(0, Ordering::Relaxed);
(got, asked.0, asked.1)
}
fn ids(f: impl Fn(u64) -> bool) -> BTreeSet<Vec<u64>> {
(0..N).filter(|&i| f(i)).map(|i| vec![BASE + i]).collect()
}
#[test]
fn the_choice_of_a_lookup() {
let range = || {
Some(Index::Range {
lookup: Source::External(Arc::new(Range {
pairs: vec![],
asked: Default::default(),
handed: Default::default(),
})),
within: None,
})
};
let key = |ty| Key {
ty,
indexes: vec![range()],
};
let b = |on, op, value| Bound { on, op, value };
// bounds on an unsigned property; an equality preferred over a range
let lk = Lookup {
props: vec![key(Type::U64), key(Type::U64)],
bounds: vec![
b(On::Prop(0), Cmp::Ge, 10),
b(On::Prop(0), Cmp::Lt, 50),
b(On::Prop(1), Cmp::Eq, 7),
],
..Lookup::default()
};
assert_eq!(
lk.choose(&[]),
Some(Choice::Range {
prop: 1,
lo: 7,
hi: 7,
eq: true
})
);
let lk = Lookup {
props: vec![key(Type::U64)],
bounds: vec![b(On::Prop(0), Cmp::Ge, 10), b(On::Prop(0), Cmp::Lt, 50)],
..Lookup::default()
};
assert_eq!(
lk.choose(&[]),
Some(Choice::Range {
prop: 0,
lo: 10,
hi: 49,
eq: false
})
);
// a typed property: the null code is never in the range
let lk = Lookup {
props: vec![key(Type::I64)],
bounds: vec![b(On::Prop(0), Cmp::Gt, 3)],
..Lookup::default()
};
assert!(
matches!(lk.choose(&[]), Some(Choice::Range { hi, .. }) if hi == kleene_plan::NULL - 1)
);
// only `<>`, no index, a holder without one: none
let ne = |props| Lookup {
props,
bounds: vec![b(On::Prop(0), Cmp::Ne, 3)],
..Lookup::default()
};
assert_eq!(ne(vec![key(Type::U64)]).choose(&[]), None);
let half = Key {
ty: Type::U64,
indexes: vec![range(), None],
};
let lk = Lookup {
props: vec![half],
bounds: vec![b(On::Prop(0), Cmp::Eq, 3)],
..Lookup::default()
};
assert_eq!(lk.choose(&[]), None);
// an OR of equalities: a lookup per value
let lk = Lookup {
props: vec![key(Type::U64)],
ors: vec![vec![b(On::Prop(0), Cmp::Eq, 5), b(On::Prop(0), Cmp::Eq, 7)]],
..Lookup::default()
};
assert_eq!(
lk.choose(&[]),
Some(Choice::At {
prop: 0,
values: vec![5, 7]
})
);
// id bounds on blocks first
let lk = Lookup {
props: vec![key(Type::U64)],
blocks: Some(vec![(0, 10)]),
bounds: vec![b(On::Id, Cmp::Ge, 3), b(On::Prop(0), Cmp::Eq, 1)],
..Lookup::default()
};
assert_eq!(
lk.choose(&[]),
Some(Choice::Ids {
wanted: vec![(3, u64::MAX)]
})
);
// a string equality by its name index, over a range
let names = Key {
ty: Type::Str,
indexes: vec![Some(Index::Names {
index: Arc::new(Names(Default::default())),
within: None,
})],
};
let lk = Lookup {
props: vec![key(Type::U64), names],
bounds: vec![b(On::Prop(0), Cmp::Eq, 4), b(On::Prop(1), Cmp::Eq, 1)],
..Lookup::default()
};
let strings = ["a".to_string(), "lex".to_string()];
assert_eq!(
lk.choose(&strings),
Some(Choice::Names {
prop: 1,
names: vec!["lex".into()]
})
);
}
#[tokio::test]
async fn every_shape_gives_the_answers_of_the_plan_as_written() {
// young(N) :- person(N), person.age(N, A), A < 30, A >= 0.
let mut w = world();
let young = w.plan.derived("young", 1);
let (n, a) = (w.plan.var("N"), w.plan.var("A"));
w.plan
.rule(
at(young, vec![Term::Var(n)]),
[
Literal::Pos(at(w.person, vec![Term::Var(n)])),
Literal::Pos(at(w.age, vec![Term::Var(n), Term::Var(a)])),
Literal::Cond(Cond::Cmp {
left: Term::Var(a),
op: Cmp::Lt,
right: Term::int(30),
}),
Literal::Cond(Cond::Cmp {
left: Term::Var(a),
op: Cmp::Ge,
right: Term::int(0),
}),
],
)
.unwrap();
let (rows, asked, _) = both(&w, young).await;
assert_eq!(rows, ids(|i| (0..30).contains(&age(i))));
assert_eq!(asked, 1);
// the label atom gave its place to the found ids
let (q, _, chosen) = choose_indexes(&w.plan, &w.inputs).unwrap().unwrap();
let rule = q.rule_at(chosen[0].rule);
assert!(
!rule.body.iter().any(|x| x.rel == w.person),
"{}",
q.show_rule(chosen[0].rule)
);
assert!(rule.body.iter().any(|x| x.rel == chosen[0].found));
// sized(N) :- person.size(N, 7). (a constant in the atom)
let mut w = world();
let sized = w.plan.derived("sized", 1);
let n = w.plan.var("N");
w.plan
.rule(
at(sized, vec![Term::Var(n)]),
[at(w.size, vec![Term::Var(n), Term::Const(7)])],
)
.unwrap();
let (rows, asked, _) = both(&w, sized).await;
assert_eq!(rows, ids(|i| size(i) == 7));
assert_eq!(asked, 1);
// named(N, S) :- person.name(N, "f3"), person.size(N, S), S > 10. (a name lookup)
let mut w = world();
let named = w.plan.derived("named", 2);
let (n, s) = (w.plan.var("N"), w.plan.var("S"));
let f3 = w.plan.str("f3");
w.plan
.rule(
at(named, vec![Term::Var(n), Term::Var(s)]),
[
Literal::Pos(at(w.name, vec![Term::Var(n), f3])),
Literal::Pos(at(w.size, vec![Term::Var(n), Term::Var(s)])),
cmp(s, Cmp::Gt, 10),
],
)
.unwrap();
let (rows, asked, by_name) = both(&w, named).await;
let want: BTreeSet<Vec<u64>> = (0..N)
.filter(|&i| name(i) == "f3" && size(i) > 10)
.map(|i| vec![BASE + i, size(i)])
.collect();
assert_eq!(rows, want);
assert_eq!((asked, by_name), (0, 1));
// some(N) :- person(N), N >= BASE + 20, N < BASE + 25. (ids from the block)
let mut w = world();
let some = w.plan.derived("some", 1);
let n = w.plan.var("N");
w.plan
.rule(
at(some, vec![Term::Var(n)]),
[
Literal::Pos(at(w.person, vec![Term::Var(n)])),
Literal::Cond(Cond::Within {
x: Term::Var(n),
lo: Term::Const(BASE + 20),
hi: Term::Const(BASE + 25),
}),
],
)
.unwrap();
let (rows, ..) = both(&w, some).await;
assert_eq!(rows, ids(|i| (20..25).contains(&i)));
let (q, ..) = choose_indexes(&w.plan, &w.inputs).unwrap().unwrap();
assert!(!q.rules()[0].body.iter().any(|x| x.rel == w.person));
// not by an index: only `<>`; an empty range finds nothing
let mut w = world();
let ne = w.plan.derived("ne", 1);
let empty = w.plan.derived("empty", 1);
let (n, s) = (w.plan.var("N"), w.plan.var("S"));
let body = |op1, c1, op2, c2| {
[
Literal::Pos(at(w.size, vec![Term::Var(n), Term::Var(s)])),
cmp(s, op1, c1),
cmp(s, op2, c2),
]
};
let ne_body = body(Cmp::Ne, 3, Cmp::Ne, 4);
let empty_body = body(Cmp::Gt, 30, Cmp::Le, 30);
w.plan.rule(at(ne, vec![Term::Var(n)]), ne_body).unwrap();
w.plan
.rule(at(empty, vec![Term::Var(n)]), empty_body)
.unwrap();
let (rows, asked, _) = both(&w, ne).await;
assert_eq!(rows, ids(|i| ![3, 4].contains(&size(i))));
assert_eq!(asked, 1, "the empty range alone is a lookup");
let (rows, ..) = both(&w, empty).await;
assert!(rows.is_empty());
}
/// The index lookup written by hand (`hand(N) :- idx(10, 19, N), person.size(N, S),
/// S >= 10, S < 20`) and the plain rule (`plain(N) :- person(N), person.size(N, S), S >= 10,
/// S < 20`): the same answers, the same lookups, the same rows from the index, the same
/// facts derived.
#[tokio::test]
async fn a_lookup_written_by_hand_and_the_plain_rule_cost_the_same() {
let run = |hand: bool| async move {
let mut w = world();
let out = w.plan.derived("out", 1);
let (n, s) = (w.plan.var("N"), w.plan.var("S"));
let mut body: Vec<Literal> = vec![
Literal::Pos(at(w.size, vec![Term::Var(n), Term::Var(s)])),
cmp(s, Cmp::Ge, 10),
cmp(s, Cmp::Lt, 20),
];
if hand {
let idx = w.plan.external("size index", 3);
w.inputs.set(idx, w.size_index.clone());
body.insert(
0,
Literal::Pos(at(
idx,
vec![Term::Const(10), Term::Const(19), Term::Var(n)],
)),
);
} else {
body.insert(0, Literal::Pos(at(w.person, vec![Term::Var(n)])));
}
w.plan.rule(at(out, vec![Term::Var(n)]), body).unwrap();
let o = engine(true).run(&w.plan, &w.inputs).await.unwrap();
let rows: BTreeSet<Vec<u64>> = o.get(out).unwrap().rows().collect();
let facts: usize = o.report.strata.iter().map(|s| s.facts).sum();
let shapes: Vec<&str> = o.report.strata.iter().map(|s| s.kind).collect();
(
rows,
w.asked.load(Ordering::Relaxed),
w.handed.load(Ordering::Relaxed),
facts,
shapes.join(", "),
)
};
let hand = run(true).await;
let plain = run(false).await;
assert_eq!(hand.0, ids(|i| (10..20).contains(&size(i))));
assert_eq!(hand, plain);
assert_eq!(plain.1, 1, "one lookup");
assert_eq!(
plain.2,
hand.0.len(),
"the index hands the rows found, no more"
);
}