crates/kleene-datalog/tests/why_cost.rs
//! Explaining a closure's fact costs about the proof, not a copy of the relation per step: the
//! proof of the far end of a long chain allocates in step with its own size, on either side.
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use kleene_datalog::{Engine, Facts, Inputs, Output, Program, Proof, Rel, Side};
use kleene_sparse::{CpuBackend, CpuDevice};
struct Counting;
thread_local! {
static BYTES: Cell<usize> = const { Cell::new(0) };
}
// SAFETY: forwards to the system allocator; only counts the bytes asked for.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
BYTES.with(|c| c.set(c.get() + l.size()));
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 {
BYTES.with(|c| c.set(c.get() + n));
unsafe { System.realloc(p, l, n) }
}
}
#[global_allocator]
static A: Counting = Counting;
/// The chain's length: the proof of `t(0, N)` takes `N - 1` closure steps.
const N: u32 = 600;
/// What one step of a proof may allocate: its tuple, binding and premises with room to spare
/// (a copy of the chain's relation is about 20 bytes per edge, so about 12 000 per step).
const PER_STEP: usize = 2000;
/// The proof's depth: closure steps down to the base fact.
fn depth(p: &Proof) -> usize {
match &p.how {
kleene_datalog::How::Rule { premises, .. } => {
1 + premises.iter().map(depth).max().unwrap_or(0)
}
_ => 0,
}
}
/// The bytes the proof of `t(0, N)` allocates, a proof asked once before (what the store
/// builds once is built), and the proof's depth.
fn cost(p: &Program, out: &Output, t: &Rel<2>) -> (usize, usize) {
assert!(out.why(p, t, [1u64, u64::from(N)]).is_some());
let before = BYTES.with(Cell::get);
let proof = out.why(p, t, [0u64, u64::from(N)]).expect("t(0, N) holds");
let bytes = BYTES.with(Cell::get) - before;
(bytes, depth(&proof))
}
#[tokio::test]
async fn a_proof_down_a_chain_allocates_about_its_own_size_on_either_side() {
let edges = Facts::from_rows(2, (0..N).map(|i| vec![i, i + 1])).unwrap();
for side in [Side::Right, Side::Left] {
let mut p = Program::new();
let e = p.input::<2>("e");
let t = p.derived::<2>("t");
let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
p.rule(t.at([x, y]), [e.at([x, y])]).unwrap();
match side {
Side::Right => p.rule(t.at([x, z]), [t.at([x, y]), e.at([y, z])]).unwrap(),
Side::Left => p.rule(t.at([x, z]), [e.at([x, y]), t.at([y, z])]).unwrap(),
};
let mut inputs = Inputs::new();
inputs.facts(&e, edges.clone()).unwrap();
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.explain(true)
.run(&p, &inputs)
.await
.unwrap();
// the deep proof on a thread of its own, with room for its recursion
let (bytes, steps) = std::thread::scope(|s| {
std::thread::Builder::new()
.stack_size(256 << 20)
.spawn_scoped(s, || cost(&p, &out, &t))
.unwrap()
.join()
.unwrap()
});
assert_eq!(steps, N as usize, "{side:?}: one step per edge");
assert!(
bytes < PER_STEP * steps,
"{side:?}: {bytes} bytes for {steps} steps"
);
}
}