crates/kleene-gql/tests/one_of.rs
//! Line 22 from GQL: `value IN (list)` of a node or a node's property against constants is
//! the core's one list test (`Cond::OneOf`, as `datalog!`'s `K in (..)`), against plain Rust
//! over the same rows at 1, 2 and 4 threads: unsigned, signed (with nulls) and string
//! properties, a node's id, `NOT ... IN`, a NULL member (dropped from IN; NOT IN never
//! true), a repeated member, the empty list; and the plan holds the list test, not an OR.
use std::sync::Arc;
use arrow_array::{ArrayRef, Int64Array, StringArray, UInt64Array};
use kleene_gql::{Catalog, lower, parse, query};
use kleene_plan::{Engine, RuleId, Source, Type};
use kleene_sparse::{CpuBackend, CpuDevice};
const N: u64 = 3000;
const WORDS: &[&str] = &["memcpy", "memmove", "memset", "strlen", "malloc", "free"];
/// Deterministic pseudo-random numbers (a 64-bit LCG), no dependency.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0 >> 11
}
}
struct Rows {
k: Vec<u64>,
s: Vec<Option<i64>>,
name: Vec<Option<&'static str>>,
}
fn data() -> (Catalog, Rows) {
let mut g = Lcg(22);
let k: Vec<u64> = (0..N).map(|_| g.next() % 40).collect();
let s: Vec<Option<i64>> = (0..N)
.map(|_| match g.next() % 9 {
0 => None,
x => Some(x as i64 - 4),
})
.collect();
let name: Vec<Option<&str>> = (0..N)
.map(|_| match g.next() % 7 {
0 => None,
x => Some(WORDS[(x as usize - 1) % WORDS.len()]),
})
.collect();
let ids: ArrayRef = Arc::new(UInt64Array::from((0..N).collect::<Vec<_>>()));
let mut c = Catalog::new();
c.label("Func", Source::Columns(vec![ids.clone()]))
.typed_property(
"Func",
"k",
Source::Columns(vec![ids.clone(), Arc::new(UInt64Array::from(k.clone()))]),
Type::U64,
)
.typed_property(
"Func",
"s",
Source::Columns(vec![ids.clone(), Arc::new(Int64Array::from(s.clone()))]),
Type::I64,
)
.typed_property(
"Func",
"name",
Source::Columns(vec![ids, Arc::new(StringArray::from(name.clone()))]),
Type::Str,
);
(c, Rows { k, s, name })
}
type Pred = fn(&Rows, usize) -> Option<bool>;
#[tokio::test]
async fn in_equals_plain_rust_at_every_thread_count() {
let (c, r) = data();
let callees = ["memcpy", "memmove", "nope"];
let cases: Vec<(&str, Pred)> = vec![
("f.k IN (1, 2, 3)", |r, i| Some([1, 2, 3].contains(&r.k[i]))),
("NOT f.k IN [1, 2]", |r, i| Some(![1, 2].contains(&r.k[i]))),
("f.k IN (7, 7)", |r, i| Some(r.k[i] == 7)),
("f IN (3, 4, 2999)", |_, i| Some([3, 4, 2999].contains(&i))),
("f.name IN ('memcpy', 'memmove', 'nope')", |r, i| {
r.name[i].map(|s| ["memcpy", "memmove", "nope"].contains(&s))
}),
("NOT f.name IN ['memcpy', 'memmove', 'nope']", |r, i| {
r.name[i].map(|s| !["memcpy", "memmove", "nope"].contains(&s))
}),
("f.s IN (-1, 5)", |r, i| r.s[i].map(|s| s == -1 || s == 5)),
("NOT f.s IN (-1, 5)", |r, i| {
r.s[i].map(|s| s != -1 && s != 5)
}),
// a NULL member: IN true or unknown, NOT IN never true
("f.s IN (-1, NULL)", |r, i| match r.s[i] {
Some(-1) => Some(true),
_ => None,
}),
("NOT f.s IN (-1, NULL)", |r, i| match r.s[i] {
Some(-1) => Some(false),
_ => None,
}),
("f.s IN ()", |_, _| Some(false)),
("NOT f.s IN ()", |_, _| Some(true)),
("f.k IN (1, 2) OR f.s IN (3)", |r, i| {
let a = [1, 2].contains(&r.k[i]);
match (a, r.s[i]) {
(true, _) => Some(true),
(false, Some(s)) => Some(s == 3),
(false, None) => None,
}
}),
];
let _ = callees;
for threads in [1, 2, 4] {
let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads));
for (cond, pred) in &cases {
let text = format!("MATCH (f:Func) WHERE {cond} RETURN f");
let t = query(&e, &c, &text)
.await
.unwrap_or_else(|err| panic!("{text}: {err}"));
let want: Vec<Vec<u64>> = (0..N as usize)
.filter(|&i| pred(&r, i) == Some(true))
.map(|i| vec![i as u64])
.collect();
assert_eq!(t.rows, want, "{cond} at {threads}");
}
}
}
/// A repeated member gives each row as often as one member does (rows as a bag).
#[tokio::test]
async fn a_repeated_member_gives_a_row_once() {
let (c, r) = data();
let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
let once = query(&e, &c, "MATCH (f:Func) WHERE f.k = 7 RETURN f.k")
.await
.unwrap();
let twice = query(&e, &c, "MATCH (f:Func) WHERE f.k IN (7, 7) RETURN f.k")
.await
.unwrap();
assert_eq!(once.rows.len(), r.k.iter().filter(|&&k| k == 7).count());
assert_eq!(twice.rows, once.rows);
}
/// The plan holds the core's list test (`f.k in (1, 2, 3)`), not one rule per member.
#[test]
fn the_plan_holds_the_list_test() {
let (c, _) = data();
for (q, want) in [
(
"MATCH (f:Func) WHERE f.k IN (1, 2, 3) RETURN f",
"f.k in (1, 2, 3)",
),
(
"MATCH (f:Func) WHERE NOT f.k IN [1, 2] RETURN f",
"!(f.k in (1, 2))",
),
(
"MATCH (f:Func) WHERE f.name IN ('memcpy', 'nope') RETURN f",
"f.name in (\"memcpy\", \"nope\")",
),
] {
let l = lower(&parse(q).unwrap(), &c).unwrap();
let rules: Vec<String> = (0..l.plan.rules().len())
.map(|i| l.plan.show_rule(rule_id(i)))
.collect();
assert!(rules.iter().any(|r| r.contains(want)), "{q}: {rules:#?}");
// one rule holds the test: not a rule per member
assert_eq!(
rules.iter().filter(|r| r.contains(" in ")).count(),
1,
"{q}: {rules:#?}"
);
}
}
/// The id of rule `i` (rules are numbered as added).
fn rule_id(i: usize) -> RuleId {
let mut p = kleene_plan::Plan::new();
let a = p.input("a", 1);
let d = p.derived("d", 1);
let x = p.var("X");
let at = |rel| kleene_plan::Atom {
rel,
terms: vec![kleene_plan::Term::Var(x)],
};
let mut last = None;
for _ in 0..=i {
last = Some(p.rule(at(d), [at(a)]).unwrap());
}
last.unwrap()
}