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

//! Whole values in more places, on a small library in one id space (Book 0..3, Shelf 3..5,
//! Reader 5..7, as `kleene gql` reads a set): a node carried through `WITH` or yielded by
//! a procedure, whole nodes and edges with `UNION`, with aggregates (as group keys and
//! inside `count`) and with `OPTIONAL MATCH` (null where it does not extend a row), and
//! `relationships(p)` of a shortest path. Each answer against a plain loop over the rows.

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use kleene_gql::{Catalog, Entity, GqlError, Params, Table, lower_with, parse};
use kleene_plan::{Datum, Engine, Facts, Source};
use kleene_sparse::{CpuBackend, CpuDevice};

const PAGES: [u64; 3] = [120, 340, 90];
const FLOOR: [u64; 2] = [1, 2];
const AGE: [u64; 2] = [31, 47];
/// Book -> Shelf, slot.
const ON: [(u64, u64, u64); 3] = [(0, 3, 7), (1, 3, 8), (2, 4, 9)];
/// Reader -> Book, minutes.
const READ: [(u64, u64, u64); 4] = [(5, 0, 30), (5, 1, 12), (6, 1, 45), (6, 2, 60)];

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

fn pairs(xs: impl IntoIterator<Item = [u64; 2]>) -> Source {
    Source::Facts(Facts::from_rows(2, xs).unwrap())
}

fn triples(xs: impl IntoIterator<Item = [u64; 3]>) -> Source {
    Source::Facts(Facts::from_rows(3, xs).unwrap())
}

fn catalog() -> Catalog {
    let mut c = Catalog::new();
    c.label("Book", ones(0..3))
        .label("Shelf", ones(3..5))
        .label("Reader", ones(5..7))
        .property(
            "Book",
            "pages",
            pairs((0..3).map(|i| [i, PAGES[i as usize]])),
        )
        .property(
            "Shelf",
            "floor",
            pairs((0..2).map(|i| [3 + i, FLOOR[i as usize]])),
        )
        .property(
            "Reader",
            "age",
            pairs((0..2).map(|i| [5 + i, AGE[i as usize]])),
        )
        .edge("on", pairs(ON.iter().map(|e| [e.0, e.1])))
        .edge_property("on", "slot", triples(ON.iter().map(|e| [e.0, e.1, e.2])))
        .edge("read", pairs(READ.iter().map(|e| [e.0, e.1])))
        .edge_property(
            "read",
            "minutes",
            triples(READ.iter().map(|e| [e.0, e.1, e.2])),
        );
    c
}

fn node(id: u64) -> Entity {
    let (label, key, v) = match id {
        0..3 => ("Book", "pages", PAGES[id as usize]),
        3..5 => ("Shelf", "floor", FLOOR[id as usize - 3]),
        _ => ("Reader", "age", AGE[id as usize - 5]),
    };
    Entity::Node {
        id,
        labels: vec![label.into()],
        properties: vec![(key.into(), Datum::U64(v))],
    }
}

fn on(b: u64, s: u64) -> Entity {
    let e = ON.iter().find(|e| e.0 == b && e.1 == s).expect("an edge");
    Entity::Edge {
        label: "on".into(),
        start: b,
        end: s,
        properties: vec![("slot".into(), Datum::U64(e.2))],
    }
}

fn read(a: u64, b: u64) -> Entity {
    let e = READ.iter().find(|e| e.0 == a && e.1 == b).expect("an edge");
    Entity::Edge {
        label: "read".into(),
        start: a,
        end: b,
        properties: vec![("minutes".into(), Datum::U64(e.2))],
    }
}

async fn table(text: &str) -> Table {
    let l = lower_with(&parse(text).unwrap(), &catalog(), &Params::new())
        .unwrap_or_else(|e| panic!("{text}: {e}"));
    l.run(&Engine::<CpuBackend>::new(CpuDevice::new(2)))
        .await
        .unwrap_or_else(|e| panic!("{text}: {e}"))
}

fn refused(text: &str) -> GqlError {
    lower_with(&parse(text).unwrap(), &catalog(), &Params::new()).unwrap_err()
}

/// Each row as its cells: a whole value, null, or the value.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Cell {
    Whole(Entity),
    Null,
    Value(u64),
}

fn cells(t: &Table) -> Vec<Vec<Cell>> {
    (0..t.rows.len())
        .map(|r| {
            (0..t.columns.len())
                .map(|c| match (t.entity(r, c), t.is_null(r, c)) {
                    (Some(e), false) => Cell::Whole(e.clone()),
                    (None, true) => Cell::Null,
                    (None, false) => Cell::Value(t.rows[r][c]),
                    (Some(e), true) => panic!("a null with a whole value {e}"),
                })
                .collect()
        })
        .collect()
}

/// The rows as a sorted list of their cells' texts (row order aside).
fn bag(rows: Vec<Vec<Cell>>) -> Vec<String> {
    let mut v: Vec<String> = rows.iter().map(|r| format!("{r:?}")).collect();
    v.sort();
    v
}

#[tokio::test]
async fn a_node_through_with_or_from_a_procedure_is_whole() {
    let t = table("MATCH (b:Book) WITH b WHERE b.pages > 100 RETURN b, b.pages").await;
    let want: Vec<Vec<Cell>> = (0..3)
        .filter(|&b| PAGES[b as usize] > 100)
        .map(|b| vec![Cell::Whole(node(b)), Cell::Value(PAGES[b as usize])])
        .collect();
    assert_eq!(cells(&t), want);
    let t = table("MATCH (a:Reader)-[:read]->(b) WITH DISTINCT b RETURN b").await;
    let want: BTreeSet<u64> = READ.iter().map(|e| e.1).collect();
    assert_eq!(
        cells(&t),
        want.iter()
            .map(|&b| vec![Cell::Whole(node(b))])
            .collect::<Vec<_>>()
    );
    // A procedure's node: an id, read whole (a node of the graph's vertices 0..5).
    let t = table("CALL wcc(on) YIELD node, component RETURN node, component").await;
    assert_eq!(t.rows.len(), 5);
    for (r, row) in t.rows.iter().enumerate() {
        assert_eq!(t.entity(r, 0), Some(&node(row[0])), "row {r}");
        assert_eq!(t.entity(r, 1), None);
    }
}

#[tokio::test]
async fn whole_edges_in_a_union() {
    // Two edges from one reader are two rows; an edge in both parts is one.
    let t = table(
        "MATCH (a:Reader)-[r:read]->(b) RETURN r AS x \
         UNION MATCH (a:Reader)-[r:read]->(b:Book) WHERE b.pages > 100 RETURN r AS x \
         UNION MATCH (b:Book)-[r:on]->(s) RETURN r AS x",
    )
    .await;
    let mut want: Vec<Vec<Cell>> = READ
        .iter()
        .map(|e| vec![Cell::Whole(read(e.0, e.1))])
        .chain(ON.iter().map(|e| vec![Cell::Whole(on(e.0, e.1))]))
        .collect();
    assert_eq!(bag(cells(&t)), bag(want.clone()));
    // UNION ALL keeps the repeats.
    let t = table(
        "MATCH (a:Reader)-[r:read]->(b) RETURN r AS x \
         UNION ALL MATCH (a:Reader)-[r:read]->(b:Book) WHERE b.pages > 100 RETURN r AS x",
    )
    .await;
    want = READ
        .iter()
        .map(|e| vec![Cell::Whole(read(e.0, e.1))])
        .collect();
    want.extend(
        READ.iter()
            .filter(|e| PAGES[e.1 as usize] > 100)
            .map(|e| vec![Cell::Whole(read(e.0, e.1))]),
    );
    assert_eq!(bag(cells(&t)), bag(want));
}

#[tokio::test]
async fn whole_values_with_aggregates() {
    // A whole edge as a group key: each edge, its matches (one per shelf).
    let t = table("MATCH (a:Reader)-[r:read]->(b:Book), (s:Shelf) RETURN r, count(*)").await;
    let want: Vec<Vec<Cell>> = READ
        .iter()
        .map(|e| vec![Cell::Whole(read(e.0, e.1)), Cell::Value(2)])
        .collect();
    assert_eq!(bag(cells(&t)), bag(want));
    // A whole edge and a whole node as keys, a sum.
    let t = table("MATCH (a:Reader)-[r:read]->(b:Book)-[:on]->(s:Shelf) RETURN s, r, sum(b.pages)")
        .await;
    let mut want = Vec::new();
    for &(a, b, _) in &READ {
        let s = ON.iter().find(|e| e.0 == b).unwrap().1;
        want.push(vec![
            Cell::Whole(node(s)),
            Cell::Whole(read(a, b)),
            Cell::Value(PAGES[b as usize]),
        ]);
    }
    assert_eq!(bag(cells(&t)), bag(want));
    // Inside count: an edge counted per match, or once.
    let t = table(
        "MATCH (a:Reader)-[r:read]->(b:Book), (s:Shelf) \
         RETURN a, count(r), count(DISTINCT r), count(DISTINCT b)",
    )
    .await;
    let mut want = Vec::new();
    for a in 5..7 {
        let n = READ.iter().filter(|e| e.0 == a).count() as u64;
        want.push(vec![
            Cell::Whole(node(a)),
            Cell::Value(2 * n),
            Cell::Value(n),
            Cell::Value(n),
        ]);
    }
    assert_eq!(cells(&t), want);
    // A part of a whole value is no group of its own here: refused by name.
    for q in [
        "MATCH (n) RETURN labels(n), count(*)",
        "MATCH (a)-[r:read|on]->(b) RETURN type(r), count(*)",
        "MATCH (b:Book) RETURN properties(b), count(*)",
    ] {
        let e = refused(q);
        assert!(e.to_string().contains("group"), "{q}: {e}");
    }
}

#[tokio::test]
async fn whole_values_of_an_optional_match_are_null_where_it_finds_none() {
    let q = "MATCH (s:Shelf) OPTIONAL MATCH (b:Book)-[r:on]->(s) WHERE b.pages > 100 \
             RETURN s, b, r";
    let t = table(q).await;
    let mut want = Vec::new();
    for s in 3..5 {
        let found: Vec<u64> = ON
            .iter()
            .filter(|e| e.1 == s && PAGES[e.0 as usize] > 100)
            .map(|e| e.0)
            .collect();
        if found.is_empty() {
            want.push(vec![Cell::Whole(node(s)), Cell::Null, Cell::Null]);
        }
        for b in found {
            want.push(vec![
                Cell::Whole(node(s)),
                Cell::Whole(node(b)),
                Cell::Whole(on(b, s)),
            ]);
        }
    }
    assert_eq!(bag(cells(&t)), bag(want));
    // count of an edge of an OPTIONAL MATCH: 0 where it finds none.
    let t = table(
        "MATCH (s:Shelf) OPTIONAL MATCH (b:Book)-[r:on]->(s) WHERE b.pages > 100 \
         RETURN s, count(r), count(DISTINCT r)",
    )
    .await;
    let want: Vec<Vec<Cell>> = (3..5)
        .map(|s| {
            let n = ON
                .iter()
                .filter(|e| e.1 == s && PAGES[e.0 as usize] > 100)
                .count() as u64;
            vec![Cell::Whole(node(s)), Cell::Value(n), Cell::Value(n)]
        })
        .collect();
    assert_eq!(cells(&t), want);
    // An edge between two nodes found before: whether it is there is the clause's alone.
    let e = refused("MATCH (b:Book), (s:Shelf) OPTIONAL MATCH (b)-[r:on]->(s) RETURN b, s, r");
    assert!(e.to_string().contains("OPTIONAL"), "{e}");
}

/// BFS distances from `s` over `edges`.
fn depths(s: u64, edges: &[(u64, u64)]) -> BTreeMap<u64, u64> {
    let mut d = BTreeMap::from([(s, 0)]);
    let mut q = VecDeque::from([s]);
    while let Some(x) = q.pop_front() {
        for &(a, b) in edges {
            if a == x && !d.contains_key(&b) {
                d.insert(b, d[&x] + 1);
                q.push_back(b);
            }
        }
    }
    d
}

#[tokio::test]
async fn relationships_of_a_shortest_path() {
    let edges: Vec<(u64, u64)> = READ
        .iter()
        .map(|e| (e.0, e.1))
        .chain(ON.iter().map(|e| (e.0, e.1)))
        .collect();
    let edge = |a: u64, b: u64| {
        if a >= 5 { read(a, b) } else { on(a, b) }
    };
    for (q, backward) in [
        (
            "MATCH p = ANY SHORTEST (a:Reader)-[:read|on]->+(s:Shelf) \
             RETURN id(a), id(s), length(p), relationships(p), nodes(p)",
            false,
        ),
        (
            "MATCH p = ANY SHORTEST (s:Shelf)<-[:read|on]-+(a:Reader) \
             RETURN id(a), id(s), length(p), relationships(p), nodes(p)",
            true,
        ),
    ] {
        let t = table(q).await;
        let mut ends = BTreeSet::new();
        for (r, row) in t.rows.iter().enumerate() {
            let (a, s, len) = (row[0], row[1], row[2]);
            ends.insert((a, s));
            assert_eq!(depths(a, &edges).get(&s), Some(&len), "{q}: {a} to {s}");
            let ns = t.list(r, 4).unwrap().to_vec();
            let Some(Entity::Edges(es)) = t.entity(r, 3) else {
                panic!("{q}: no edges in row {r}")
            };
            // Each edge as stored (from, to), in the path's order.
            let want: Vec<Entity> = ns
                .windows(2)
                .map(|w| {
                    if backward {
                        edge(w[1], w[0])
                    } else {
                        edge(w[0], w[1])
                    }
                })
                .collect();
            assert_eq!(es, &want, "{q}: row {r}");
            assert_eq!(es.len() as u64, len);
        }
        let want: BTreeSet<(u64, u64)> = (5..7)
            .flat_map(|a| {
                depths(a, &edges)
                    .into_keys()
                    .filter(|s| (3..5).contains(s))
                    .map(move |s| (a, s))
            })
            .collect();
        assert_eq!(ends, want, "{q}");
    }
}