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

//! Index lookups chosen by the lowering: a property index for constant bounds on a node of
//! one label, a reach index for `*` and `+` between pinned ends; each answer equal to the
//! plan without indexes and to plain Rust, and `explain` naming what was chosen.

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

use kleene_gql::{Catalog, lower, parse, query};
use kleene_plan::{Engine, External, Facts, Source, Value};
use kleene_sparse::{CpuBackend, CpuDevice};

const FUNC: [u64; 7] = [0, 1, 2, 3, 4, 5, 6];
const LIB: [u64; 3] = [7, 8, 9];
const CALLS: [(u64, u64); 11] = [
    (0, 1),
    (1, 2),
    (2, 0),
    (2, 3),
    (3, 7),
    (4, 5),
    (5, 6),
    (6, 4),
    (1, 8),
    (8, 9),
    (9, 9),
];
const FUNC_SIZE: [(u64, u64); 7] = [(0, 5), (1, 20), (2, 15), (3, 40), (4, 1), (5, 60), (6, 7)];
const LIB_SIZE: [(u64, u64); 3] = [(7, 100), (8, 3), (9, 9)];

/// (lo, hi, id): a plain range index over (id, value) pairs, counting its lookups.
#[derive(Debug)]
struct Range {
    pairs: Vec<(u64, u64)>,
    asked: Arc<AtomicUsize>,
}

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.asked.fetch_add(1, Ordering::Relaxed);
            for &(id, v) in &self.pairs {
                if (lo..=hi).contains(&v) {
                    out(k, &[lo, hi, id]);
                }
            }
        }
        Ok(())
    }
}

/// (a, b): a path of zero or more CALLS edges leads from a to b (a search per key),
/// counting its lookups.
#[derive(Debug)]
struct ReachIdx {
    asked: Arc<AtomicUsize>,
}

impl External for ReachIdx {
    fn arity(&self) -> usize {
        2
    }
    fn can(&self, bound: u64) -> bool {
        bound == 0b11
    }
    fn lookup(
        &self,
        _bound: u64,
        keys: &[&[Value]],
        n: usize,
        out: &mut dyn FnMut(usize, &[Value]),
    ) -> kleene_plan::Result<()> {
        for (k, (&a, &b)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
            self.asked.fetch_add(1, Ordering::Relaxed);
            if reach(a).contains(&b) {
                out(k, &[a, b]);
            }
        }
        Ok(())
    }
}

/// Every vertex `a` reaches by zero or more CALLS edges.
fn reach(a: u64) -> BTreeSet<u64> {
    let mut seen = BTreeSet::from([a]);
    let mut q = VecDeque::from([a]);
    while let Some(x) = q.pop_front() {
        for &(_, y) in CALLS.iter().filter(|e| e.0 == x) {
            if seen.insert(y) {
                q.push_back(y);
            }
        }
    }
    seen
}

/// Every vertex `a` reaches by one or more CALLS edges.
fn reach_plus(a: u64) -> BTreeSet<u64> {
    CALLS
        .iter()
        .filter(|e| e.0 == a)
        .flat_map(|e| reach(e.1))
        .collect()
}

fn ones(xs: &[u64]) -> Source {
    Source::Facts(Facts::from_rows(1, xs.iter().map(|&x| [x])).unwrap())
}

fn twos(xs: &[(u64, u64)]) -> Source {
    Source::Facts(Facts::from_rows(2, xs.iter().map(|&(a, b)| [a, b])).unwrap())
}

fn plain() -> Catalog {
    let mut c = Catalog::new();
    c.label("Func", ones(&FUNC))
        .label("Lib", ones(&LIB))
        .edge("CALLS", twos(&CALLS))
        .property("Func", "size", twos(&FUNC_SIZE))
        .property("Lib", "size", twos(&LIB_SIZE));
    c
}

/// `plain` with a Func.size index and a CALLS reach index; their lookup counts.
fn indexed() -> (Catalog, Arc<AtomicUsize>, Arc<AtomicUsize>) {
    let (ra, rr) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
    let mut c = plain();
    let range: Arc<dyn External> = Arc::new(Range {
        pairs: FUNC_SIZE.to_vec(),
        asked: ra.clone(),
    });
    let reach: Arc<dyn External> = Arc::new(ReachIdx { asked: rr.clone() });
    c.property_index("Func", "size", Source::External(range))
        .reach_index("CALLS", Source::External(reach));
    (c, ra, rr)
}

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

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

fn rows(xs: impl IntoIterator<Item = u64>) -> Vec<Vec<u64>> {
    xs.into_iter().map(|x| vec![x]).collect()
}

#[tokio::test]
async fn property_index_for_constant_bounds() {
    let sized = |f: &dyn Fn(u64) -> bool| -> Vec<Vec<u64>> {
        rows(FUNC_SIZE.iter().filter(|p| f(p.1)).map(|p| p.0))
    };
    let (r, ex, ra, _) = both("MATCH (a:Func) WHERE a.size >= 10 AND a.size < 50 RETURN a").await;
    assert_eq!(r, sized(&|v| (10..50).contains(&v)));
    assert!(
        ra && ex.contains("(a): index lookup Func.size in 10..=49"),
        "{ex}"
    );
    // An equality, written either way round; the equality chosen over a bound.
    let (r, ex, ra, _) = both("MATCH (a:Func) WHERE 15 = a.size AND a.size > 3 RETURN a").await;
    assert_eq!(r, sized(&|v| v == 15));
    assert!(ra && ex.contains("in 15..=15"), "{ex}");
    // A parameter-free empty range: nothing found.
    let (r, ex, _, _) = both("MATCH (a:Func) WHERE a.size > 30 AND a.size <= 30 RETURN a").await;
    assert!(r.is_empty());
    assert!(ex.contains("in 31..=30"), "{ex}");
    // Not by the index: a label with no index, a label alternative, only `<>`.
    for q in [
        "MATCH (a:Lib) WHERE a.size > 5 RETURN a",
        "MATCH (a:Func|Lib) WHERE a.size > 5 RETURN a",
        "MATCH (a:Func) WHERE a.size <> 5 RETURN a",
    ] {
        let (_, ex, ra, _) = both(q).await;
        assert!(
            !ra && !ex.contains("index lookup") && ex.contains("(a): label scan"),
            "{q}: {ex}"
        );
    }
    // An OR of equalities: a lookup per value, the same rows as the scan.
    let (r, ex, ra, _) = both("MATCH (a:Func) WHERE a.size = 5 OR a.size = 7 RETURN a").await;
    assert_eq!(r, sized(&|v| v == 5 || v == 7));
    assert!(
        ra && ex.contains("(a): index lookup Func.size at 5, 7"),
        "{ex}"
    );
    // IN a list (the core's list test): the same lookup per value, the same rows.
    let (r, ex, ra, _) = both("MATCH (a:Func) WHERE a.size IN (7, 5) RETURN a").await;
    assert_eq!(r, sized(&|v| v == 5 || v == 7));
    assert!(
        ra && ex.contains("(a): index lookup Func.size at 5, 7"),
        "{ex}"
    );
    // The lookup in a pattern: callers of a function of size 15.
    let (r, ex, ra, _) =
        both("MATCH (a:Func)-[:CALLS]->(b:Func) WHERE b.size = 15 RETURN a, b").await;
    assert_eq!(r, vec![vec![1, 2]]);
    assert!(
        ra && ex.contains("(b): index lookup") && ex.contains("(a): label scan Func"),
        "{ex}"
    );
}

#[tokio::test]
async fn reach_index_between_pinned_ends() {
    for (a, b) in [(0, 3), (0, 4), (3, 3), (2, 2), (4, 6), (6, 0)] {
        let (r, ex, _, rr) = both(&format!(
            "MATCH (a:Func)-[:CALLS]->*(b:Func) WHERE a = {a} AND b = {b} RETURN a, b"
        ))
        .await;
        let want: Vec<Vec<u64>> = reach(a)
            .contains(&b)
            .then(|| vec![a, b])
            .into_iter()
            .collect();
        assert_eq!(r, want, "{a} *-> {b}");
        assert!(rr && ex.contains("(a)-[:CALLS*]->(b): reach index"), "{ex}");
        let (r, ex, _, rr) = both(&format!(
            "MATCH (a:Func)-[:CALLS]->+(b:Func) WHERE a = {a} AND b = {b} RETURN a"
        ))
        .await;
        let want: Vec<Vec<u64>> = reach_plus(a)
            .contains(&b)
            .then(|| vec![a])
            .into_iter()
            .collect();
        assert_eq!(r, want, "{a} +-> {b}");
        assert!(
            rr && ex.contains("[:CALLS+]") && ex.contains("reach index"),
            "{ex}"
        );
    }
    // Cypher's `*` is one or more: the `+` index form.
    let (r, ex, _, rr) =
        both("MATCH (a:Func)-[:CALLS*]->(b:Func) WHERE a = 3 AND b = 3 RETURN a").await;
    assert!(
        r.is_empty() && rr && ex.contains("(a)-[:CALLS+]->(b): reach index"),
        "{ex}"
    );
    // Ends pinned by a property lookup and a constant.
    let (r, ex, ra, rr) =
        both("MATCH (a:Func)-[:CALLS]->*(b:Lib) WHERE a.size = 20 AND b = 9 RETURN a, b").await;
    assert_eq!(r, vec![vec![1, 9]]);
    assert!(ra && rr && ex.contains("reach index"), "{ex}");
    // One end free: a search, not the index (the strata show the reach).
    let (r, ex, _, rr) = both("MATCH (a:Func)-[:CALLS]->*(b:Func) WHERE a = 4 RETURN b").await;
    assert_eq!(r, rows(reach(4).into_iter().filter(|v| FUNC.contains(v))));
    assert!(
        !rr && !ex.contains("reach index") && ex.contains("stratum:"),
        "{ex}"
    );
    // Bounded lengths and either way are not the index's.
    for q in [
        "MATCH (a:Func)-[:CALLS*1..2]->(b:Func) WHERE a = 0 AND b = 2 RETURN a",
        "MATCH (a:Func)-[:CALLS*]-(b:Func) WHERE a = 0 AND b = 3 RETURN a",
    ] {
        let (_, ex, _, rr) = both(q).await;
        assert!(!rr && !ex.contains("reach index"), "{q}: {ex}");
    }
}