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

nordisk/kleene

crates/kleene-plan/tests/rank.rs

//! The position of a row in an order ([`Aggregate::rank`]): per group of the body's
//! bindings, each binding gets the number of distinct key tuples before its own in rising
//! key order (from 0, equal keys sharing it), against a plain sort of the distinct rows.
//! Keys of i64, f64 and strings in their own order, null keys skipped, the same rows at
//! every thread count, and each fact's proof its own binding and its group's size.

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

use arrow_array::{ArrayRef, Float64Array, Int64Array, StringArray, UInt64Array};
use kleene_plan::{
    Aggregate, Atom, Datum, Engine, How, Inputs, Plan, RelId, Term, Type, Value, Var,
};
use kleene_sparse::{CpuBackend, CpuDevice};

fn atom(rel: RelId, vars: &[Var]) -> Atom {
    Atom {
        rel,
        terms: vars.iter().map(|&v| Term::Var(v)).collect(),
    }
}

/// Rows (group, i64 key or null, f64 key or null, name, payload).
type Row = (u64, Option<i64>, Option<f64>, String, u64);

fn rows() -> Vec<Row> {
    let mut v: Vec<Row> = Vec::new();
    for i in 0..300u64 {
        let g = i % 7;
        let k = (i % 11 != 4).then_some((i as i64 * 37) % 23 - 11);
        let f = (i % 13 != 6).then_some(((i * 5) % 17) as f64 * 0.25 - 2.0);
        let name = ["pear", "apple", "Zed", "fig", "äpple", "a", ""][(i * 3 % 7) as usize];
        v.push((g, k, f, name.to_string(), i % 5));
    }
    v
}

/// Per group, the distinct keys in rising order: the position of each.
fn positions<K: Ord + Clone>(pairs: impl Iterator<Item = (u64, K)>) -> BTreeMap<(u64, K), u64> {
    let mut by: BTreeMap<u64, BTreeSet<K>> = BTreeMap::new();
    for (g, k) in pairs {
        by.entry(g).or_default().insert(k);
    }
    let mut out = BTreeMap::new();
    for (g, ks) in by {
        for (n, k) in ks.into_iter().enumerate() {
            out.insert((g, k), n as u64);
        }
    }
    out
}

struct Ranks {
    plan: Plan,
    t: RelId,
    rule: kleene_plan::RuleId,
    rels: [RelId; 4],
}

/// `by_int(G, K, N) :- N = rank (K) by (G): t(G, K, _, _, _).`, the same of the f64 key and
/// of the name, `whole(G, K, P, N) :- N = rank (K) by (G): t(G, K, _, _, P).` (a fact per
/// binding, equal keys sharing N) and `all(S, N) :- N = rank (S): t(_, _, _, S, _).`.
fn ranks() -> Ranks {
    let mut p = Plan::new();
    let t = p.input_typed(
        "t",
        &[Type::U64, Type::I64, Type::F64, Type::Str, Type::U64],
    );
    let by_int = p.derived_typed("by_int", &[Type::U64, Type::I64, Type::U64]);
    let by_f = p.derived_typed("by_f", &[Type::U64, Type::F64, Type::I64]);
    let whole = p.derived_typed("whole", &[Type::U64, Type::I64, Type::U64, Type::U64]);
    let all = p.derived_typed("all", &[Type::Str, Type::U64]);
    let [g, k, f, s, w, n] = ["G", "K", "F", "S", "P", "N"].map(|x| p.var(x));
    let body = atom(t, &[g, k, f, s, w]);
    let r = p
        .aggregate(
            atom(by_int, &[g, k, n]),
            Aggregate::rank([g], [k], n),
            [body.clone()],
        )
        .unwrap();
    assert_eq!(
        p.show_rule(r),
        "by_int(G, K, N) :- N = rank (K) by (G): t(G, K, F, S, P)."
    );
    p.aggregate(
        atom(by_f, &[g, f, n]),
        Aggregate::rank([g], [f], n),
        [body.clone()],
    )
    .unwrap();
    p.aggregate(
        atom(whole, &[g, k, w, n]),
        Aggregate::rank([g], [k], n),
        [body.clone()],
    )
    .unwrap();
    p.aggregate(atom(all, &[s, n]), Aggregate::rank([], [s], n), [body])
        .unwrap();
    Ranks {
        plan: p,
        t,
        rule: r,
        rels: [by_int, by_f, whole, all],
    }
}

fn inputs(t: RelId, rs: &[Row], reversed: bool) -> Inputs {
    let mut rs = rs.to_vec();
    if reversed {
        rs.reverse();
    }
    let u = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
    let cols: Vec<ArrayRef> = vec![
        u(rs.iter().map(|r| r.0).collect()),
        Arc::new(Int64Array::from(rs.iter().map(|r| r.1).collect::<Vec<_>>())),
        Arc::new(Float64Array::from(
            rs.iter().map(|r| r.2).collect::<Vec<_>>(),
        )),
        Arc::new(StringArray::from(
            rs.iter().map(|r| r.3.as_str()).collect::<Vec<_>>(),
        )),
        u(rs.iter().map(|r| r.4).collect()),
    ];
    let mut inp = Inputs::new();
    inp.columns(t, cols);
    inp
}

#[tokio::test]
async fn ranks_by_a_typed_key_like_a_sort_at_any_thread_count() {
    let rs = rows();
    let Ranks {
        plan: p, t, rels, ..
    } = ranks();
    // the plain reference
    let int = positions(rs.iter().filter_map(|r| r.1.map(|k| (r.0, k))));
    // (no -0.0 among them: the bits tell the floats apart)
    let float = positions(rs.iter().filter_map(|r| r.2.map(|f| (r.0, f.to_bits()))));
    let names = positions(rs.iter().map(|r| (0, r.3.clone())));
    let mut whole: BTreeSet<(u64, i64, u64, u64)> = BTreeSet::new();
    for r in &rs {
        if let Some(k) = r.1 {
            whole.insert((r.0, k, r.4, int[&(r.0, k)]));
        }
    }
    let mut seen: Option<Vec<Vec<Vec<Datum>>>> = None;
    for (threads, reversed) in [(1, false), (2, true), (8, false), (16, true)] {
        let out = Engine::<CpuBackend>::new(CpuDevice::new(threads))
            .run(&p, &inputs(t, &rs, reversed))
            .await
            .unwrap();
        let got: Vec<Vec<Vec<Datum>>> = rels
            .iter()
            .map(|&r| out.datums(&p, r).unwrap_or_default())
            .collect();
        // by_int: one fact per distinct (G, K), no null key
        let by_int: BTreeSet<(u64, i64, u64)> = got[0]
            .iter()
            .map(|r| match r[..] {
                [Datum::U64(g), Datum::I64(k), Datum::U64(n)] => (g, k, n),
                _ => panic!("{r:?}"),
            })
            .collect();
        assert_eq!(by_int.len(), got[0].len());
        assert_eq!(
            by_int,
            int.iter()
                .map(|(&(g, k), &n)| (g, k, n))
                .collect::<BTreeSet<_>>()
        );
        // by_f: in an i64 column, by the floats' own order (negatives first)
        let mut by_f: BTreeMap<u64, Vec<(f64, i64)>> = BTreeMap::new();
        for r in &got[1] {
            match r[..] {
                [Datum::U64(g), Datum::F64(f), Datum::I64(n)] => {
                    by_f.entry(g).or_default().push((f, n))
                }
                _ => panic!("{r:?}"),
            }
        }
        assert_eq!(
            by_f.values().map(Vec::len).sum::<usize>(),
            float.len(),
            "one fact per distinct float key"
        );
        for v in by_f.values_mut() {
            v.sort_by(|a, b| a.0.total_cmp(&b.0));
            let ns: Vec<i64> = v.iter().map(|x| x.1).collect();
            assert_eq!(ns, (0..v.len() as i64).collect::<Vec<_>>());
        }
        // whole: a fact per binding, equal keys sharing their position
        let w: BTreeSet<(u64, i64, u64, u64)> = got[2]
            .iter()
            .map(|r| match r[..] {
                [Datum::U64(g), Datum::I64(k), Datum::U64(p), Datum::U64(n)] => (g, k, p, n),
                _ => panic!("{r:?}"),
            })
            .collect();
        assert_eq!(w, whole);
        // all: one group, the strings in byte order
        let a: BTreeMap<String, u64> = got[3]
            .iter()
            .map(|r| match &r[..] {
                [Datum::Str(s), Datum::U64(n)] => (s.clone(), *n),
                _ => panic!("{r:?}"),
            })
            .collect();
        assert_eq!(
            a,
            names
                .iter()
                .map(|((_, s), &n)| (s.clone(), n))
                .collect::<BTreeMap<_, _>>()
        );
        // the same rows in the same order at every thread count
        match &seen {
            None => seen = Some(got),
            Some(s) => assert_eq!(s, &got, "{threads} threads"),
        }
    }
}

#[tokio::test]
async fn a_ranked_fact_is_proven_by_its_own_binding_and_its_group_size() {
    let rs = rows();
    let Ranks {
        plan: p,
        t,
        rule,
        rels,
    } = ranks();
    let out = Engine::<CpuBackend>::new(CpuDevice::new(4))
        .explain(true)
        .run(&p, &inputs(t, &rs, false))
        .await
        .unwrap();
    let int = positions(rs.iter().filter_map(|r| r.1.map(|k| (r.0, k))));
    let mut keys: BTreeMap<u64, u64> = BTreeMap::new();
    for &(g, _) in int.keys() {
        *keys.entry(g).or_default() += 1;
    }
    let by_int = rels[0];
    let rule = p.rule_at(rule).clone();
    let facts = out.get(by_int).unwrap();
    assert!(!facts.is_empty());
    for t in facts.rows() {
        let q = out.why(&p, by_int, &t).expect("a proof");
        let How::Aggregate {
            binding,
            members,
            size,
            ..
        } = &q.how
        else {
            panic!("{q:?}")
        };
        // the head's values, N among them
        let val = |bs: &[(Var, Value)], name: &str| {
            bs.iter()
                .find(|(v, _)| p.var_name(*v) == name)
                .unwrap_or_else(|| panic!("{name} in {bs:?}"))
                .1
        };
        assert_eq!(val(binding, "N"), t[2]);
        // one member: a binding of the fact's own group and key
        assert_eq!(members.len(), 1, "{}", out.render(&p, &q));
        let m = &members[0];
        assert_eq!(val(&m.binding, "G"), t[0]);
        assert_eq!(val(&m.binding, "K"), t[1]);
        assert_eq!(m.premises.len(), rule.body.len());
        // its group's size: the distinct keys, more than its position
        assert_eq!(*size as u64, keys[&t[0]]);
        assert!(t[2] < *size as u64);
    }
}

#[test]
fn malformed_ranks_are_refused() {
    let mut p = Plan::new();
    let e = p.input("e", 2);
    let r3 = p.derived("r3", 3);
    let r2 = p.derived("r2", 2);
    let [x, y, n, z] = ["X", "Y", "N", "Z"].map(|v| p.var(v));
    let body = [atom(e, &[x, y])];
    let mut bad = |head: Atom, agg: Aggregate| p.aggregate(head, agg, body.clone()).is_err();
    // an empty key, an unbound key, an unbound group
    assert!(bad(atom(r2, &[x, n]), Aggregate::rank([x], [], n)));
    assert!(bad(atom(r3, &[x, z, n]), Aggregate::rank([x], [z], n)));
    assert!(bad(atom(r3, &[z, y, n]), Aggregate::rank([z], [y], n)));
    // the position bound by the body, or grouping
    assert!(bad(atom(r2, &[x, y]), Aggregate::rank([x], [y], y)));
    assert!(bad(atom(r2, &[n, y]), Aggregate::rank([n], [y], n)));
    // a grouping variable not in the head
    assert!(bad(atom(r2, &[y, n]), Aggregate::rank([x], [y], n)));
    // a head variable bound by nothing
    assert!(bad(atom(r3, &[x, z, n]), Aggregate::rank([x], [y], n)));
    // well formed: the group, the key and the position; any body variable besides
    assert!(!bad(atom(r3, &[x, y, n]), Aggregate::rank([x], [y], n)));
    assert!(!bad(atom(r2, &[y, n]), Aggregate::rank([], [y], n)));
    assert!(!bad(atom(r3, &[y, x, n]), Aggregate::rank([], [y], n)));
}

#[test]
fn a_position_goes_in_a_u64_or_i64_column() {
    let mut p = Plan::new();
    let e = p.input_typed("e", &[Type::U64, Type::Str]);
    let ok = p.derived_typed("ok", &[Type::U64, Type::Str, Type::I64]);
    let no = p.derived_typed("no", &[Type::U64, Type::Str, Type::Str]);
    let [x, y, n] = ["X", "Y", "N"].map(|v| p.var(v));
    let body = [atom(e, &[x, y])];
    assert!(
        p.aggregate(
            atom(ok, &[x, y, n]),
            Aggregate::rank([x], [y], n),
            body.clone()
        )
        .is_ok()
    );
    assert!(
        p.aggregate(atom(no, &[x, y, n]), Aggregate::rank([x], [y], n), body)
            .is_err()
    );
}