crates/kleene-plan/tests/columns_alloc.rs
//! Rules allocate per batch, never per row: a join, an anti-join and the dedupe of the head
//! over ten times the rows make few more allocations. Alone in its own
//! test binary, since the count is taken over every thread.
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
use kleene_plan::{Atom, Engine, Facts, Inputs, Literal, Plan, Term};
use kleene_sparse::{CpuBackend, CpuDevice};
struct Counting;
static COUNT: AtomicUsize = AtomicUsize::new(0);
// SAFETY: forwards to the system allocator; only counts.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
COUNT.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
unsafe { System.dealloc(p, l) }
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
COUNT.fetch_add(1, Ordering::Relaxed);
unsafe { System.realloc(p, l, n) }
}
}
#[global_allocator]
static A: Counting = Counting;
#[test]
fn a_join_with_negation_and_dedupe_allocates_per_batch_not_per_row() {
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
// out(X, Z, Y) :- e(X, Y), e(Y, Z), !bad(Z). from(X) :- out(X, Z, Y).
let mut p = Plan::new();
let e = p.input("e", 2);
let bad = p.input("bad", 1);
let out = p.derived("out", 3);
let from = p.derived("from", 1);
let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
let at = |rel, vs: &[kleene_plan::Var]| Atom {
rel,
terms: vs.iter().map(|&v| Term::Var(v)).collect(),
};
p.rule(
at(out, &[x, z, y]),
[
Literal::Pos(at(e, &[x, y])),
Literal::Pos(at(e, &[y, z])),
Literal::Neg(at(bad, &[z])),
],
)
.unwrap();
p.rule(at(from, &[x]), [at(out, &[x, z, y])]).unwrap();
let run = |n: u32| -> (usize, usize) {
let (mut src, mut dst) = (Vec::new(), Vec::new());
for v in 0..n {
for w in [(v + 1) % n, (v * 7 + 3) % n] {
src.push(v);
dst.push(w);
}
}
let bads: Vec<u32> = (0..n).filter(|v| v % 5 == 0).collect();
let mut inputs = Inputs::new();
inputs
.facts(e, Facts::from_columns(vec![src, dst]).unwrap())
.facts(bad, Facts::from_columns(vec![bads]).unwrap());
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(1));
let before = COUNT.load(Ordering::Relaxed);
let o = rt.block_on(engine.run(&p, &inputs)).unwrap();
let allocs = COUNT.load(Ordering::Relaxed) - before;
(allocs, o.get(out).unwrap().len())
};
let (small, small_rows) = run(20_000);
let (big, big_rows) = run(200_000);
assert!(
big_rows >= 9 * small_rows,
"{small_rows} then {big_rows} rows"
);
// Per batch: fewer than one allocation per 50 rows at either size, and ten times the
// rows take less than three times the allocations.
assert!(
50 * small < small_rows && 50 * big < big_rows && big < 3 * small,
"{small} allocations for {small_rows} rows, {big} for {big_rows}"
);
}