crates/kleene-index/tests/catalog.rs
//! An X.gar set read as a catalog with its indexes ([`kleene_index::catalog`]) by a Datalog
//! program: the inputs bound by name, the range index over `person.age` found by the index
//! choice (one lookup, no scan), the reach index read as a relation; against plain loops.
use std::collections::BTreeSet;
use std::path::PathBuf;
use graphar::mapped::{IntColumn, IntEdges, IntGraphWriter};
use kleene_datalog::{Engine, Inputs, Program, Source, Term, ge, le};
use kleene_gar::GarGraph;
use kleene_sparse::{CpuBackend, CpuDevice};
const AGES: [u32; 6] = [20, 45, 33, 61, 18, 40];
const KNOWS: [(u32, u32); 5] = [(1, 2), (2, 4), (4, 0), (3, 3), (0, 1)];
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn set() -> TempDir {
let dir = std::env::temp_dir().join(format!("kleene-index-catalog-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut w = IntGraphWriter::new(&dir, "X").unwrap();
w.vertices(
"person",
AGES.len() as u32,
vec![("age".to_string(), IntColumn::U32(AGES.to_vec()))],
)
.unwrap();
let (s, d): (Vec<u32>, Vec<u32>) = KNOWS.iter().copied().unzip();
let n = AGES.len() as u32;
w.edges(IntEdges::from_pairs(("person", "knows", "person"), (n, n), &s, &d, vec![]).unwrap())
.unwrap();
w.finish().unwrap();
TempDir(dir)
}
#[tokio::test]
async fn a_program_binds_a_set_and_its_indexes_by_name() {
let dir = set();
let g = GarGraph::open(&dir.0).unwrap();
let c = kleene_index::catalog(&g).unwrap();
let base = g.id_space().unwrap().base("person").unwrap();
assert!(
c.prop_idx("person", "age").is_some(),
"a range index per number"
);
let Some(Source::External(reach)) = c.reach_idx("knows").cloned() else {
panic!("a reach index per edge label")
};
let mut runs: Vec<Vec<String>> = Vec::new();
for on in [false, true] {
let mut p = Program::new();
let person = p.input_from::<1>(&c, "person").unwrap();
let age = p.input_from::<2>(&c, "person.age").unwrap();
let reaches = p.external::<2>("reaches");
let mid = p.derived::<1>("mid");
let far = p.derived::<2>("far");
let [x, a, y] = ["X", "A", "Y"].map(|n| p.var(n));
// mid(X) :- person(X), person.age(X, A), A >= 30, A <= 45.
p.rule(
mid.at([x]),
[
person.at([x]).into(),
age.at([x, a]).into(),
ge(a, Term::Const(30)),
le(a, Term::Const(45)),
],
)
.unwrap();
// far(X, Y) :- mid(X), person(Y), reaches(X, Y).
p.rule(
far.at([x, y]),
[mid.at([x]), person.at([y]), reaches.at([x, y])],
)
.unwrap();
let mut inputs = Inputs::new();
inputs.external(&reaches, reach.clone()).unwrap();
inputs.bind(&p, &c).unwrap();
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.index_choice(on)
.run(&p, &inputs)
.await
.unwrap();
let ran: Vec<String> = out
.report
.strata
.iter()
.flat_map(|s| s.relations.clone())
.collect();
runs.push(ran);
let want_mid: BTreeSet<Vec<u64>> = (0..AGES.len())
.filter(|&i| (30..=45).contains(&AGES[i]))
.map(|i| vec![base + i as u64])
.collect();
let got: BTreeSet<Vec<u64>> = out.get(&mid).unwrap().rows().collect();
assert_eq!(got, want_mid);
// the reach index: a path of zero or more `knows` edges (a plain closure; each
// node reaches itself)
let mut want_far: BTreeSet<Vec<u64>> = BTreeSet::new();
for m in &want_mid {
let s = (m[0] - base) as u32;
let mut seen: BTreeSet<u32> = BTreeSet::from([s]);
let mut todo = vec![s];
while let Some(v) = todo.pop() {
for &(a, b) in &KNOWS {
if a == v && seen.insert(b) {
todo.push(b);
}
}
}
for t in seen {
want_far.insert(vec![m[0], base + t as u64]);
}
}
let got: BTreeSet<Vec<u64>> = out.get(&far).unwrap().rows().collect();
assert_eq!(got, want_far);
}
// the index choice read the range index: the run's relations are the pass's
assert_ne!(runs[0], runs[1], "the index choice rewrote the rule");
}