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

//! One row per match (Cypher's and ISO GQL's default): a match binds every node and edge of
//! the pattern, the anonymous ones too, so parallel edges and middle nodes each make a row;
//! counts count matches, sums and means weigh by them; `RETURN DISTINCT`, `count(DISTINCT)`
//! and `Rows::Distinct` give the distinct rows. Each answer against a plain loop that
//! enumerates the matches over an edge list with parallel edges, a self loop and a
//! two-cycle.

use std::collections::BTreeMap;
use std::sync::Arc;

use arrow_array::{ArrayRef, UInt64Array};
use kleene_gql::{Catalog, Params, lower_rows, parse};
use kleene_plan::{Datum, Engine, Facts, Rows, Source};
use kleene_sparse::{CpuBackend, CpuDevice};

/// Edges of label E, repeats are parallel edges: 0->1 twice, a self loop 2->2, a
/// two-cycle 3<->4, 1->2, 2->3 twice, 4->5, 1->3.
const EDGES: [(u64, u64); 10] = [
    (0, 1),
    (0, 1),
    (1, 2),
    (2, 2),
    (2, 3),
    (2, 3),
    (3, 4),
    (4, 3),
    (4, 5),
    (1, 3),
];

/// Nodes `0..6` of label N, `v` = 10 + id.
fn catalog() -> Catalog {
    let mut c = Catalog::new();
    let ids = || -> ArrayRef { Arc::new(UInt64Array::from_iter_values(0..6)) };
    let mut pairs: Vec<[u64; 2]> = EDGES.iter().map(|&(a, b)| [a, b]).collect();
    pairs.sort_unstable();
    pairs.dedup();
    let mut counts: BTreeMap<(u64, u64), u64> = BTreeMap::new();
    for &e in &EDGES {
        *counts.entry(e).or_default() += 1;
    }
    c.label("N", Source::Columns(vec![ids()]))
        .edge("E", Source::Facts(Facts::from_rows(2, pairs).unwrap()))
        .edge_counts(
            "E",
            Source::Facts(
                Facts::from_rows(3, counts.iter().map(|(&(a, b), &n)| [a, b, n])).unwrap(),
            ),
        )
        .property(
            "N",
            "v",
            Source::Columns(vec![ids(), Arc::new(UInt64Array::from_iter_values(10..16))]),
        );
    c
}

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

async fn rows(q: &str, mode: Rows) -> Vec<Vec<Datum>> {
    let c = catalog();
    let l = lower_rows(
        &parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
        &c,
        &Params::new(),
        mode,
    )
    .unwrap_or_else(|e| panic!("{q}: {e}"));
    let mut r = l
        .run_typed(&engine())
        .await
        .unwrap_or_else(|e| panic!("{q}: {e}"))
        .rows;
    r.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}")));
    r
}

fn sorted(mut r: Vec<Vec<Datum>>) -> Vec<Vec<Datum>> {
    r.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}")));
    r
}

/// The walks of `lens` edges from `s` (each listed edge a step): (start, end) per walk.
fn walks(lens: std::ops::RangeInclusive<u64>, starts: &[u64]) -> Vec<(u64, u64)> {
    fn go(s: u64, v: u64, d: u64, lens: &std::ops::RangeInclusive<u64>, out: &mut Vec<(u64, u64)>) {
        if lens.contains(&d) {
            out.push((s, v));
        }
        if d == *lens.end() {
            return;
        }
        for &(a, b) in &EDGES {
            if a == v {
                go(s, b, d + 1, lens, out);
            }
        }
    }
    let mut out = Vec::new();
    for &s in starts {
        go(s, s, 0, &lens, &mut out);
    }
    out
}

const ALL: [u64; 6] = [0, 1, 2, 3, 4, 5];

fn u(x: u64) -> Datum {
    Datum::U64(x)
}

#[tokio::test]
async fn fixed_patterns_return_a_row_per_match() {
    // (s)-->()-->(n): one match per middle node and per pair of edges
    let two = walks(2..=2, &ALL);
    let q = "MATCH (s:N)-[:E]->()-[:E]->(n:N) RETURN s, n";
    let want: Vec<Vec<Datum>> = sorted(two.iter().map(|&(s, n)| vec![u(s), u(n)]).collect());
    assert_eq!(rows(q, Rows::Bag).await, want);
    // DISTINCT, and the whole query's switch: the distinct rows
    let mut d = want.clone();
    d.dedup();
    let q = "MATCH (s:N)-[:E]->()-[:E]->(n:N) RETURN DISTINCT s, n";
    assert_eq!(rows(q, Rows::Bag).await, d);
    let q = "MATCH (s:N)-[:E]->()-[:E]->(n:N) RETURN s, n";
    assert_eq!(rows(q, Rows::Distinct).await, d);
    // one edge: a row per parallel edge
    let q = "MATCH (a:N)-[:E]->(b:N) RETURN a, b";
    let one: Vec<Vec<Datum>> = sorted(EDGES.iter().map(|&(a, b)| vec![u(a), u(b)]).collect());
    assert_eq!(rows(q, Rows::Bag).await, one);
    // counts count matches; sums and means weigh by them; count(DISTINCT) does not
    let n = two.len() as u64;
    let q = "MATCH (s:N)-[:E]->()-[:E]->(n:N) RETURN count(*) AS c, count(n) AS k, sum(n.v) AS t";
    let t: u64 = two.iter().map(|&(_, n)| 10 + n).sum();
    assert_eq!(rows(q, Rows::Bag).await, vec![vec![u(n), u(n), u(t)]]);
    let q = "MATCH (s:N)-[:E]->()-[:E]->(n:N) RETURN count(DISTINCT n) AS c";
    let mut ends: Vec<u64> = two.iter().map(|x| x.1).collect();
    ends.sort_unstable();
    ends.dedup();
    assert_eq!(rows(q, Rows::Bag).await, vec![vec![u(ends.len() as u64)]]);
    let q = "MATCH (s:N)-[:E]->()-[:E]->(n:N) RETURN s, count(*) AS c, avg(n.v) AS m";
    let mut per: BTreeMap<u64, (u64, u64)> = BTreeMap::new();
    for &(s, n) in &two {
        let x = per.entry(s).or_default();
        x.0 += 1;
        x.1 += 10 + n;
    }
    let want: Vec<Vec<Datum>> = sorted(
        per.iter()
            .map(|(&s, &(c, t))| vec![u(s), u(c), Datum::F64(t as f64 / c as f64)])
            .collect(),
    );
    assert_eq!(rows(q, Rows::Bag).await, want);
    // the old answer under the switch: each distinct (s, middle, n) binding once
    let q = "MATCH (s:N)-[:E]->(m:N)-[:E]->(n:N) RETURN count(*) AS c";
    let mut b: Vec<(u64, u64, u64)> = Vec::new();
    for &(s, m) in &EDGES {
        for &(m2, n) in &EDGES {
            if m == m2 {
                b.push((s, m, n));
            }
        }
    }
    b.sort_unstable();
    b.dedup();
    assert_eq!(rows(q, Rows::Distinct).await, vec![vec![u(b.len() as u64)]]);
}

/// Not the standard yet (the lib.rs Rows row): an edge may be used twice in one match.
/// The self loop 2 -> 2 taken twice is a match here; Cypher (no edge twice) has none.
#[tokio::test]
async fn an_edge_may_be_used_twice_in_one_match() {
    let q =
        "MATCH (x:N)-[:E]->(y:N)-[:E]->(z:N) WHERE x = 2 AND y = 2 AND z = 2 RETURN count(*) AS c";
    assert_eq!(rows(q, Rows::Bag).await, vec![vec![u(1)]]);
    let q = "MATCH (x:N)-[:E*2..2]->(z:N) WHERE x = 2 AND z = 2 RETURN count(*) AS c";
    assert_eq!(rows(q, Rows::Bag).await, vec![vec![u(1)]]);
}

#[tokio::test]
async fn bounded_lengths_count_walks_by_folds() {
    for (lo, hi) in [(1u64, 1u64), (2, 2), (3, 3), (1, 3), (6, 6)] {
        let w = walks(lo..=hi, &[0]);
        let q = format!("MATCH (s:N)-[:E*{lo}..{hi}]->(t:N) WHERE s = 0 RETURN count(t) AS c");
        assert_eq!(
            rows(&q, Rows::Bag).await,
            vec![vec![u(w.len() as u64)]],
            "{q}"
        );
        let q = format!("MATCH (s:N)-[:E*{lo}..{hi}]->(t:N) WHERE s = 0 RETURN t");
        let want: Vec<Vec<Datum>> = sorted(w.iter().map(|&(_, t)| vec![u(t)]).collect());
        assert_eq!(rows(&q, Rows::Bag).await, want, "{q}");
        let mut d = want.clone();
        d.dedup();
        assert_eq!(rows(&q, Rows::Distinct).await, d, "{q}");
    }
    // unbounded: one row per pair of ends (reachability)
    let q = "MATCH (s:N)-[:E*]->(t:N) WHERE s = 0 RETURN t";
    let got = rows(q, Rows::Bag).await;
    let mut d = got.clone();
    d.dedup();
    assert_eq!(got, d);
}

/// WITH, UNWIND and OPTIONAL MATCH carry the counts: a row per row before.
#[tokio::test]
async fn with_unwind_and_optional_keep_a_row_per_match() {
    let out = |v: u64| EDGES.iter().filter(|e| e.0 == v).count() as u64;
    // WITH m (no DISTINCT): a row per first edge, each extended by m's edges
    let q = "MATCH (s:N)-[:E]->(m:N) WITH m MATCH (m)-[:E]->(n:N) RETURN count(*) AS c";
    let want: u64 = EDGES.iter().map(|&(_, m)| out(m)).sum();
    assert_eq!(rows(q, Rows::Bag).await, vec![vec![u(want)]]);
    let q = "MATCH (s:N)-[:E]->(m:N) WITH DISTINCT m MATCH (m)-[:E]->(n:N) RETURN count(*) AS c";
    let mut ms: Vec<u64> = EDGES.iter().map(|e| e.1).collect();
    ms.sort_unstable();
    ms.dedup();
    let want: u64 = ms.iter().map(|&m| out(m)).sum();
    assert_eq!(rows(q, Rows::Bag).await, vec![vec![u(want)]]);
    // UNWIND: a row per item per row before, a repeated item twice
    let q = "MATCH (a:N)-[:E]->(b:N) UNWIND [1, 1, 2] AS x RETURN count(*) AS c";
    assert_eq!(
        rows(q, Rows::Bag).await,
        vec![vec![u(3 * EDGES.len() as u64)]]
    );
    // OPTIONAL MATCH: a row per extension (parallel edges each), or one with nulls
    let q = "MATCH (a:N) OPTIONAL MATCH (a)-[:E]->(b:N) RETURN count(*) AS c, count(b) AS k";
    let all: u64 = ALL.iter().map(|&a| out(a).max(1)).sum();
    assert_eq!(
        rows(q, Rows::Bag).await,
        vec![vec![u(all), u(EDGES.len() as u64)]]
    );
}

/// A row of the counted matches has a proof of its count ([`kleene_plan::How::Counted`]),
/// through the core's counting rule: the edge 0->1 twice is one row of count 2, its member
/// resting on the edge counts' input fact (0, 1, 2); every row's parts add up to its count.
#[tokio::test]
async fn a_row_of_the_matches_has_a_proof_of_its_count() {
    let c = catalog();
    let q = "MATCH (a:N)-[:E]->(b:N) RETURN a, b";
    let l = lower_rows(&parse(q).unwrap(), &c, &Params::new(), Rows::Bag).unwrap();
    let m = l.matches().expect("the counted matches");
    let out = engine()
        .explain(true)
        .run(&l.plan, &l.inputs)
        .await
        .unwrap();
    let counts = l
        .plan
        .relations()
        .iter()
        .position(|r| r.name == "E counts")
        .expect("the edge counts");
    let facts = out.get(m).unwrap();
    assert!(!facts.is_empty());
    let mut want: BTreeMap<(u64, u64), u64> = BTreeMap::new();
    for &e in &EDGES {
        *want.entry(e).or_default() += 1;
    }
    let mut seen = 0;
    for row in facts.rows() {
        let n = *row.last().unwrap();
        let proof = out
            .why(&l.plan, m, &row)
            .unwrap_or_else(|| panic!("a proof of {row:?}"));
        let kleene_plan::How::Counted { parts } = &proof.how else {
            panic!("a counted proof of {row:?}: {:?}", proof.how)
        };
        let sum: u64 = parts.iter().map(|q| *q.tuple.last().unwrap()).sum();
        assert_eq!(sum, n, "{}", out.render(&l.plan, &proof));
        let text = out.render(&l.plan, &proof);
        if row[..2] == [0, 1] {
            assert_eq!(n, want[&(0, 1)]);
            let kleene_plan::How::Aggregate { members, .. } = &parts[0].how else {
                panic!("an aggregate part")
            };
            assert!(
                members.iter().any(|mem| mem
                    .premises
                    .iter()
                    .any(|q| q.rel.index() == counts && q.tuple == [0, 1, 2])),
                "{text}"
            );
            seen += 1;
        }
    }
    assert_eq!(seen, 1);
}