crates/kleene-datalog/tests/index_choice.rs
//! The index choice from the Datalog side: a program binds a catalog's relations by name
//! (their indexes come with them) and writes plain rules; the engine finds the ids by the
//! indexes. The same answers with the choice off; the plain rule costs what the rule with
//! the index lookup written by hand costs (lookups, rows from the index, facts derived).
use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use arrow_array::{ArrayRef, UInt64Array};
use kleene_datalog::{Catalog, Engine, External, Inputs, Program, Source, Term, Value, ge, lt};
use kleene_sparse::{CpuBackend, CpuDevice};
const N: u64 = 300;
const BASE: u64 = 40;
fn size(i: u64) -> u64 {
(i * 7) % 60
}
/// (lo, hi, id) for the ids whose size lies in lo..=hi; counts lookups and rows handed.
#[derive(Debug)]
struct SizeIndex {
asked: Arc<AtomicUsize>,
handed: Arc<AtomicUsize>,
}
impl External for SizeIndex {
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_datalog::Result<()> {
for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
self.asked.fetch_add(1, Ordering::Relaxed);
for i in 0..N {
if (lo..=hi).contains(&size(i)) {
self.handed.fetch_add(1, Ordering::Relaxed);
out(k, &[lo, hi, BASE + i]);
}
}
}
Ok(())
}
}
struct Counts {
asked: Arc<AtomicUsize>,
handed: Arc<AtomicUsize>,
}
/// Functions with ids `BASE..BASE + N` (an id block) and a size with a range index.
fn catalog() -> (Catalog, Counts, Source) {
let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
let ids = u((BASE..BASE + N).collect());
let counts = Counts {
asked: Arc::new(AtomicUsize::new(0)),
handed: Arc::new(AtomicUsize::new(0)),
};
let index = Source::External(Arc::new(SizeIndex {
asked: counts.asked.clone(),
handed: counts.handed.clone(),
}));
let mut c = Catalog::new();
c.label("func", Source::Columns(vec![ids.clone()]))
.id_block("func", BASE, N)
.property(
"func",
"size",
Source::Columns(vec![ids, u((0..N).map(size).collect())]),
)
.property_index("func", "size", index.clone());
(c, counts, index)
}
/// `mid(F) :- func(F), func.size(F, S), S >= 20, S < 30.` and `low(F) :- func(F), F < 50.`:
/// the rows, the lookups asked, the rows the index handed, the facts derived.
async fn run(
on: bool,
hand: bool,
) -> (BTreeSet<Vec<u64>>, BTreeSet<Vec<u64>>, usize, usize, usize) {
let (c, counts, index) = catalog();
let mut p = Program::new();
let func = p.input_from::<1>(&c, "func").unwrap();
let size_of = p.input_from::<2>(&c, "func.size").unwrap();
let mid = p.derived::<1>("mid");
let (f, s) = (p.var("F"), p.var("S"));
let mut inputs = Inputs::new();
if hand {
// the lookup written by hand: mid(F) :- size_index(20, 29, F), func.size(F, S), ...
let idx = p.external::<3>("size_index");
inputs
.external(
&idx,
match &index {
Source::External(e) => e.clone(),
_ => unreachable!(),
},
)
.unwrap();
p.rule(
mid.at([f]),
[
idx.atom([Term::Const(20), Term::Const(29), f.into()])
.into(),
size_of.at([f, s]).into(),
ge(s, Term::Const(20)),
lt(s, Term::Const(30)),
],
)
.unwrap();
} else {
p.rule(
mid.at([f]),
[
func.at([f]).into(),
size_of.at([f, s]).into(),
ge(s, Term::Const(20)),
lt(s, Term::Const(30)),
],
)
.unwrap();
}
let low = p.derived::<1>("low");
p.rule(low.at([f]), [func.at([f]).into(), lt(f, Term::Const(50))])
.unwrap();
inputs.bind(&p, &c).unwrap();
let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2)).index_choice(on);
let out = e.run(&p, &inputs).await.unwrap();
let rows = |r| -> BTreeSet<Vec<u64>> { out.get(r).unwrap().rows().collect() };
let facts: usize = out.report.strata.iter().map(|s| s.facts).sum();
(
rows(&mid),
rows(&low),
counts.asked.load(Ordering::Relaxed),
counts.handed.load(Ordering::Relaxed),
facts,
)
}
#[tokio::test]
async fn plain_rules_find_their_ids_by_the_catalogs_indexes() {
let want_mid: BTreeSet<Vec<u64>> = (0..N)
.filter(|&i| (20..30).contains(&size(i)))
.map(|i| vec![BASE + i])
.collect();
let want_low: BTreeSet<Vec<u64>> = (BASE..50).map(|i| vec![i]).collect();
let off = run(false, false).await;
let on = run(true, false).await;
assert_eq!((&off.0, &off.1), (&want_mid, &want_low));
assert_eq!((&on.0, &on.1), (&want_mid, &want_low));
assert_eq!(off.2, 0, "the plain rule as written reads no index");
assert_eq!(on.2, 1, "one lookup of the size index");
assert_eq!(on.3, want_mid.len(), "the index hands the rows found");
// the lookup written by hand: the same answers and the same cost
let hand = run(true, true).await;
assert_eq!(hand, on);
}