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

nordisk/kleene

crates/kleene-gql/tests/lookups.rs

//! The common lookups through indexes: a name equality (or `IN`, or a property map) through
//! a name index, signed and float bounds through the range index on order-keeping codes,
//! labels through a kinds index (a union of bitmaps for `A|B`). Each answer equals the
//! plan with no index, and each test counts the index's lookups and reads `explain`.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use arrow_array::{Array, ArrayRef, Float64Array, Int64Array, StringArray, UInt64Array};
use kleene_gql::{Catalog, NameIndex, lower, parse, query};
use kleene_plan::{Datum, Engine, External, Facts, Source, Type, Value};
use kleene_sparse::{CpuBackend, CpuDevice};

/// (id, name, delta, weight, kind): two functions named `lex`, some values null.
type Func = (u64, Option<&'static str>, Option<i64>, Option<f64>, u64);

const FUNCS: [Func; 7] = [
    (0, Some("parse_expr"), Some(-3), Some(1.5), 1),
    (1, Some("lex"), Some(4), Some(-0.25), 2),
    (2, Some("it's"), None, Some(2.0), 1),
    (3, Some("parse"), Some(-3), None, 1),
    (4, None, Some(0), Some(10.0), 3),
    (5, Some("eval_expr"), Some(-7), Some(-2.5), 3),
    (6, Some("lex"), Some(9), Some(0.0), 2),
];
const CALLS: [(u64, u64); 7] = [(0, 1), (1, 2), (0, 3), (3, 5), (5, 4), (6, 0), (3, 6)];

fn col(a: impl Array + 'static) -> ArrayRef {
    Arc::new(a)
}

fn ones(xs: impl IntoIterator<Item = u64>) -> Source {
    Source::Facts(Facts::from_rows(1, xs.into_iter().map(|x| [x])).unwrap())
}

/// The plain catalog: Func, CALLS, typed name / delta / weight, and the kind labels as
/// plain label sets.
fn plain() -> Catalog {
    let ids = || col(UInt64Array::from_iter_values(FUNCS.iter().map(|x| x.0)));
    let mut c = Catalog::new();
    c.label("Func", ones(FUNCS.iter().map(|f| f.0)))
        .edge(
            "CALLS",
            Source::Facts(Facts::from_rows(2, CALLS.iter().map(|&(a, b)| [a, b])).unwrap()),
        )
        .typed_property(
            "Func",
            "name",
            Source::Columns(vec![
                ids(),
                col(StringArray::from(FUNCS.map(|x| x.1).to_vec())),
            ]),
            Type::Str,
        )
        .typed_property(
            "Func",
            "delta",
            Source::Columns(vec![
                ids(),
                col(Int64Array::from(FUNCS.map(|x| x.2).to_vec())),
            ]),
            Type::I64,
        )
        .typed_property(
            "Func",
            "weight",
            Source::Columns(vec![
                ids(),
                col(Float64Array::from(FUNCS.map(|x| x.3).to_vec())),
            ]),
            Type::F64,
        );
    for (label, kind) in [("Parser", 1), ("Lexer", 2), ("Eval", 3)] {
        c.label(
            label,
            ones(FUNCS.iter().filter(|f| f.4 == kind).map(|f| f.0)),
        );
    }
    c
}

/// A test of a function.
type Want<'a> = &'a dyn Fn(&Func) -> bool;

/// Lookups an index was asked.
type Asked = Arc<AtomicUsize>;

#[derive(Debug)]
struct Names(Asked);

impl NameIndex for Names {
    fn nodes(&self, name: &str, out: &mut dyn FnMut(u32)) -> kleene_plan::Result<()> {
        self.0.fetch_add(1, Ordering::Relaxed);
        for f in FUNCS.iter().filter(|f| f.1 == Some(name)) {
            out(f.0 as u32);
        }
        Ok(())
    }
}

/// (lo, hi, id) over (id, code) pairs.
#[derive(Debug)]
struct Range(Vec<(u64, Value)>, Asked);

impl External for Range {
    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_plan::Result<()> {
        for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            self.1.fetch_add(1, Ordering::Relaxed);
            for &(id, c) in &self.0 {
                if (lo..=hi).contains(&c) {
                    out(k, &[lo, hi, id]);
                }
            }
        }
        Ok(())
    }
}

/// (kind, node), answered with the kind bound.
#[derive(Debug)]
struct Kinds(Asked);

impl External for Kinds {
    fn arity(&self) -> usize {
        2
    }
    fn can(&self, bound: u64) -> bool {
        bound & 1 == 1
    }
    fn lookup(
        &self,
        bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        for (k, &kind) in keys[0].iter().enumerate().take(n) {
            self.0.fetch_add(1, Ordering::Relaxed);
            for f in FUNCS.iter().filter(|f| f.4 == kind) {
                if bound & 2 == 0 || keys[1][k] == f.0 {
                    out(k, &[kind, f.0]);
                }
            }
        }
        Ok(())
    }
}

/// `plain` with every index, and the lookups each is asked: names, ranges, kinds.
fn indexed() -> (Catalog, [Asked; 3]) {
    let asked: [Asked; 3] = std::array::from_fn(|_| Arc::new(AtomicUsize::new(0)));
    let mut c = plain();
    let codes = |ty: Type, f: &dyn Fn(&Func) -> Option<Datum>| -> Vec<(u64, Value)> {
        FUNCS
            .iter()
            .filter_map(|x| Some((x.0, ty.encode(&f(x)?, None)?)))
            .collect()
    };
    let delta = codes(Type::I64, &|x| x.2.map(Datum::I64));
    let weight = codes(Type::F64, &|x| x.3.map(Datum::F64));
    c.name_index("Func", "name", Arc::new(Names(asked[0].clone())))
        .property_index(
            "Func",
            "delta",
            Source::External(Arc::new(Range(delta, asked[1].clone()))),
        )
        .property_index(
            "Func",
            "weight",
            Source::External(Arc::new(Range(weight, asked[1].clone()))),
        )
        .kinds_index("kind", Source::External(Arc::new(Kinds(asked[2].clone()))));
    for (label, kind) in [("Parser", 1), ("Lexer", 2), ("Eval", 3)] {
        c.kind_label(label, "kind", kind);
    }
    (c, asked)
}

fn engine() -> Engine<CpuBackend> {
    Engine::new(CpuDevice::new(2))
}

/// The rows on both catalogs (equal), the indexed plan's explain text and the lookups each
/// index was asked.
async fn both(text: &str) -> (Vec<Vec<u64>>, String, [usize; 3]) {
    let e = engine();
    let want = query(&e, &plain(), text)
        .await
        .unwrap_or_else(|err| panic!("{text}: {err}"));
    let (c, asked) = indexed();
    let got = query(&e, &c, text)
        .await
        .unwrap_or_else(|err| panic!("{text} (indexed): {err}"));
    assert_eq!(got.rows, want.rows, "{text}");
    let ex = lower(&parse(text).unwrap(), &c).unwrap().explain().unwrap();
    (got.rows, ex, asked.map(|a| a.load(Ordering::Relaxed)))
}

fn rows(f: impl Fn(&Func) -> bool) -> Vec<Vec<u64>> {
    FUNCS.iter().filter(|x| f(x)).map(|x| vec![x.0]).collect()
}

#[tokio::test]
async fn names_through_the_name_index() {
    for q in [
        "MATCH (f:Func {name: \"lex\"}) RETURN f",
        "MATCH (f:Func) WHERE f.name = \"lex\" RETURN f",
        "MATCH (f:Func) WHERE \"lex\" = f.name RETURN f",
    ] {
        let (r, ex, asked) = both(q).await;
        assert_eq!(r, rows(|x| x.1 == Some("lex")), "{q}");
        assert!(
            asked[0] > 0 && ex.contains("(f): name index Func.name for \"lex\""),
            "{q}: {ex}"
        );
    }
    let (r, ex, asked) =
        both("MATCH (f:Func) WHERE f.name IN [\"lex\", \"parse\", \"nope\"] RETURN f").await;
    assert_eq!(r, rows(|x| matches!(x.1, Some("lex" | "parse"))));
    assert!(
        asked[0] == 3 && ex.contains("for \"lex\", \"parse\", \"nope\""),
        "{ex}"
    );
    // A name no node has; a property map on an unnamed node inside a pattern.
    let (r, _, asked) = both("MATCH (f:Func {name: 'nope'}) RETURN f").await;
    assert!(r.is_empty() && asked[0] == 1);
    let (r, ex, asked) = both("MATCH (a:Func)-[:CALLS]->(:Func {name: \"lex\"}) RETURN a").await;
    let callers: Vec<Vec<u64>> = {
        let mut v: Vec<u64> = CALLS
            .iter()
            .filter(|e| FUNCS[e.1 as usize].1 == Some("lex"))
            .map(|e| e.0)
            .collect();
        v.sort_unstable();
        v.dedup();
        v.into_iter().map(|x| vec![x]).collect()
    };
    assert_eq!(r, callers);
    assert!(asked[0] > 0 && ex.contains("name index"), "{ex}");
    // Not by the index: a string range, a text test, an OR over two properties.
    for q in [
        "MATCH (f:Func) WHERE f.name > \"m\" RETURN f",
        "MATCH (f:Func) WHERE f.name STARTS WITH \"pa\" RETURN f",
        "MATCH (f:Func) WHERE f.name = \"lex\" OR f.delta = 0 RETURN f",
    ] {
        let (_, ex, asked) = both(q).await;
        assert!(asked[0] == 0 && !ex.contains("name index"), "{q}: {ex}");
    }
}

#[tokio::test]
async fn signed_and_float_bounds_through_the_range_index() {
    let cases: [(&str, Want, &str); 5] = [
        ("f.delta < 0", &|x| x.2.is_some_and(|d| d < 0), "Func.delta"),
        (
            "f.delta >= -3 AND f.delta <= 4",
            &|x| x.2.is_some_and(|d| (-3..=4).contains(&d)),
            "Func.delta",
        ),
        ("f.delta = -3", &|x| x.2 == Some(-3), "Func.delta"),
        (
            "f.weight > 1.0",
            &|x| x.3.is_some_and(|w| w > 1.0),
            "Func.weight",
        ),
        (
            "f.weight <= 0",
            &|x| x.3.is_some_and(|w| w <= 0.0),
            "Func.weight",
        ),
    ];
    for (cond, want, key) in cases {
        let q = format!("MATCH (f:Func) WHERE {cond} RETURN f");
        let (r, ex, asked) = both(&q).await;
        assert_eq!(r, rows(want), "{q}");
        assert!(
            asked[1] > 0 && ex.contains(&format!("(f): index lookup {key} in ")),
            "{q}: {ex}"
        );
    }
    // A null is no value: `> anything` never finds node 2's missing delta (the null code
    // is past the range's top).
    let (r, ex, _) = both("MATCH (f:Func) WHERE f.delta > -100 RETURN f").await;
    assert_eq!(r, rows(|x| x.2.is_some()));
    assert!(
        ex.contains(&format!("..={}", kleene_plan::NULL - 1)),
        "{ex}"
    );
}

#[tokio::test]
async fn labels_through_the_kinds_index() {
    let (r, ex, asked) = both("MATCH (f:Parser) RETURN f").await;
    assert_eq!(r, rows(|x| x.4 == 1));
    assert!(
        asked[2] > 0 && ex.contains("(f): kinds index kind Parser"),
        "{ex}"
    );
    let (r, ex, asked) = both("MATCH (f:Parser|Lexer) RETURN f").await;
    assert_eq!(r, rows(|x| x.4 <= 2));
    assert!(
        asked[2] >= 2 && ex.contains("kinds index kind Lexer|Parser"),
        "{ex}"
    );
    let (r, ex, asked) = both("MATCH (a:Parser)-[:CALLS]->(b:Lexer|Eval) RETURN a, b").await;
    let mut want: Vec<Vec<u64>> = CALLS
        .iter()
        .filter(|e| FUNCS[e.0 as usize].4 == 1 && FUNCS[e.1 as usize].4 >= 2)
        .map(|e| vec![e.0, e.1])
        .collect();
    want.sort();
    assert_eq!(r, want);
    assert!(
        asked[2] > 0 && ex.contains("(b): kinds index kind Eval|Lexer"),
        "{ex}"
    );
    // A kind with a plain label: a label scan.
    let (_, ex, asked) = both("MATCH (f:Parser|Func) RETURN f").await;
    assert!(asked[2] == 0 && ex.contains("label scan"), "{ex}");
}