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

//! `rank(x BY g, ..)` in `RETURN`: per row, the number of distinct values of `x` before its
//! own among the rows equal on the `g`s (from 0), every row kept. Lowered onto the core's
//! rank aggregate (`kleene_plan::Aggregate::rank`, the one `N = rank(K) by (G)` reaches from
//! Datalog), checked against a plain sort, at two thread counts.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use arrow_array::{ArrayRef, StringArray, UInt64Array};
use kleene_gql::{Catalog, GqlError, Params, TypedTable, lower_with, parse};
use kleene_plan::{Agg, Datum, Engine, Facts, Source, Type};
use kleene_sparse::{CpuBackend, CpuDevice};

/// People: (dept, age, name).
const PEOPLE: [(u64, u64, &str); 9] = [
    (1, 40, "eve"),
    (1, 30, "bo"),
    (1, 40, "ann"),
    (2, 25, "cy"),
    (2, 25, "dan"),
    (2, 61, "al"),
    (2, 20, "bo"),
    (3, 50, "fay"),
    (3, 18, "eve"),
];

/// Person -> Person (some starts twice: a row per match).
const KNOWS: [(u64, u64); 6] = [(0, 1), (0, 2), (1, 2), (3, 4), (5, 0), (5, 8)];

fn catalog() -> Catalog {
    let n = PEOPLE.len() as u64;
    let ids = || -> ArrayRef { Arc::new(UInt64Array::from_iter_values(0..n)) };
    let col = |f: fn(&(u64, u64, &str)) -> u64| -> ArrayRef {
        Arc::new(UInt64Array::from_iter_values(PEOPLE.iter().map(f)))
    };
    let mut c = Catalog::new();
    c.label("Person", Source::Columns(vec![ids()]))
        .property("Person", "dept", Source::Columns(vec![ids(), col(|p| p.0)]))
        .property("Person", "age", Source::Columns(vec![ids(), col(|p| p.1)]))
        .typed_property(
            "Person",
            "name",
            Source::Columns(vec![
                ids(),
                Arc::new(StringArray::from_iter_values(PEOPLE.iter().map(|p| p.2))),
            ]),
            Type::Str,
        )
        .edge(
            "knows",
            Source::Facts(Facts::from_rows(2, KNOWS.iter().map(|&(a, b)| [a, b])).unwrap()),
        );
    c
}

async fn run(text: &str, threads: usize) -> TypedTable {
    let l = lower_with(&parse(text).unwrap(), &catalog(), &Params::new()).unwrap();
    let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads));
    l.run_typed(&e).await.unwrap()
}

/// The same table at 1 and 8 threads.
async fn rows(text: &str) -> Vec<Vec<Datum>> {
    let a = run(text, 1).await;
    let b = run(text, 8).await;
    assert_eq!(a, b, "{text}");
    a.rows
}

/// Per group, the distinct keys in rising order: each one's position.
fn positions<G: Ord + Clone, K: Ord + Clone>(
    pairs: impl Iterator<Item = (G, K)>,
) -> BTreeMap<(G, K), u64> {
    let mut by: BTreeMap<G, BTreeSet<K>> = BTreeMap::new();
    for (g, k) in pairs {
        by.entry(g).or_default().insert(k);
    }
    by.into_iter()
        .flat_map(|(g, ks)| {
            ks.into_iter()
                .enumerate()
                .map(move |(i, k)| ((g.clone(), k), i as u64))
        })
        .collect()
}

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

#[tokio::test]
async fn rank_by_a_group_like_a_sort() {
    let got = rows(
        "MATCH (p:Person) RETURN p.dept AS d, p.age AS a, rank(p.age BY p.dept) AS n \
         ORDER BY d, n",
    )
    .await;
    let pos = positions(PEOPLE.iter().map(|p| (p.0, p.1)));
    // a row per person, equal ages sharing their position
    let mut want: Vec<Vec<Datum>> = PEOPLE
        .iter()
        .map(|p| vec![u(p.0), u(p.1), u(pos[&(p.0, p.1)])])
        .collect();
    want.sort_by_key(|r| match r[..] {
        [Datum::U64(d), Datum::U64(a), Datum::U64(n)] => (d, n, a),
        _ => unreachable!(),
    });
    assert_eq!(got, want);
}

#[tokio::test]
async fn rank_without_by_is_one_group_strings_in_byte_order() {
    let got =
        rows("MATCH (p:Person) RETURN DISTINCT p.name AS s, rank(p.name) AS n ORDER BY n").await;
    let names: BTreeSet<&str> = PEOPLE.iter().map(|p| p.2).collect();
    let want: Vec<Vec<Datum>> = names
        .iter()
        .enumerate()
        .map(|(i, s)| vec![Datum::Str(s.to_string()), u(i as u64)])
        .collect();
    assert_eq!(got, want);
    // by two values
    let got = rows("MATCH (p:Person) RETURN p.name AS s, rank(p.age BY p.dept, p.name) AS n").await;
    assert_eq!(got.len(), PEOPLE.len());
    assert!(got.iter().all(|r| r[1] == u(0)), "{got:?}");
}

#[tokio::test]
async fn ranked_rows_keep_their_matches() {
    // a row per match: a start with two friends shows twice
    let got =
        rows("MATCH (a:Person)-[:knows]->(b:Person) RETURN a.dept AS d, rank(a.dept) AS n").await;
    let pos = positions(KNOWS.iter().map(|&(a, _)| (0, PEOPLE[a as usize].0)));
    let mut want: Vec<Vec<Datum>> = KNOWS
        .iter()
        .map(|&(a, _)| {
            let d = PEOPLE[a as usize].0;
            vec![u(d), u(pos[&(0, d)])]
        })
        .collect();
    want.sort_by_key(|r| format!("{r:?}"));
    let mut got = got;
    got.sort_by_key(|r| format!("{r:?}"));
    assert_eq!(got, want);
}

#[test]
fn rank_reaches_the_core_rank_aggregate() {
    let text = "MATCH (p:Person) RETURN p.age AS a, rank(p.age BY p.dept) AS n";
    let l = lower_with(&parse(text).unwrap(), &catalog(), &Params::new()).unwrap();
    let ranks: Vec<_> = l
        .plan
        .rules()
        .iter()
        .filter_map(|r| r.agg.as_ref())
        .filter(|a| matches!(a.agg, Agg::Rank { .. }))
        .collect();
    assert_eq!(ranks.len(), 1);
    assert!(matches!(&ranks[0].agg, Agg::Rank { key, .. } if key.len() == 1));
    assert_eq!(ranks[0].group.len(), 1);
}

#[test]
fn rank_with_an_aggregate_or_optional_match_is_refused() {
    for text in [
        "MATCH (p:Person) RETURN p.dept, rank(p.age), count(*)",
        "MATCH (p:Person) OPTIONAL MATCH (p)-[:knows]->(q:Person) RETURN q.age, rank(q.age)",
    ] {
        let got = lower_with(&parse(text).unwrap(), &catalog(), &Params::new());
        assert!(
            matches!(got, Err(GqlError::Unsupported(_))),
            "{text}: {:?}",
            got.err()
        );
    }
}