crates/kleene-plan/tests/order.rs
//! The output operator ([`Order`]): keys rising and falling with their nulls first, last or
//! by default, nulls from flag columns, offsets and limits, each against a plain sort of the
//! same rows; a counted relation's bag cut after it is expanded; with no key the reading
//! stops at the limit (a bag of 10^15 rows gives its first rows at once).
use std::cmp::Ordering;
use std::sync::Arc;
use arrow_array::{ArrayRef, UInt64Array};
use kleene_plan::{
Atom, Engine, Facts, Inputs, NULL, Nulls, Order, OrderKey, Plan, RelId, Rows, 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 (a: u64, b: i64 nullable as codes, flag: 0 or 1).
fn rows() -> Vec<Vec<Value>> {
(0..60u64)
.map(|i| {
let a = (i * 7) % 5;
let b = if i % 9 == 4 {
NULL
} else {
Type::I64
.encode(&kleene_plan::Datum::I64((i as i64 * 13) % 11 - 5), None)
.unwrap()
};
vec![a, b, (i % 4 != 1) as Value]
})
.collect()
}
const TYPES: [Type; 3] = [Type::U64, Type::I64, Type::U64];
/// The plain reference: compare rows key by key (a null by its placement, then nulls by
/// flag, then values), then by the whole row.
fn reference(order: &Order, mut rows: Vec<Vec<Value>>) -> Vec<Vec<Value>> {
let cmp = |x: &Vec<Value>, y: &Vec<Value>| -> Ordering {
for k in &order.keys {
let flag = |r: &Vec<Value>| k.null_when.iter().any(|&f| r[f] == 0);
let null = |r: &Vec<Value>| flag(r) || (TYPES[k.col].nullable() && r[k.col] == NULL);
let (nx, ny) = (null(x), null(y));
if nx != ny {
let last = match k.nulls {
Nulls::Default => !k.desc,
Nulls::Last => true,
Nulls::First => false,
};
return if nx == last {
Ordering::Greater
} else {
Ordering::Less
};
}
let o = flag(x).cmp(&flag(y)).then(x[k.col].cmp(&y[k.col]));
let o = if k.desc { o.reverse() } else { o };
if o.is_ne() {
return o;
}
}
x.cmp(y)
};
rows.sort_by(cmp);
let skip = order.offset as usize;
let take = order.limit.map_or(usize::MAX, |l| l as usize);
rows.into_iter().skip(skip).take(take).collect()
}
#[test]
fn keys_nulls_offsets_and_limits_as_a_plain_sort() {
let keys = [
vec![OrderKey::asc(1)],
vec![OrderKey::desc(1)],
vec![OrderKey::asc(1).nulls_first()],
vec![OrderKey::desc(1).nulls_last()],
vec![OrderKey::desc(0), OrderKey::asc(1)],
vec![
OrderKey::asc(0).null_when([2]),
OrderKey::desc(1).nulls_first(),
],
vec![OrderKey::desc(0).null_when([2]), OrderKey::desc(2)],
vec![OrderKey::asc(1).null_when([2]).nulls_last()],
];
let cuts = [
(0, None),
(3, None),
(0, Some(5)),
(7, Some(4)),
(0, Some(0)),
(58, Some(9)),
];
for k in &keys {
for &(offset, limit) in &cuts {
let order = Order {
keys: k.clone(),
offset,
limit,
};
let got = order.apply(&TYPES, rows());
assert_eq!(got, reference(&order, rows()), "{order:?}");
}
}
// no key: the rows as they come, cut
let order = Order::new().offset(2).limit(3);
assert_eq!(order.apply(&TYPES, rows()), rows()[2..5].to_vec());
}
/// `two(A, C, N) :- e(A, B), e(B, C)` counted over parallel edges: its bag in order, cut.
#[tokio::test]
async fn a_counted_relation_is_cut_after_its_rows_are_expanded() {
let edges: [(u64, u64, u64); 5] = [(0, 1, 2), (1, 2, 3), (1, 3, 1), (2, 0, 1), (3, 3, 2)];
let mut p = Plan::new();
let e = p.input_counted("e", &[Type::U64, Type::U64]);
let two = p.derived_counted("two", &[Type::U64, Type::U64]);
let [a, b, c, n, m, k] = ["A", "B", "C", "N", "M", "K"].map(|x| p.var(x));
p.count_rule(
atom(two, &[a, c, k]),
[atom(e, &[a, b, n]), atom(e, &[b, c, m])],
)
.unwrap();
let mut inputs = Inputs::new();
inputs.facts(
e,
Facts::from_rows(3, edges.iter().map(|x| [x.0, x.1, x.2])).unwrap(),
);
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.run(&p, &inputs)
.await
.unwrap();
// the bag by a plain loop
let mut bag: Vec<Vec<Value>> = Vec::new();
for x in &edges {
for y in &edges {
if x.1 == y.0 {
for _ in 0..x.2 * y.2 {
bag.push(vec![x.0, y.1]);
}
}
}
}
let types = [Type::U64, Type::U64];
for order in [
Order::new().by(OrderKey::desc(1)).limit(4),
Order::new()
.by(OrderKey::asc(0))
.by(OrderKey::desc(1))
.offset(3)
.limit(5),
Order::new().by(OrderKey::asc(1)),
] {
let got = out.ordered(&p, two, Rows::Bag, &order).unwrap();
assert_eq!(got, order.apply(&types, bag.clone()), "{order:?}");
}
// distinct rows: each once
let order = Order::new().by(OrderKey::asc(0)).by(OrderKey::asc(1));
let mut distinct = bag.clone();
distinct.sort();
distinct.dedup();
assert_eq!(
out.ordered(&p, two, Rows::Distinct, &order).unwrap(),
distinct
);
}
/// With no key, a limit stops the reading: a bag of 10^15 rows gives its first three.
#[tokio::test]
async fn a_limit_with_no_key_stops_early() {
let mut p = Plan::new();
let big = p.input_counted("big", &[Type::U64]);
let copy = p.derived_counted("copy", &[Type::U64]);
let (x, n, k) = (p.var("X"), p.var("N"), p.var("K"));
p.count_rule(atom(copy, &[x, k]), [atom(big, &[x, n])])
.unwrap();
let mut inputs = Inputs::new();
let ids: ArrayRef = Arc::new(UInt64Array::from(vec![5, 9]));
let counts: ArrayRef = Arc::new(UInt64Array::from(vec![1_000_000_000_000_000, 2]));
inputs.columns(big, vec![ids, counts]);
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.run(&p, &inputs)
.await
.unwrap();
let got = out
.ordered(&p, copy, Rows::Bag, &Order::new().offset(1).limit(3))
.unwrap();
assert_eq!(got.len(), 3);
assert!(got.iter().all(|r| r.len() == 1));
}