crates/kleene-datalog/tests/one_of.rs
//! Line 22: "a value is one of a list" as one literal (`K in (1, 2, 3)`, `N in {LIST}`,
//! `!(K in (..))`), each against plain Rust over the same rows, at 1, 2 and 4 threads: text
//! constants typed by the left side, Rust values in braces as members, a Rust slice as the
//! whole list (an empty one holds for no value), the negated form (a null holds neither), an
//! expression on the left, the range `in` unchanged beside it, the hand-written builder
//! giving the same answer, the proof showing the value and the list, and a member of the
//! wrong type refused by name.
use std::collections::BTreeSet;
use std::sync::Arc;
use arrow_array::{ArrayRef, Int64Array, StringArray, UInt64Array};
use kleene_datalog::{
Datum, Engine, Inputs, ListMember, Literal, Program, Type, datalog, not_one_of, one_of, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};
fn engine(threads: usize) -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(threads)).explain(true)
}
/// 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
}
}
mod names {
pub mod code {
pub mod term {
pub const VIRTUAL: u64 = 5;
pub const FN_POINTER: u32 = 9;
}
}
pub const CALLEES: &[&str] = &["memcpy", "memmove", "no-such-name"];
}
const LIST: &[u32] = &[3, 4, 11, 12];
const WIDE: &[u64] = &[
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38,
];
const EMPTY: &[u64] = &[];
const WORDS: &[&str] = &["memcpy", "memmove", "memset", "strlen", "malloc", "free"];
fn nums(v: &[u64]) -> ArrayRef {
Arc::new(UInt64Array::from(v.to_vec()))
}
/// The ids where `keep` holds.
fn ids(n: usize, keep: impl Fn(usize) -> bool) -> BTreeSet<u64> {
(0..n).filter(|&i| keep(i)).map(|i| i as u64).collect()
}
fn got(out: &kleene_datalog::Output, rel: &kleene_datalog::Rel<1>) -> BTreeSet<u64> {
out.get(rel)
.map(|f| f.rows().map(|r: Vec<u64>| r[0]).collect())
.unwrap_or_default()
}
#[tokio::test]
async fn one_of_equals_plain_rust_at_every_thread_count() {
let mut p = Program::new();
let item = p.input_typed("item", [Type::U64, Type::U64]);
let name = p.input_typed("name", [Type::U64, Type::Str]);
let sval = p.input_typed("sval", [Type::U64, Type::I64]);
let rels: Vec<kleene_datalog::Rel<1>> = [
"small",
"mixed",
"named",
"callee",
"listed",
"wide",
"not_small",
"not_callee",
"masked",
"none",
"all",
"signed",
"one",
"ranged",
"braced",
"trailing",
]
.iter()
.map(|n| p.derived_typed(n, [Type::U64]))
.collect();
let [
small,
mixed,
named,
callee,
listed,
wide,
not_small,
not_callee,
masked,
none,
all,
signed,
one,
ranged,
braced,
trailing,
] = rels[..]
else {
unreachable!()
};
datalog!(&mut p =>
small(I) :- item(I, K), K in (1, 2, 3).
mixed(I) :- item(I, K), K in ({names::code::term::VIRTUAL}, {names::code::term::FN_POINTER}, 0).
named(I) :- name(I, N), N in ("memcpy", "memmove", "not-in-any-column").
callee(I) :- name(I, N), N in {names::CALLEES}.
listed(I) :- item(I, K), K in {LIST}.
wide(I) :- item(I, K), K in {WIDE}.
not_small(I) :- item(I, K), !(K in (1, 2)).
not_callee(I) :- name(I, N), !(N in {names::CALLEES}).
masked(I) :- item(I, K), K & {0xF} in (1, 2).
none(I) :- item(I, K), K in {EMPTY}.
all(I) :- item(I, K), !(K in {EMPTY}).
signed(I) :- sval(I, S), S in (-1, 5).
one(I) :- item(I, K), K in (7).
ranged(I) :- item(I, K), K in (2 + 1)..{9}.
braced(I) :- item(I, K), K in {2}..{5}.
trailing(I) :- item(I, K), K in (13, 14,).
)
.unwrap();
assert!(plan(&p).is_ok());
let mut g = Lcg(22);
let n = 5000usize;
let ks: Vec<u64> = (0..n).map(|_| g.next() % 40).collect();
// a name or a null, about one in seven
let names: Vec<Option<&str>> = (0..n)
.map(|_| match g.next() % 7 {
0 => None,
x => Some(WORDS[(x as usize - 1) % WORDS.len()]),
})
.collect();
let svals: Vec<Option<i64>> = (0..n)
.map(|_| match g.next() % 9 {
0 => None,
x => Some(x as i64 - 4),
})
.collect();
let idv: Vec<u64> = (0..n as u64).collect();
let mut inputs = Inputs::new();
inputs.columns(&item, [nums(&idv), nums(&ks)]);
inputs.columns(
&name,
[
nums(&idv),
Arc::new(StringArray::from(names.clone())) as ArrayRef,
],
);
inputs.columns(
&sval,
[
nums(&idv),
Arc::new(Int64Array::from(svals.clone())) as ArrayRef,
],
);
// the plain reference
let callees = names::CALLEES;
let want: Vec<BTreeSet<u64>> = vec![
ids(n, |i| [1, 2, 3].contains(&ks[i])),
ids(n, |i| [5, 9, 0].contains(&ks[i])),
ids(n, |i| {
names[i].is_some_and(|s| ["memcpy", "memmove"].contains(&s))
}),
ids(n, |i| names[i].is_some_and(|s| callees.contains(&s))),
ids(n, |i| LIST.iter().any(|&x| u64::from(x) == ks[i])),
ids(n, |i| WIDE.contains(&ks[i])),
ids(n, |i| ![1, 2].contains(&ks[i])),
// a null is in no list, and not out of one either
ids(n, |i| names[i].is_some_and(|s| !callees.contains(&s))),
ids(n, |i| [1, 2].contains(&(ks[i] & 0xF))),
BTreeSet::new(),
ids(n, |_| true),
ids(n, |i| svals[i].is_some_and(|s| s == -1 || s == 5)),
ids(n, |i| ks[i] == 7),
ids(n, |i| (3..9).contains(&ks[i])),
ids(n, |i| (2..5).contains(&ks[i])),
ids(n, |i| ks[i] == 13 || ks[i] == 14),
];
for (r, w) in rels.iter().zip(&want).skip(1) {
// each list picks some rows and leaves some (the empty one and its negation aside)
if !(r.id() == none.id() || r.id() == all.id()) {
assert!(
!w.is_empty() && w.len() < n,
"{}",
p.relation_info(r.id()).name
);
}
}
let mut proofs_at_one: Option<Vec<String>> = None;
for threads in [1, 2, 4] {
let out = engine(threads).run(&p, &inputs).await.unwrap();
for (r, w) in rels.iter().zip(&want) {
assert_eq!(
&got(&out, r),
w,
"{} at {threads}",
p.relation_info(r.id()).name
);
}
// proofs, the same at every thread count
let mut proofs = Vec::new();
for (r, w) in [
(small, &want[0]),
(callee, &want[3]),
(not_small, &want[6]),
(masked, &want[8]),
(mixed, &want[1]),
] {
for &i in w.iter().take(10) {
let pr = out.why_of(&p, &r, [Datum::U64(i)]).unwrap();
proofs.push(out.render(&p, &pr));
}
}
match &proofs_at_one {
None => proofs_at_one = Some(proofs),
Some(one) => assert_eq!(one, &proofs, "proofs at {threads}"),
}
}
let proofs = proofs_at_one.unwrap();
// the value and the list
let k = ks[*want[0].iter().next().unwrap() as usize];
assert!(
proofs[0].contains(&format!("{k} in (1, 2, 3) [holds]")),
"{}",
proofs[0]
);
// a slice: the Rust path's text and its values
let first_callee = names[*want[3].iter().next().unwrap() as usize].unwrap();
assert!(
proofs[10].contains(&format!(
"{first_callee:?} in names::CALLEES = (\"memcpy\", \"memmove\", \"no-such-name\") [holds]"
)),
"{}",
proofs[10]
);
let k = ks[*want[6].iter().next().unwrap() as usize];
assert!(
proofs[20].contains(&format!("{k} not in (1, 2) [holds]")),
"{}",
proofs[20]
);
// the rule text as written
let shown: Vec<String> = p
.rules()
.iter()
.enumerate()
.map(|(i, _)| p.show_rule(rule_id(i)))
.collect();
assert!(
shown.contains(&"small(I) :- item(I, K), K in (1, 2, 3).".to_string()),
"{shown:?}"
);
assert!(
shown.contains(&"not_small(I) :- item(I, K), !(K in (1, 2)).".to_string()),
"{shown:?}"
);
assert!(
shown.contains(&"callee(I) :- name(I, N), N in {names::CALLEES}.".to_string()),
"{shown:?}"
);
}
/// The id of rule `i` (rules are numbered as added).
fn rule_id(i: usize) -> kleene_datalog::RuleId {
let mut p = Program::new();
let a = p.input::<1>("a");
let d = p.derived::<1>("d");
let x = p.var("X");
let mut last = None;
for _ in 0..=i {
last = Some(p.rule(d.at([x]), [a.at([x])]).unwrap());
}
last.unwrap()
}
/// The hand-written program (`Program::list`, `one_of`, `not_one_of`) is the same literal:
/// the same answers as the rule text.
#[tokio::test]
async fn the_builder_gives_the_same_answers_as_the_text() {
let mut p = Program::new();
let item = p.input_typed("item", [Type::U64, Type::U64]);
let name = p.input_typed("name", [Type::U64, Type::Str]);
let a = p.derived_typed("a", [Type::U64]);
let b = p.derived_typed("b", [Type::U64]);
let c = p.derived_typed("c", [Type::U64]);
let (i, k, nm) = (p.var("I"), p.var("K"), p.var("N"));
let nums_list = p
.list(
Type::U64,
[
ListMember::from(1u64),
ListMember::from(3u32),
ListMember::from(7u8),
],
)
.unwrap();
let strs_list = p
.list_named(
"callees",
Type::Str,
names::CALLEES.iter().map(|&s| ListMember::from(s)),
)
.unwrap();
p.rule(
a.at([i]),
[Literal::from(item.at([i, k])), one_of(k, nums_list)],
)
.unwrap();
p.rule(
b.at([i]),
[Literal::from(item.at([i, k])), not_one_of(k, nums_list)],
)
.unwrap();
p.rule(
c.at([i]),
[Literal::from(name.at([i, nm])), one_of(nm, strs_list)],
)
.unwrap();
let ks: Vec<u64> = (0..64).map(|x| x % 9).collect();
let words: Vec<Option<&str>> = (0..64)
.map(|x| (x % 5 != 0).then(|| WORDS[x % WORDS.len()]))
.collect();
let idv: Vec<u64> = (0..64).collect();
let mut inputs = Inputs::new();
inputs.columns(&item, [nums(&idv), nums(&ks)]);
inputs.columns(
&name,
[
nums(&idv),
Arc::new(StringArray::from(words.clone())) as ArrayRef,
],
);
for threads in [1, 2, 4] {
let out = engine(threads).run(&p, &inputs).await.unwrap();
assert_eq!(got(&out, &a), ids(64, |x| [1, 3, 7].contains(&ks[x])));
assert_eq!(got(&out, &b), ids(64, |x| ![1, 3, 7].contains(&ks[x])));
assert_eq!(
got(&out, &c),
ids(64, |x| words[x]
.is_some_and(|s| names::CALLEES.contains(&s)))
);
}
}
/// A member of the wrong type is refused by name, at the list and at the rule.
#[test]
fn a_member_of_the_wrong_type_is_refused_by_name() {
let mut p = Program::new();
let e = p
.list(Type::U64, [ListMember::from(1u64), ListMember::from("x")])
.unwrap_err()
.to_string();
assert!(
e.contains("list member 2: a string compared with a u64 value"),
"{e}"
);
let e = p
.list(Type::Str, [ListMember::from(5u64)])
.unwrap_err()
.to_string();
assert!(
e.contains("list member 1: a Rust integer for a str value"),
"{e}"
);
// a list of strings tested on a u64 value
let item = p.input_typed("item", [Type::U64, Type::U64]);
let a = p.derived_typed("a", [Type::U64]);
let (i, k) = (p.var("I"), p.var("K"));
let l = p.list(Type::Str, [ListMember::from("memcpy")]).unwrap();
let e = p
.rule(a.at([i]), [Literal::from(item.at([i, k])), one_of(k, l)])
.unwrap_err()
.to_string();
assert!(
e.contains("`K in (..)`: a list of str values tested on K, a u64 value"),
"{e}"
);
// the text: a literal member typed by the left side
let mut q = Program::new();
let item = q.input_typed("item", [Type::U64, Type::U64]);
let b = q.derived_typed("b", [Type::U64]);
let _ = (item, b);
let e = datalog!(&mut q => b(I) :- item(I, K), K in (1, "two").)
.unwrap_err()
.to_string();
assert!(
e.contains("list member 2: a string compared with a u64 value"),
"{e}"
);
}
mod seek {
use std::sync::atomic::{AtomicUsize, Ordering};
use kleene_datalog::{Catalog, External, Source, Value};
use super::*;
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 the lookups.
#[derive(Debug)]
struct SizeIndex(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.0.fetch_add(1, Ordering::Relaxed);
for i in 0..N {
if (lo..=hi).contains(&size(i)) {
out(k, &[lo, hi, BASE + i]);
}
}
}
Ok(())
}
}
/// `pick(F) :- func(F), func.size(F, S), S in (3, 21, 50).` with the index choice on
/// or off: the rows and the lookups asked.
async fn run(on: bool, threads: usize) -> (BTreeSet<u64>, usize) {
let asked = Arc::new(AtomicUsize::new(0));
let ids: ArrayRef = Arc::new(UInt64Array::from((BASE..BASE + N).collect::<Vec<_>>()));
let sizes: ArrayRef = Arc::new(UInt64Array::from((0..N).map(size).collect::<Vec<_>>()));
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, sizes]))
.property_index(
"func",
"size",
Source::External(Arc::new(SizeIndex(asked.clone()))),
);
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 pick = p.derived::<1>("pick");
datalog!(&mut p => pick(F) :- func(F), {size_of}(F, S), S in (3, 21, 50).).unwrap();
let mut inputs = Inputs::new();
inputs.bind(&p, &c).unwrap();
let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads)).index_choice(on);
let out = e.run(&p, &inputs).await.unwrap();
(got(&out, &pick), asked.load(Ordering::Relaxed))
}
/// A list test on an indexed property is one lookup per member (the core's OR of
/// equalities), the same rows as the scan, at 1, 2 and 4 threads.
#[tokio::test]
async fn a_list_on_an_indexed_property_is_one_lookup_per_member() {
let want: BTreeSet<u64> = (0..N)
.filter(|&i| [3, 21, 50].contains(&size(i)))
.map(|i| BASE + i)
.collect();
assert!(!want.is_empty());
for threads in [1, 2, 4] {
let (rows, asked) = run(true, threads).await;
assert_eq!(rows, want, "index at {threads}");
assert_eq!(asked, 3, "one lookup per member at {threads}");
let (rows, asked) = run(false, threads).await;
assert_eq!(rows, want, "scan at {threads}");
assert_eq!(asked, 0);
}
}
}