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/index_choice_why.rs

//! The proof of a fact is the same with the index choice on as off: it names the author's
//! rule and atoms, never a relation the pass put in. Each rewritten shape: an equality on a
//! property with a range index, an equality on a string with a name index, an OR of
//! equalities (two rules: Datalog has no OR in a rule), a range, an id range of a label's
//! block, the index lookup written by hand, and a recursive rule whose base case is
//! rewritten.

use std::collections::BTreeSet;
use std::sync::Arc;

use arrow_array::{ArrayRef, StringArray, UInt64Array};
use kleene_datalog::{
    Catalog, Engine, External, Inputs, Program, Rel, Source, Term, Value, eq, ge, lt,
};
use kleene_plan::NameIndex;
use kleene_sparse::{CpuBackend, CpuDevice};

const N: u64 = 120;
const BASE: u64 = 40;

fn size(i: u64) -> u64 {
    (i * 7) % 30
}

fn name(i: u64) -> String {
    format!("f{}", i % 11)
}

/// (lo, hi, id) for the ids whose size lies in lo..=hi.
#[derive(Debug)]
struct SizeIndex;

impl External for SizeIndex {
    fn arity(&self) -> usize {
        3
    }
    fn can(&self, bound: u64) -> bool {
        bound & 0b11 == 0b11
    }
    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_datalog::Result<()> {
        for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            for i in 0..N {
                if (lo..=hi).contains(&size(i)) {
                    out(k, &[lo, hi, BASE + i]);
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
struct Names;

impl NameIndex for Names {
    fn nodes(&self, s: &str, out: &mut dyn FnMut(u32)) -> kleene_datalog::Result<()> {
        for i in 0..N {
            if name(i) == s {
                out((BASE + i) as u32);
            }
        }
        Ok(())
    }
}

/// Functions with ids `BASE..BASE + N` (an id block), a size with a range index, a name
/// with a name index; calls from each function to the next two.
fn catalog() -> Catalog {
    let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
    let ids = u((BASE..BASE + N).collect());
    let mut c = Catalog::new();
    c.label("func", Source::Columns(vec![ids.clone()]))
        .id_block("func", BASE, N)
        .property(
            "func",
            "size",
            Source::Columns(vec![ids.clone(), u((0..N).map(size).collect())]),
        )
        .property_index("func", "size", Source::External(Arc::new(SizeIndex)))
        .typed_property(
            "func",
            "name",
            Source::Columns(vec![
                ids,
                Arc::new(StringArray::from_iter_values((0..N).map(name))),
            ]),
            kleene_datalog::Type::Str,
        )
        .name_index("func", "name", Arc::new(Names));
    c
}

/// Each relation's facts with the proof of each, rendered, from a run with the choice on
/// or off.
async fn proofs(on: bool) -> (Vec<(String, BTreeSet<Vec<u64>>, Vec<String>)>, Vec<String>) {
    let c = catalog();
    let mut p = Program::new();
    let func = p.input_from::<1>(&c, "func").unwrap();
    let size_of = p.input_from::<2>(&c, "func.size").unwrap();
    let name_of = p.input_from::<2>(&c, "func.name").unwrap();
    let calls = p.input::<2>("calls");
    let idx = p.external::<3>("size_index");
    let (f, g, s, x) = (p.var("F"), p.var("G"), p.var("S"), p.var("X"));
    let k = |v: u64| Term::Const(v);
    let mut rels: Vec<(&str, Rel<1>)> = Vec::new();
    // an equality on a property with a range index
    let seven = p.derived::<1>("seven");
    p.rule(
        seven.at([f]),
        [func.at([f]).into(), size_of.at([f, s]).into(), eq(s, k(7))],
    )
    .unwrap();
    rels.push(("seven", seven));
    // an equality on a string with a name index
    let f3 = p.str("f3");
    let named = p.derived::<1>("named");
    p.rule(
        named.at([f]),
        [func.at([f]).into(), name_of.at([f, x]).into(), eq(x, f3)],
    )
    .unwrap();
    rels.push(("named", named));
    // an OR of equalities: a rule per value
    let either = p.derived::<1>("either");
    for v in [4, 11] {
        p.rule(
            either.at([f]),
            [func.at([f]).into(), size_of.at([f, s]).into(), eq(s, k(v))],
        )
        .unwrap();
    }
    rels.push(("either", either));
    // a range
    let mid = p.derived::<1>("mid");
    p.rule(
        mid.at([f]),
        [
            func.at([f]).into(),
            size_of.at([f, s]).into(),
            ge(s, k(20)),
            lt(s, k(23)),
        ],
    )
    .unwrap();
    rels.push(("mid", mid));
    // an id range of the label's block
    let low = p.derived::<1>("low");
    p.rule(low.at([f]), [func.at([f]).into(), lt(f, k(BASE + 5))])
        .unwrap();
    rels.push(("low", low));
    // the index lookup written by hand
    let hand = p.derived::<1>("hand");
    p.rule(
        hand.at([f]),
        [
            idx.atom([k(20), k(22), f.into()]).into(),
            size_of.at([f, s]).into(),
            ge(s, k(20)),
            lt(s, k(23)),
        ],
    )
    .unwrap();
    rels.push(("hand", hand));
    // a recursive rule whose base case is rewritten
    let reach = p.derived::<1>("reach");
    p.rule(
        reach.at([f]),
        [func.at([f]).into(), size_of.at([f, s]).into(), eq(s, k(0))],
    )
    .unwrap();
    p.rule(reach.at([g]), [reach.at([f]), calls.at([f, g])])
        .unwrap();
    rels.push(("reach", reach));
    let mut inputs = Inputs::new();
    let from: Vec<u64> = (BASE..BASE + N - 2).flat_map(|i| [i, i]).collect();
    let to: Vec<u64> = (BASE..BASE + N - 2).flat_map(|i| [i + 1, i + 2]).collect();
    let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
    inputs.columns(&calls, [u(from), u(to)]);
    inputs.external(&idx, Arc::new(SizeIndex)).unwrap();
    inputs.bind(&p, &c).unwrap();
    let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2))
        .index_choice(on)
        .explain(true);
    let out = e.run(&p, &inputs).await.unwrap();
    let ran: Vec<String> = out
        .report
        .strata
        .iter()
        .flat_map(|s| s.relations.clone())
        .collect();
    let shown = rels
        .iter()
        .map(|(n, r)| {
            let rows: BTreeSet<Vec<u64>> = out.get(r).unwrap().rows().collect();
            let shown = rows
                .iter()
                .take(6)
                .map(|t| {
                    let proof = out.why(&p, r, [t[0]]).expect("a proof");
                    out.render(&p, &proof)
                })
                .collect();
            (n.to_string(), rows, shown)
        })
        .collect();
    (shown, ran)
}

#[tokio::test]
async fn a_proof_names_the_rule_as_written_with_the_choice_on_and_off() {
    let (off, ran_off) = proofs(false).await;
    let (on, ran_on) = proofs(true).await;
    let made = |n: &str| n.ends_with(" found") || n.contains(" asked once");
    assert!(!ran_off.iter().any(|n| made(n)), "{ran_off:?}");
    for (name, _, _) in &on {
        // each shape ran through a relation the pass made (its lookup)
        assert!(
            ran_on
                .iter()
                .any(|n| made(n) && n.starts_with(&format!("{name}: "))),
            "{name} is rewritten: {ran_on:?}"
        );
    }
    for ((name, rows_off, off), (_, rows_on, on)) in off.iter().zip(&on) {
        assert!(!rows_off.is_empty(), "{name} derives facts");
        assert_eq!(rows_off, rows_on, "{name}: the same facts");
        for (a, b) in off.iter().zip(on) {
            assert_eq!(a, b, "{name}: the same proof");
            assert!(
                !b.contains(" found") && !b.contains(": range") && !b.contains("asked once"),
                "{name}: a proof names no relation the pass made:\n{b}"
            );
        }
    }
}