Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/tests/split.rs

//! A plan run split over parts ([`Engine::split`]) gives the one-machine answers: reach
//! both ways, closure right- and left-linear, weak components, shortest paths (weighted or
//! not), on graphs split 2, 3 and 8 ways; a plan that does not split is refused for the
//! split and still answers on one machine.

use std::collections::BTreeSet;

use kleene_graph::SplitKey;
use kleene_plan::{
    Atom, Engine, Facts, Inputs, Literal, Plan, PlanError, Procedure, RelId, Term, Var,
};
use kleene_sparse::{CpuBackend, CpuDevice};

fn atom<const K: usize>(rel: RelId, terms: [Var; K]) -> Atom {
    Atom {
        rel,
        terms: terms.iter().map(|&v| Term::Var(v)).collect(),
    }
}

/// Edges of a graph of 3 rings of 20 joined one after the other and back, chords, a tail
/// and a lone vertex 70 with a self-loop: 71 vertices.
fn edges() -> Vec<[u32; 2]> {
    let mut e = Vec::new();
    for r in 0..3u32 {
        for i in 0..20 {
            e.push([r * 20 + i, r * 20 + (i + 1) % 20]);
            if i % 6 == 0 {
                e.push([r * 20 + i, (r * 20 + i + 31) % 60]);
            }
        }
    }
    e.push([59, 60]);
    for t in 60..69 {
        e.push([t, t + 1]);
    }
    e.push([70, 70]);
    e
}

fn keys() -> Vec<SplitKey> {
    vec![
        SplitKey::Hash(2),
        SplitKey::Hash(3),
        SplitKey::Hash(8),
        SplitKey::Blocks(vec![0, 20, 40, 60]),
        SplitKey::Property((0..71).map(|v| v % 3).collect()),
    ]
}

fn rows(f: &Facts) -> BTreeSet<Vec<u64>> {
    f.rows().collect()
}

/// The program: reach both ways from `entry`, a right- and a left-linear closure, weak
/// components, shortest paths from 3 with and without weights.
fn program() -> (Plan, Vec<RelId>, Inputs) {
    let mut p = Plan::new();
    let entry = p.input("entry", 1);
    let e = p.input("e", 2);
    let w = p.input("w", 3);
    let fwd = p.derived("fwd", 1);
    let back = p.derived("back", 1);
    let right = p.derived("right", 2);
    let left = p.derived("left", 2);
    let wcc = p.derived("wcc", 2);
    let hops = p.derived("hops", 2);
    let dist = p.derived("dist", 2);
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    p.rule(atom(fwd, [x]), [atom(entry, [x])]).unwrap();
    p.rule(atom(fwd, [y]), [atom(fwd, [x]), atom(e, [x, y])])
        .unwrap();
    p.rule(atom(back, [x]), [atom(entry, [x])]).unwrap();
    p.rule(atom(back, [x]), [atom(back, [y]), atom(e, [x, y])])
        .unwrap();
    p.rule(atom(right, [x, y]), [atom(e, [x, y])]).unwrap();
    p.rule(atom(right, [x, z]), [atom(right, [x, y]), atom(e, [y, z])])
        .unwrap();
    p.rule(atom(left, [x, y]), [atom(e, [x, y])]).unwrap();
    p.rule(atom(left, [x, z]), [atom(e, [x, y]), atom(left, [y, z])])
        .unwrap();
    p.procedure(wcc, e, Procedure::WeakComponents).unwrap();
    p.procedure(
        hops,
        e,
        Procedure::Sssp {
            source: 3,
            weights: None,
        },
    )
    .unwrap();
    p.procedure(
        dist,
        e,
        Procedure::Sssp {
            source: 3,
            weights: Some(w),
        },
    )
    .unwrap();
    let es = edges();
    let mut inputs = Inputs::new();
    inputs
        .facts(entry, Facts::from_rows(1, [[25u32], [65]]).unwrap())
        .facts(e, Facts::from_rows(2, es.iter().copied()).unwrap())
        .facts(
            w,
            Facts::from_rows(3, es.iter().map(|&[a, b]| [a, b, 1 + (a * 7 + b) % 5])).unwrap(),
        );
    (p, vec![fwd, back, right, left, wcc, hops, dist], inputs)
}

#[tokio::test]
async fn a_split_run_gives_the_one_machine_answers() {
    let (p, out, inputs) = program();
    let one: Engine<CpuBackend> = Engine::new(CpuDevice::new(4));
    let want = one.run(&p, &inputs).await.unwrap();
    for r in &out {
        assert!(!want.get(*r).unwrap().is_empty());
    }
    for key in keys() {
        let split: Engine<CpuBackend> = Engine::new(CpuDevice::new(4)).split(key.clone());
        let got = split.run(&p, &inputs).await.unwrap();
        for &r in &out {
            assert_eq!(
                rows(got.get(r).unwrap()),
                rows(want.get(r).unwrap()),
                "{key:?}: {}",
                p.relation_info(r).name
            );
        }
    }
}

#[tokio::test]
async fn a_plan_that_does_not_split_is_refused_for_the_split_and_answers_on_one_machine() {
    let mut p = Plan::new();
    let e = p.input("e", 2);
    let tc = p.derived("tc", 2);
    let rank = p.derived("rank", 2);
    let (x, y, z) = (p.var("X"), p.var("Y"), p.var("Z"));
    // A closure squared (non-linear recursion over joins) and PageRank: neither splits.
    p.rule(atom(tc, [x, y]), [atom(e, [x, y])]).unwrap();
    p.rule(
        atom(tc, [x, z]),
        [
            Literal::Pos(atom(tc, [x, y])),
            Literal::Pos(atom(tc, [y, z])),
        ],
    )
    .unwrap();
    p.procedure(rank, e, Procedure::PageRank).unwrap();
    let mut inputs = Inputs::new();
    inputs.facts(e, Facts::from_rows(2, edges()).unwrap());
    let strata = kleene_plan::plan(&p).unwrap();
    assert!(strata.iter().any(|s| !s.splittable(&p)));
    let split: Engine<CpuBackend> = Engine::new(CpuDevice::new(2)).split(SplitKey::Hash(3));
    assert!(matches!(
        split.run(&p, &inputs).await,
        Err(PlanError::NotSplittable(_))
    ));
    let one: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = one.run(&p, &inputs).await.unwrap();
    assert!(!out.get(tc).unwrap().is_empty());
    assert_eq!(out.get(rank).unwrap().len(), 71);
    // The why of a split run is refused too; the program above splits otherwise.
    let (q, _, ins) = program();
    let why: Engine<CpuBackend> = Engine::new(CpuDevice::new(2))
        .explain(true)
        .split(SplitKey::Hash(2));
    assert!(matches!(
        why.run(&q, &ins).await,
        Err(PlanError::NotSplittable(_))
    ));
    assert!(
        kleene_plan::plan(&q)
            .unwrap()
            .iter()
            .all(|s| s.splittable(&q))
    );
}