crates/kleene-datalog/tests/strings.rs
//! Line 9: strings made by a rule (`S = concat(A, "-", B)`, `P = substr(S, I, N)`,
//! `L = len(S)`), each against plain Rust over the same rows, at 1, 2 and 4 threads: a made
//! string that equals a string read joins it, ordered tests and the output order of made
//! strings go by their bytes, the proof shows the made value with its operands, and what is
//! not covered is refused by name.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use arrow_array::{ArrayRef, StringArray, UInt64Array};
use kleene_datalog::{
Cond, Datum, Engine, Expr, Inputs, Literal, Order, OrderKey, Program, Type, compute, datalog,
plan,
};
use kleene_plan::TextOp;
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
}
/// A short word: ASCII mostly, some letters of two, three and four bytes.
fn word(&mut self) -> String {
const PIECES: &[&str] = &["a", "b", "lex", "z", "é", "ß", "日本", "🦀", "-", "m"];
let n = self.next() % 4;
(0..n)
.map(|_| PIECES[(self.next() % PIECES.len() as u64) as usize])
.collect()
}
}
fn strs(v: &[String]) -> ArrayRef {
Arc::new(StringArray::from_iter_values(v.iter().map(String::as_str)))
}
fn nums(v: &[u64]) -> ArrayRef {
Arc::new(UInt64Array::from(v.to_vec()))
}
/// `substr` in plain Rust: `n` characters from character `i` (fewer past the end).
fn cut(s: &str, i: u64, n: Option<u64>) -> String {
let it = s.chars().skip(i as usize);
match n {
Some(n) => it.take(n as usize).collect(),
None => it.collect(),
}
}
fn pairs(rows: Option<Vec<[Datum; 2]>>) -> BTreeSet<(u64, String)> {
rows.unwrap_or_default()
.into_iter()
.map(|[a, b]| match (a, b) {
(Datum::U64(a), Datum::Str(b)) => (a, b),
other => panic!("not (u64, str): {other:?}"),
})
.collect()
}
#[tokio::test]
async fn made_strings_equal_plain_rust_at_every_thread_count() {
let mut p = Program::new();
let word = p.input_typed("word", [Type::U64, Type::Str]);
let pre = p.input_typed("pre", [Type::U64, Type::Str]);
let num = p.input_typed("num", [Type::U64, Type::U64, Type::U64]);
let joined = p.derived_typed("joined", [Type::U64, Type::Str]);
let piece = p.derived_typed("piece", [Type::U64, Type::Str]);
let rest = p.derived_typed("rest", [Type::U64, Type::Str]);
let size = p.derived_typed("size", [Type::U64, Type::U64]);
let long = p.derived_typed("long", [Type::U64, Type::Str]);
let after = p.derived_typed("after", [Type::U64, Type::Str]);
let hit = p.derived_typed("hit", [Type::U64, Type::U64]);
let lexy = p.derived_typed("lexy", [Type::U64, Type::Str]);
let dash = p.str("-");
let m = p.str("m");
datalog!(&mut p =>
joined(I, S) :- word(I, A), pre(I, B), S = concat(A, dash, B).
piece(I, P) :- word(I, S), num(I, K, N), P = substr(S, K, N).
rest(I, P) :- word(I, S), num(I, K, _), P = substr(S, K).
size(I, L) :- word(I, S), L = len(S).
long(I, S) :- joined(I, S), len(S) > 5.
after(I, S) :- joined(I, S), S > m.
hit(I, J) :- word(I, A), pre(I, B), C = concat(A, B), word(J, C).
)
.unwrap();
// a text test of a made string (the builder's Cond::Text: no text for it in this line)
let (i, s) = (p.var("I"), p.var("S"));
let lex = p.str("lex");
p.rule(
lexy.at([i, s]),
[
Literal::from(joined.at([i, s])),
Literal::Cond(Cond::Text {
x: s.into(),
op: TextOp::Contains,
pat: lex,
}),
],
)
.unwrap();
assert!(plan(&p).is_ok());
let mut g = Lcg(9);
let n = 3000u64;
let words: Vec<String> = (0..n).map(|_| g.word()).collect();
let pres: Vec<String> = (0..n).map(|_| g.word()).collect();
let ks: Vec<u64> = (0..n).map(|_| g.next() % 6).collect();
let ns: Vec<u64> = (0..n).map(|_| g.next() % 6).collect();
let ids: Vec<u64> = (0..n).collect();
let mut inputs = Inputs::new();
inputs.columns(&word, [nums(&ids), strs(&words)]);
inputs.columns(&pre, [nums(&ids), strs(&pres)]);
inputs.columns(&num, [nums(&ids), nums(&ks), nums(&ns)]);
// the plain reference
let want_joined: BTreeSet<(u64, String)> = (0..n as usize)
.map(|i| (i as u64, format!("{}-{}", words[i], pres[i])))
.collect();
let want_piece: BTreeSet<(u64, String)> = (0..n as usize)
.map(|i| (i as u64, cut(&words[i], ks[i], Some(ns[i]))))
.collect();
let want_rest: BTreeSet<(u64, String)> = (0..n as usize)
.map(|i| (i as u64, cut(&words[i], ks[i], None)))
.collect();
let want_size: BTreeSet<Vec<u64>> = (0..n as usize)
.map(|i| vec![i as u64, words[i].chars().count() as u64])
.collect();
let want_long: BTreeSet<(u64, String)> = want_joined
.iter()
.filter(|x| x.1.chars().count() > 5)
.cloned()
.collect();
let want_after: BTreeSet<(u64, String)> = want_joined
.iter()
.filter(|x| x.1.as_bytes() > b"m".as_slice())
.cloned()
.collect();
let want_lexy: BTreeSet<(u64, String)> = want_joined
.iter()
.filter(|x| x.1.contains("lex"))
.cloned()
.collect();
let mut by_word: BTreeMap<&str, Vec<u64>> = BTreeMap::new();
for (j, w) in words.iter().enumerate() {
by_word.entry(w.as_str()).or_default().push(j as u64);
}
let want_hit: BTreeSet<Vec<u64>> = (0..n as usize)
.flat_map(|i| {
let c = format!("{}{}", words[i], pres[i]);
by_word
.get(c.as_str())
.into_iter()
.flatten()
.map(move |&j| vec![i as u64, j])
.collect::<Vec<_>>()
})
.collect();
assert!(
want_hit.len() > 100,
"made strings meet words: {}",
want_hit.len()
);
assert!(!want_after.is_empty() && want_after.len() < want_joined.len());
assert!(!want_lexy.is_empty());
assert!(
want_piece.iter().any(|x| x.1.is_empty()),
"some cuts past the end"
);
let mut proofs_at_one: Option<Vec<String>> = None;
for threads in [1, 2, 4] {
let out = engine(threads).run(&p, &inputs).await.unwrap();
assert_eq!(
pairs(out.datums(&p, &joined)),
want_joined,
"joined at {threads}"
);
assert_eq!(
pairs(out.datums(&p, &piece)),
want_piece,
"piece at {threads}"
);
assert_eq!(pairs(out.datums(&p, &rest)), want_rest, "rest at {threads}");
let got_size: BTreeSet<Vec<u64>> = out.get(&size).unwrap().rows().collect();
assert_eq!(got_size, want_size, "size at {threads}");
assert_eq!(pairs(out.datums(&p, &long)), want_long, "long at {threads}");
assert_eq!(
pairs(out.datums(&p, &after)),
want_after,
"after at {threads}"
);
assert_eq!(pairs(out.datums(&p, &lexy)), want_lexy, "lexy at {threads}");
let got_hit: BTreeSet<Vec<u64>> = out.get(&hit).unwrap().rows().collect();
assert_eq!(got_hit, want_hit, "hit at {threads}");
// the output order of made strings is their byte order
let ordered: Vec<String> = out
.ordered(&p, &joined, &Order::new().by(OrderKey::asc(1)))
.unwrap()
.into_iter()
.map(|r| r[1].to_string())
.collect();
let mut sorted = ordered.clone();
sorted.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
assert_eq!(ordered, sorted, "ordered at {threads}");
// proofs, the same at every thread count
let proofs: Vec<String> = want_joined
.iter()
.take(40)
.map(|(i, s)| {
let pr = out
.why_of(&p, &joined, [Datum::U64(*i), Datum::Str(s.clone())])
.unwrap();
out.render(&p, &pr)
})
.collect();
match &proofs_at_one {
None => proofs_at_one = Some(proofs),
Some(one) => assert_eq!(one, &proofs, "proofs at {threads}"),
}
}
}
/// 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()
}
#[tokio::test]
async fn the_proof_shows_the_made_value_with_its_operands() {
let mut p = Program::new();
let word = p.input_typed("word", [Type::U64, Type::Str]);
let pre = p.input_typed("pre", [Type::U64, Type::Str]);
let joined = p.derived_typed("joined", [Type::U64, Type::Str]);
let size = p.derived_typed("size", [Type::U64, Type::U64]);
let both = p.derived_typed("both", [Type::U64]);
let starts = p.derived_typed("starts", [Type::U64, Type::Str]);
// quoted strings in a string place are string constants
datalog!(&mut p =>
joined(I, S) :- word(I, A), pre(I, B), S = concat(A, "-", B).
size(I, L) :- joined(I, S), L = len(substr(S, 1)).
both(I) :- word(I, A), pre(I, B), concat(A, B) == "ab日本", len("xyz") == 3.
starts(I, S) :- joined(I, S), S starts with "ab-".
)
.unwrap();
assert_eq!(
p.show_rule(rule_id(0)),
"joined(I, S) :- word(I, A), pre(I, B), S = concat(A, \"-\", B)."
);
let mut inputs = Inputs::new();
inputs.columns(&word, [nums(&[1]), strs(&["ab".into()])]);
inputs.columns(&pre, [nums(&[1]), strs(&["日本".into()])]);
let out = engine(2).run(&p, &inputs).await.unwrap();
let pr = out
.why_of(&p, &joined, [Datum::U64(1), Datum::Str("ab-日本".into())])
.unwrap();
let text = out.render(&p, &pr);
assert!(
text.contains(
"S = concat(A, \"-\", B) = concat(\"ab\", \"-\", \"日本\") = \"ab-日本\" [computed]"
),
"{text}"
);
let got: Vec<[Datum; 1]> = out.datums(&p, &both).unwrap();
assert_eq!(got, vec![[Datum::U64(1)]]);
let got: Vec<[Datum; 2]> = out.datums(&p, &starts).unwrap();
assert_eq!(got, vec![[Datum::U64(1), Datum::Str("ab-日本".into())]]);
let pr = out
.why_of(&p, &size, [Datum::U64(1), Datum::U64(4)])
.unwrap();
let text = out.render(&p, &pr);
assert!(
text.contains("L = len(substr(S, 1)) = len(substr(\"ab-日本\", 1)) = 4 [computed]"),
"{text}"
);
}
#[tokio::test]
async fn what_is_not_covered_is_refused_by_name() {
// concat inside a recursion would make longer strings for ever
let mut p = Program::new();
let word = p.input_typed("word", [Type::Str]);
let grow = p.derived_typed("grow", [Type::Str]);
let a = p.str("a");
datalog!(&mut p =>
grow(S) :- word(S).
grow(T) :- grow(S), T = concat(S, a).
)
.unwrap();
let e = plan(&p).unwrap_err().to_string();
assert!(e.contains("concat inside a recursion"), "{e}");
// substr inside a recursion ends: it only cuts strings already there
let mut p = Program::new();
let word = p.input_typed("word", [Type::Str]);
let tails = p.derived_typed("tails", [Type::Str]);
datalog!(&mut p =>
tails(S) :- word(S).
tails(T) :- tails(S), T = substr(S, 1).
)
.unwrap();
assert!(plan(&p).is_ok());
let mut inputs = Inputs::new();
inputs.columns(&word, [strs(&["abc".into(), "日本x".into()])]);
let out = engine(2).run(&p, &inputs).await.unwrap();
let got: BTreeSet<String> = out
.datums(&p, &tails)
.unwrap()
.into_iter()
.map(|[d]| d.to_string())
.collect();
let want: BTreeSet<String> = ["abc", "bc", "c", "", "日本x", "本x", "x"]
.iter()
.map(|s| format!("{s:?}"))
.collect();
assert_eq!(got, want);
// a number where a string goes, a string where a number goes
let mut p = Program::new();
let pair = p.input_typed("pair", [Type::U64, Type::Str]);
let bad = p.derived_typed("bad", [Type::Str]);
let (i, s, t) = (p.var("I"), p.var("S"), p.var("T"));
let e = p
.rule(
bad.at([t]),
[pair.at([i, s]).into(), compute(t, Expr::concat([s, i]))],
)
.unwrap_err()
.to_string();
assert!(e.contains("where a string goes"), "{e}");
let e = p
.rule(
bad.at([t]),
[pair.at([i, s]).into(), compute(t, Expr::len(s))],
)
.unwrap_err()
.to_string();
assert!(e.contains("goes in a str"), "{e}");
// a least by a made string
let mut p = Program::new();
let pair = p.input_typed("pair", [Type::U64, Type::Str]);
let made = p.derived_typed("made", [Type::U64, Type::Str]);
let first = p.derived_typed("first", [Type::U64, Type::Str]);
let x = p.str("x");
datalog!(&mut p =>
made(I, T) :- pair(I, S), T = concat(S, x).
first(I, T) :- min(T) by (I): made(I, T).
)
.unwrap();
let mut inputs = Inputs::new();
inputs.columns(&pair, [nums(&[1, 1]), strs(&["b".into(), "a".into()])]);
let e = engine(1).run(&p, &inputs).await.unwrap_err().to_string();
assert!(e.contains("a string a rule made, is not covered"), "{e}");
}