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

nordisk/kleene

crates/kleene-datalog/tests/labelled.rs

//! Labelled-edge reach, `r(E, T) :- r(E, S), edge(S, T, L), has(L, E)`: planned as one
//! entry-bitmask walk on kleene-graph, its facts equal the same rules planned as joins
//! and a plain search per entry; its proofs walk back to a seed along fewest steps, each
//! step on an edge whose label holds the entry.

use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};

use kleene_datalog::{Engine, Facts, How, Inputs, Program, Proof, Rel, RuleId, Value, lt};
use kleene_sparse::{CpuBackend, CpuDevice};

type E = Engine<CpuBackend>;

struct Lcg(u64);

impl Lcg {
    fn next(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0 >> 11
    }
}

/// Entries are wide values, so are labels; vertices are ids.
const ENTRY0: u64 = 1 << 40;
const LABEL0: u64 = 7 << 36;

struct Data {
    start: Vec<[u64; 2]>,
    /// (label, source, target): the edge relation's columns in another order than the
    /// rule's variables.
    edge: Vec<[u64; 3]>,
    has: Vec<[u64; 2]>,
}

fn data(seed: u64, n: u64, m: usize, entries: u64, labels: u64) -> Data {
    let mut r = Lcg(seed);
    let start = (0..entries * 2)
        .map(|i| [ENTRY0 + i % entries, r.next() % n])
        .collect();
    let mut edge = Vec::new();
    for _ in 0..m {
        let (s, t) = (r.next() % n, r.next() % n);
        // labels past `labels` are in no `has` row: such edges pass nobody
        edge.push([LABEL0 + r.next() % (labels + 2), s, t]);
        if r.next().is_multiple_of(4) {
            // a second label on the same edge
            edge.push([LABEL0 + r.next() % labels, s, t]);
        }
    }
    let mut has = Vec::new();
    for l in 0..labels {
        for e in 0..entries {
            if r.next().is_multiple_of(3) {
                has.push([LABEL0 + l, ENTRY0 + e]);
            }
        }
    }
    // an entry no seed names: it reaches nothing
    has.push([LABEL0, ENTRY0 + entries + 5]);
    Data { start, edge, has }
}

/// Per entry, the vertex distances from its seeds along the edges its labels pass.
fn reference(d: &Data) -> HashMap<u64, HashMap<u64, u32>> {
    let has: HashSet<(u64, u64)> = d.has.iter().map(|h| (h[0], h[1])).collect();
    let entries: BTreeSet<u64> = d.start.iter().map(|s| s[0]).collect();
    let mut out = HashMap::new();
    for &e in &entries {
        let mut adj: HashMap<u64, Vec<u64>> = HashMap::new();
        for &[l, s, t] in &d.edge {
            if has.contains(&(l, e)) {
                adj.entry(s).or_default().push(t);
            }
        }
        let mut dist: HashMap<u64, u32> = HashMap::new();
        let mut q = VecDeque::new();
        for s in d.start.iter().filter(|s| s[0] == e) {
            if dist.insert(s[1], 0).is_none() {
                q.push_back(s[1]);
            }
        }
        while let Some(v) = q.pop_front() {
            let dv = dist[&v];
            for &w in adj.get(&v).map(Vec::as_slice).unwrap_or(&[]) {
                if let std::collections::hash_map::Entry::Vacant(x) = dist.entry(w) {
                    x.insert(dv + 1);
                    q.push_back(w);
                }
            }
        }
        out.insert(e, dist);
    }
    out
}

struct Prog {
    p: Program,
    start: Rel<2>,
    edge: Rel<3>,
    has: Rel<2>,
    has_el: Rel<2>,
    /// The walk: `r(E, T)`.
    r: Rel<2>,
    /// The same rules with a condition that always holds: planned as joins.
    j: Rel<2>,
    /// The entry second and `has` as (entry, label): `q(T, E)`.
    q: Rel<2>,
    base: RuleId,
    step: RuleId,
}

fn program() -> Prog {
    let mut p = Program::new();
    let start = p.input::<2>("start");
    let edge = p.input::<3>("edge");
    let has = p.input::<2>("has");
    let has_el = p.input::<2>("has_el");
    let r = p.derived::<2>("r");
    let j = p.derived::<2>("j");
    let q = p.derived::<2>("q");
    let (e, s, t, l, v) = (p.var("E"), p.var("S"), p.var("T"), p.var("L"), p.var("V"));
    let base = p.rule(r.at([e, v]), [start.at([e, v])]).unwrap();
    let step = p
        .rule(
            r.at([e, t]),
            [edge.at([l, s, t]), r.at([e, s]), has.at([l, e])],
        )
        .unwrap();
    p.rule(j.at([e, v]), [start.at([e, v])]).unwrap();
    p.rule(
        j.at([e, t]),
        [
            j.at([e, s]).into(),
            edge.at([l, s, t]).into(),
            has.at([l, e]).into(),
            lt(t, u64::MAX),
        ],
    )
    .unwrap();
    p.rule(q.at([v, e]), [start.at([e, v])]).unwrap();
    p.rule(
        q.at([t, e]),
        [q.at([s, e]), has_el.at([e, l]), edge.at([l, s, t])],
    )
    .unwrap();
    Prog {
        p,
        start,
        edge,
        has,
        has_el,
        r,
        j,
        q,
        base,
        step,
    }
}

fn inputs(g: &Prog, d: &Data) -> Inputs {
    let mut i = Inputs::new();
    i.facts(&g.start, Facts::from_rows(2, d.start.iter()).unwrap())
        .unwrap();
    i.facts(&g.edge, Facts::from_rows(3, d.edge.iter()).unwrap())
        .unwrap();
    i.facts(&g.has, Facts::from_rows(2, d.has.iter()).unwrap())
        .unwrap();
    let el: Vec<[u64; 2]> = d.has.iter().map(|h| [h[1], h[0]]).collect();
    i.facts(&g.has_el, Facts::from_rows(2, el.iter()).unwrap())
        .unwrap();
    i
}

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

#[tokio::test]
async fn the_walk_equals_the_join_plan_and_plain_searches() {
    let g = program();
    for (seed, entries) in [(1u64, 40u64), (2, 150)] {
        let d = data(seed, 400, 1600, entries, 12);
        let want: BTreeSet<Vec<Value>> = reference(&d)
            .iter()
            .flat_map(|(&e, dist)| dist.keys().map(move |&v| vec![e, v]))
            .collect();
        assert!(want.len() > 4 * d.start.len(), "the walk spreads");
        let ins = inputs(&g, &d);
        for threads in [1, 8] {
            let out = E::new(CpuDevice::new(threads))
                .run(&g.p, &ins)
                .await
                .unwrap();
            let kind = |name: &str| {
                out.report
                    .strata
                    .iter()
                    .find(|s| s.relations == [name])
                    .unwrap()
                    .kind
            };
            assert_eq!(kind("r"), "labelled reach (kleene-graph mask walk)");
            assert_eq!(kind("q"), "labelled reach (kleene-graph mask walk)");
            assert_eq!(kind("j"), "joins (column kernels)");
            assert_eq!(rows(out.get(&g.r).unwrap()), want);
            assert_eq!(rows(out.get(&g.j).unwrap()), want);
            let q: BTreeSet<Vec<Value>> = want.iter().map(|x| vec![x[1], x[0]]).collect();
            assert_eq!(rows(out.get(&g.q).unwrap()), q);
        }
    }
}

/// The steps from `proof` (a fact of `r`) back to its seed, each checked against the
/// inputs.
fn steps_back(g: &Prog, d: &Data, mut proof: &Proof) -> u32 {
    let edges: HashSet<Vec<u64>> = d.edge.iter().map(|e| e.to_vec()).collect();
    let has: HashSet<Vec<u64>> = d.has.iter().map(|h| h.to_vec()).collect();
    let mut steps = 0;
    loop {
        let How::Rule { rule, premises, .. } = &proof.how else {
            panic!("a rule proves {:?}", proof.tuple);
        };
        if *rule == g.base {
            assert_eq!(premises.len(), 1);
            assert!(matches!(premises[0].how, How::Input));
            assert_eq!(premises[0].tuple, proof.tuple);
            return steps;
        }
        assert_eq!(*rule, g.step);
        let [edge, own, h] = &premises[..] else {
            panic!("three premises")
        };
        assert!(matches!(edge.how, How::Input) && edges.contains(&edge.tuple));
        assert!(matches!(h.how, How::Input) && has.contains(&h.tuple));
        // edge(L, S, T), r(E, S), has(L, E), r(E, T)
        assert_eq!(edge.tuple[0], h.tuple[0]);
        assert_eq!(own.tuple[0], proof.tuple[0]);
        assert_eq!(h.tuple[1], proof.tuple[0]);
        assert_eq!(edge.tuple[1], own.tuple[1]);
        assert_eq!(edge.tuple[2], proof.tuple[1]);
        steps += 1;
        proof = own;
    }
}

#[tokio::test]
async fn proofs_walk_back_along_edges_the_entry_passes() {
    let g = program();
    let d = data(3, 300, 1200, 70, 9);
    let dist = reference(&d);
    let out = E::new(CpuDevice::new(4))
        .explain(true)
        .run(&g.p, &inputs(&g, &d))
        .await
        .unwrap();
    let facts = out.get(&g.r).unwrap();
    let mut far = 0;
    for (i, row) in facts.rows().enumerate() {
        if i % 7 != 0 {
            continue;
        }
        let proof = out.why(&g.p, &g.r, [row[0], row[1]]).expect("a proof");
        let steps = steps_back(&g, &d, &proof);
        assert_eq!(steps, dist[&row[0]][&row[1]], "fewest steps for {row:?}");
        far = far.max(steps);
        let text = proof.render(&g.p);
        assert_eq!(steps > 0, text.contains("has("), "{text}");
    }
    assert!(far >= 3, "some proofs take several steps");
    // a pair the walk did not reach has no proof
    let e = d.start[0][0];
    let missing = (0..300u64).find(|v| !dist[&e].contains_key(v)).unwrap();
    assert!(out.why(&g.p, &g.r, [e, missing]).is_none());
}

#[tokio::test]
async fn other_shapes_are_planned_as_joins_and_agree() {
    // has(L, S): the label must hold the edge's source, not the entry: not the walk
    let mut p = Program::new();
    let start = p.input::<2>("start");
    let edge = p.input::<3>("edge");
    let has = p.input::<2>("has");
    let r = p.derived::<2>("r");
    let (e, s, t, l, v) = (p.var("E"), p.var("S"), p.var("T"), p.var("L"), p.var("V"));
    p.rule(r.at([e, v]), [start.at([e, v])]).unwrap();
    p.rule(
        r.at([e, t]),
        [r.at([e, s]), edge.at([s, t, l]), has.at([l, s])],
    )
    .unwrap();
    let mut ins = Inputs::new();
    ins.facts(&start, Facts::from_rows(2, [[1u64, 0], [2, 3]]).unwrap())
        .unwrap();
    ins.facts(
        &edge,
        Facts::from_rows(3, [[0u64, 1, 9], [1, 2, 9], [3, 4, 8]]).unwrap(),
    )
    .unwrap();
    ins.facts(
        &has,
        Facts::from_rows(2, [[9u64, 0], [9, 1], [8, 4]]).unwrap(),
    )
    .unwrap();
    let out = E::new(CpuDevice::new(1)).run(&p, &ins).await.unwrap();
    assert_eq!(out.report.strata[0].kind, "joins (column kernels)");
    let want: BTreeSet<Vec<Value>> = [[1u64, 0], [1, 1], [1, 2], [2, 3]]
        .iter()
        .map(|x| x.to_vec())
        .collect();
    assert_eq!(rows(out.get(&r).unwrap()), want);
}