crates/kleene-plan/tests/sparse_ids.rs
//! Graph strata on vertex ids that are not dense: a reach or closure over a few edges whose
//! ids lie far apart (a sentinel at `u32::MAX`, ids over the whole `u32` range, typed codes
//! past it) sizes its matrix by the ids that occur, never by the largest one, and gives the
//! answers and their proofs in the original values. A capping allocator stops the test
//! binary before a miss could take the host: no single allocation over 256 MB and no more
//! than 1 GB live. Alone in its own test binary, since the cap is the whole program's.
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::atomic::{AtomicUsize, Ordering};
use kleene_plan::{
Atom, Datum, Engine, Facts, How, Inputs, Literal, Plan, Proof, RelId, Stratum, Term, Type,
Value, Var, plan,
};
use kleene_sparse::{CpuBackend, CpuDevice};
struct Capped;
const ONE_MAX: usize = 256 << 20;
const LIVE_MAX: usize = 1 << 30;
static LIVE: AtomicUsize = AtomicUsize::new(0);
// SAFETY: forwards to the system allocator; refuses (null: the program stops) a request
// past the caps.
unsafe impl GlobalAlloc for Capped {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
if l.size() > ONE_MAX || LIVE.fetch_add(l.size(), Ordering::Relaxed) + l.size() > LIVE_MAX {
return std::ptr::null_mut();
}
unsafe { System.alloc(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
LIVE.fetch_sub(l.size(), Ordering::Relaxed);
unsafe { System.dealloc(p, l) }
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
if n > ONE_MAX {
return std::ptr::null_mut();
}
LIVE.fetch_add(n, Ordering::Relaxed);
LIVE.fetch_sub(l.size(), Ordering::Relaxed);
unsafe { System.realloc(p, l, n) }
}
}
#[global_allocator]
static A: Capped = Capped;
fn atom(rel: RelId, terms: &[Term]) -> Atom {
Atom {
rel,
terms: terms.to_vec(),
}
}
fn v(x: Var) -> Term {
Term::Var(x)
}
fn engine() -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(2)).explain(true)
}
fn rows(f: &Facts) -> BTreeSet<Vec<u64>> {
f.rows().collect()
}
/// `outer(C, C) :- scope(C, none). outer(C, O) :- scope(C, P), outer(P, O).`
fn scope_plan(none: Value, types: Option<Type>) -> (Plan, RelId, RelId) {
let mut p = Plan::new();
let scope = match types {
None => p.input("scope", 2),
Some(t) => p.input_typed("scope", &[t, t]),
};
let outer = match types {
None => p.derived("outer", 2),
Some(t) => p.derived_typed("outer", &[t, t]),
};
let (c, o, q) = (p.var("C"), p.var("O"), p.var("P"));
p.rule(
atom(outer, &[v(c), v(c)]),
[atom(scope, &[v(c), Term::Const(none)])],
)
.unwrap();
p.rule(
atom(outer, &[v(c), v(o)]),
[
Literal::Pos(atom(scope, &[v(c), v(q)])),
Literal::Pos(atom(outer, &[v(q), v(o)])),
],
)
.unwrap();
(p, scope, outer)
}
/// The scope rules by a plain loop: each child's outermost scope up its parents.
fn outer_by_loop(scope: &[(Value, Value)], none: Value) -> BTreeSet<Vec<u64>> {
let mut out: BTreeSet<Vec<u64>> = scope
.iter()
.filter(|e| e.1 == none)
.map(|e| vec![e.0, e.0])
.collect();
loop {
let mut grown = false;
for &(c, q) in scope {
let ends: Vec<u64> = out.iter().filter(|r| r[0] == q).map(|r| r[1]).collect();
for o in ends {
grown |= out.insert(vec![c, o]);
}
}
if !grown {
return out;
}
}
}
/// Every fact of a proof uses only `values`; its input leaves are input facts.
fn check_proof(pr: &Proof, inputs: &BTreeMap<RelId, BTreeSet<Vec<u64>>>, values: &BTreeSet<u64>) {
for x in &pr.tuple {
assert!(values.contains(x), "{x} in a proof is no id of the input");
}
match &pr.how {
How::Input => assert!(
inputs[&pr.rel].contains(&pr.tuple),
"{:?} is not an input fact",
pr.tuple
),
How::Rule { premises, .. } => {
for q in premises {
check_proof(q, inputs, values);
}
}
h => panic!("unexpected {h:?}"),
}
}
fn is_graph_stratum(p: &Plan, rel: RelId) -> bool {
plan(p).unwrap().iter().any(|s| match s {
Stratum::Closure { rel: r, .. } | Stratum::Reach { rel: r, .. } => *r == rel,
_ => false,
})
}
/// Run the scope rules on `scope` (codes), check them against the loop and check every
/// derived fact's proof; whether the closure renumbered its vertices.
async fn scope_case(scope: &[(Value, Value)], none: Value, types: Option<Type>) -> bool {
let (p, s, outer) = scope_plan(none, types);
// (a typed plan keeps nulls out by conditions, so it runs as joins: the answer counts)
assert!(
types.is_some() || is_graph_stratum(&p, outer),
"a closure stratum"
);
let (a, b): (Vec<Value>, Vec<Value>) = scope.iter().copied().unzip();
let mut inputs = Inputs::new();
inputs.facts(s, Facts::from_columns(vec![a, b]).unwrap());
let out = engine().run(&p, &inputs).await.unwrap();
let got = rows(out.get(outer).unwrap());
assert_eq!(got, outer_by_loop(scope, none));
let ins = BTreeMap::from([(s, scope.iter().map(|e| vec![e.0, e.1]).collect())]);
let values: BTreeSet<u64> = scope.iter().flat_map(|e| [e.0, e.1]).collect();
for t in &got {
let pr = out
.why(&p, outer, t)
.expect("a proof of every derived fact");
assert_eq!(&pr.tuple, t);
check_proof(&pr, &ins, &values);
}
out.report.strata.iter().any(|r| r.renumbered)
}
#[tokio::test]
async fn three_scope_rows_with_the_sentinel_at_u32_max() {
let none = u32::MAX as Value;
let scope = [(0, none), (1, none), (2, 1)];
assert!(scope_case(&scope, none, None).await);
let (p, s, outer) = scope_plan(none, None);
let mut inputs = Inputs::new();
inputs.facts(
s,
Facts::from_columns(vec![vec![0u64, 1, 2], vec![none, none, 1]]).unwrap(),
);
let out = engine().run(&p, &inputs).await.unwrap();
assert_eq!(
rows(out.get(outer).unwrap()),
BTreeSet::from([vec![0, 0], vec![1, 1], vec![2, 1]])
);
let pr = out.why(&p, outer, &[2, 1]).unwrap();
let text = pr.render(&p);
assert!(text.contains("scope(2, 1)"), "{text}");
assert!(text.contains(&format!("scope(1, {none})")), "{text}");
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
/// A forest of `n` scopes over the ids `ids` (parents before children), roots on `none`.
fn forest(ids: &[Value], none: Value, r: &mut Rng) -> Vec<(Value, Value)> {
(0..ids.len())
.map(|i| {
let parent = if i == 0 || r.next().is_multiple_of(5) {
none
} else {
ids[(r.next() % i as u64) as usize]
};
(ids[i], parent)
})
.collect()
}
#[tokio::test]
async fn scope_ids_over_the_whole_u32_range() {
let mut r = Rng(7);
let ids: Vec<Value> = (0..400)
.map(|_| r.next() % (u32::MAX as u64 - 1))
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let scope = forest(&ids, u32::MAX as Value, &mut r);
assert!(scope_case(&scope, u32::MAX as Value, None).await);
}
#[tokio::test]
async fn typed_codes_past_u32() {
// signed ids: every code is past u32 (the sign bit flipped)
let code = |x: i64| Type::I64.encode(&Datum::I64(x), None).unwrap();
let mut r = Rng(11);
let ids: Vec<Value> = (0..300)
.map(|_| code((r.next() % 2_000_001) as i64 - 1_000_000))
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let none = code(i64::MIN + 1);
let scope = forest(&ids, none, &mut r);
scope_case(&scope, none, Some(Type::I64)).await;
// the same codes as plain u64 ids: the closure
assert!(scope_case(&scope, none, None).await);
// and plain u64 ids, one past u32
let scope = [(1u64 << 40, 5), (7, 1 << 40), (9, 7)];
assert!(scope_case(&scope, 5, None).await);
}
#[tokio::test]
async fn dense_ids_keep_the_direct_path() {
let mut r = Rng(3);
let ids: Vec<Value> = (0..2000).collect();
let scope = forest(&ids, 2000, &mut r);
assert!(!scope_case(&scope, 2000, None).await);
}
/// `reach(F) :- entry(F). reach(G) :- reach(F), calls(F, G).` over far-apart ids.
#[tokio::test]
async fn a_reach_over_far_apart_ids() {
let mut p = Plan::new();
let entry = p.input("entry", 1);
let calls = p.input("calls", 2);
let reach = p.derived("reach", 1);
let (f, g) = (p.var("F"), p.var("G"));
p.rule(atom(reach, &[v(f)]), [atom(entry, &[v(f)])])
.unwrap();
p.rule(
atom(reach, &[v(g)]),
[atom(reach, &[v(f)]), atom(calls, &[v(f), v(g)])],
)
.unwrap();
assert!(is_graph_stratum(&p, reach));
let big = |i: u64| i * 40_000_000 + 3;
let edges: Vec<(u64, u64)> = vec![
(big(0), big(1)),
(big(1), big(2)),
(big(2), u32::MAX as u64),
(big(5), big(6)),
(u32::MAX as u64, 1 << 41),
];
let mut inputs = Inputs::new();
inputs
.facts(entry, Facts::from_columns(vec![vec![big(0)]]).unwrap())
.facts(
calls,
Facts::from_columns(vec![
edges.iter().map(|e| e.0).collect::<Vec<u64>>(),
edges.iter().map(|e| e.1).collect::<Vec<u64>>(),
])
.unwrap(),
);
let out = engine().run(&p, &inputs).await.unwrap();
let mut want = BTreeSet::from([big(0)]);
let mut q = VecDeque::from([big(0)]);
while let Some(x) = q.pop_front() {
for e in &edges {
if e.0 == x && want.insert(e.1) {
q.push_back(e.1);
}
}
}
let want: BTreeSet<Vec<u64>> = want.into_iter().map(|x| vec![x]).collect();
assert_eq!(rows(out.get(reach).unwrap()), want);
assert!(out.report.strata.iter().any(|r| r.renumbered));
let ins = BTreeMap::from([
(entry, BTreeSet::from([vec![big(0)]])),
(calls, edges.iter().map(|e| vec![e.0, e.1]).collect()),
]);
let values: BTreeSet<u64> = edges.iter().flat_map(|e| [e.0, e.1]).collect();
for t in &want {
let pr = out.why(&p, reach, t).unwrap();
check_proof(&pr, &ins, &values);
}
}