crates/kleene-plan/tests/count_without_rows.rs
//! A count over counted matches without their rows: an aggregate that reads a counted
//! relation made by one counting rule, weighed by its count, reads that rule's body itself,
//! and an internal relation nothing reads is not derived. The plan GQL makes for
//! `MATCH (a:L)-[:E]->(b:L) RETURN a, count(*), sum(b), min(b)` (parallel edges as counts),
//! against a plain loop over the edge list, at 1 and 8 threads, with and without the rewrite.
use std::collections::BTreeMap;
use kleene_plan::{Aggregate, Atom, Engine, Facts, Inputs, Plan, Reduce, RelId, Term, Type, Var};
use kleene_sparse::{CpuBackend, CpuDevice};
fn atom(rel: RelId, terms: &[Var]) -> Atom {
Atom {
rel,
terms: terms.iter().map(|&v| Term::Var(v)).collect(),
}
}
/// Edges with parallel ones: 0->1 three times, 1->2, 2->0 twice, 2->3, 3->3 twice, 4->0.
const EDGES: [(u64, u64); 11] = [
(0, 1),
(0, 1),
(0, 1),
(1, 2),
(2, 0),
(2, 0),
(2, 3),
(3, 3),
(3, 3),
(4, 0),
(1, 4),
];
/// The nodes with the label: 4 has none.
const LABELLED: [u64; 4] = [0, 1, 2, 3];
/// The plan, its input, and the relations: (plan, inputs, grouped, matches, match).
fn plan() -> (Plan, Inputs, RelId, RelId, RelId) {
let mut p = Plan::new();
let e = p.input_counted("e counts", &[Type::U64, Type::U64]);
let l = p.input("l", 1);
let [a, b, k, n, c, s, lo] = ["A", "B", "K", "N", "C", "S", "LO"].map(|v| p.var(v));
let body = [atom(l, &[a]), atom(e, &[a, b, k]), atom(l, &[b])];
// the match as a set (read by no rule), and the matches counted
let m = p.derived("match", 2);
p.rule(atom(m, &[a, b]), body.clone()).unwrap();
p.internal(m);
let mm = p.derived_counted("matches", &[Type::U64, Type::U64]);
let x = p.var("X");
p.count_rule(
atom(mm, &[a, b, x]),
[atom(l, &[a]), atom(e, &[a, b, k]), atom(l, &[b])],
)
.unwrap();
p.internal(mm);
let g = p.derived("grouped", 4);
let agg = Aggregate::many(
[a],
[Reduce::count(c), Reduce::sum(b, s), Reduce::min(b, lo)],
)
.times([n]);
p.aggregate(atom(g, &[a, c, s, lo]), agg, [atom(mm, &[a, b, n])])
.unwrap();
let mut counts: BTreeMap<(u64, u64), u64> = BTreeMap::new();
for &x in &EDGES {
*counts.entry(x).or_default() += 1;
}
let mut inp = Inputs::new();
inp.facts(
e,
Facts::from_rows(3, counts.into_iter().map(|((a, b), c)| [a, b, c])).unwrap(),
);
inp.facts(l, Facts::from_rows(1, LABELLED.map(|x| [x])).unwrap());
(p, inp, g, mm, m)
}
/// Per labelled start: (count, sum of ends, least end) over every edge, parallel ones each.
fn want() -> Vec<Vec<u64>> {
let mut by: BTreeMap<u64, (u64, u64, u64)> = BTreeMap::new();
for &(a, b) in &EDGES {
if LABELLED.contains(&a) && LABELLED.contains(&b) {
let x = by.entry(a).or_insert((0, 0, u64::MAX));
x.0 += 1;
x.1 += b;
x.2 = x.2.min(b);
}
}
by.into_iter()
.map(|(a, (c, s, m))| vec![a, c, s, m])
.collect()
}
#[tokio::test]
async fn a_count_over_counted_matches_builds_no_rows_of_them() {
let (p, inp, g, mm, m) = plan();
for threads in [1, 8] {
for next_rows in [true, false] {
let engine: Engine<CpuBackend> =
Engine::new(CpuDevice::new(threads)).next_rows(next_rows);
let o = engine.run(&p, &inp).await.unwrap();
let mut got: Vec<Vec<u64>> = o.get(g).unwrap().rows().map(|r| r.to_vec()).collect();
got.sort();
assert_eq!(got, want(), "threads {threads}, rewrite {next_rows}");
// (rows, facts) of the strata that derive `rel`
let of = |rel: RelId| -> (usize, usize) {
let name = p.relation_info(rel).name.clone();
o.report
.strata
.iter()
.filter(|s| s.relations.contains(&name))
.fold((0, 0), |x, s| (x.0 + s.peak_rows, x.1 + s.facts))
};
if next_rows {
// the aggregate over the body; no rows of the matches, no match set
assert_eq!(of(mm), (0, 0), "threads {threads}");
assert_eq!(of(m), (0, 0), "threads {threads}");
} else {
assert!(of(mm).1 > 0 && of(m).1 > 0);
}
}
}
}
/// A counted relation that its client reads stays derived; the aggregate over it still
/// reads the counting rule's body, with the same answers.
#[tokio::test]
async fn a_counted_relation_read_by_its_client_stays() {
// (the inputs of `plan`, the same relation ids: `e counts` then `l`)
let (_, inp, ..) = plan();
let mut q = Plan::new();
let e = q.input_counted("e counts", &[Type::U64, Type::U64]);
let l = q.input("l", 1);
let [a, b, k, n, c, x] = ["A", "B", "K", "N", "C", "X"].map(|v| q.var(v));
let two = q.derived_counted("matches", &[Type::U64, Type::U64]);
q.count_rule(
atom(two, &[a, b, x]),
[atom(l, &[a]), atom(e, &[a, b, k]), atom(l, &[b])],
)
.unwrap();
let total = q.derived("total", 1);
q.aggregate(
atom(total, &[c]),
Aggregate::many([], [Reduce::count(c)]).times([n]),
[atom(two, &[a, b, n])],
)
.unwrap();
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(4));
let o = engine.run(&q, &inp).await.unwrap();
let all: u64 = want().iter().map(|r| r[1]).sum();
let got: Vec<Vec<u64>> = o.get(total).unwrap().rows().map(|r| r.to_vec()).collect();
assert_eq!(got, vec![vec![all]]);
let pairs: u64 = o.get(two).unwrap().rows().map(|r| r[2]).sum();
assert_eq!(pairs, all);
}