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

nordisk/kleene

crates/kleene-datalog/tests/staged.rs

//! Null marks, unions and stages from the Datalog side: an optional part written as rules
//! with a found flag, its rows picked with their null cells ([`Marked::pick`], ordered by
//! [`OrderKey::null_by`]), two such answers joined (`UNION ALL`) and made distinct (`UNION`,
//! a null apart from a 0), and the rows of one run fed to the next as its input
//! ([`Inputs::datums`]), plain and counted; against plain loops.

use std::collections::BTreeMap;

use kleene_datalog::{
    Datum, Engine, Facts, Inputs, Marked, NullMark, Order, OrderKey, Program, Term, Type,
};
use kleene_sparse::{CpuBackend, CpuDevice};

const PEOPLE: [u64; 5] = [1, 2, 3, 4, 5];
const OWNS: [(u64, u64); 4] = [(1, 10), (1, 0), (3, 30), (5, 50)];

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

/// `row(P, Q, F)`: each person with each pet (F = 1), or with none (Q = 0, F = 0).
async fn optional(people: &[u64]) -> Marked {
    let mut p = Program::new();
    let person = p.input::<1>("person");
    let owns = p.input::<2>("owns");
    let any = p.derived::<1>("any");
    let row = p.derived::<3>("row");
    let [x, q] = ["P", "Q"].map(|n| p.var(n));
    p.rule(any.at([x]), [owns.at([x, q])]).unwrap();
    p.rule(
        row.atom([x.into(), q.into(), Term::Const(1)]),
        [person.at([x]), owns.at([x, q])],
    )
    .unwrap();
    p.rule(
        row.atom([x.into(), Term::Const(0), Term::Const(0)]),
        [person.at([x]).into(), !any.at([x])],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs
        .facts(
            &person,
            Facts::from_rows(1, people.iter().map(|&v| [v])).unwrap(),
        )
        .unwrap();
    inputs
        .facts(
            &owns,
            Facts::from_rows(2, OWNS.iter().map(|&(a, b)| [a, b])).unwrap(),
        )
        .unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let marks = [NullMark {
        flag: 2,
        cols: vec![1],
    }];
    // the pet rising, nulls last, then the person
    let order = Order::new()
        .by(OrderKey::asc(1).null_by(&marks))
        .by(OrderKey::asc(0));
    let rows = order.apply(&[Type::U64; 3], out.get(&row).unwrap().sorted_rows());
    Marked::pick(rows, &[0, 1], false, &marks)
}

#[tokio::test]
async fn an_optional_part_its_union_and_the_next_stage() {
    // rows 2: (person, pet or null), a null apart from pet 0
    let m = optional(&PEOPLE).await;
    let want: Vec<(u64, Option<u64>)> = vec![
        (1, Some(0)),
        (1, Some(10)),
        (3, Some(30)),
        (5, Some(50)),
        (2, None),
        (4, None),
    ];
    let got: Vec<(u64, Option<u64>)> = m
        .rows
        .iter()
        .enumerate()
        .map(|(i, r)| (r[0], (!m.is_null(i, 1)).then_some(r[1])))
        .collect();
    assert_eq!(got, want);

    // row 3: UNION ALL keeps both parts' rows, UNION each distinct row once
    let mut all = optional(&PEOPLE[..3]).await;
    let second = optional(&PEOPLE[1..]).await;
    let n = all.rows.len() + second.rows.len();
    all.append(second);
    assert_eq!(all.rows.len(), n);
    let mut distinct = all.clone();
    let was = distinct.distinct(&[]);
    let cell = |m: &Marked, i: usize| (m.rows[i][0], (!m.is_null(i, 1)).then_some(m.rows[i][1]));
    let mut want: Vec<(u64, Option<u64>)> = (0..all.rows.len()).map(|i| cell(&all, i)).collect();
    // (a null sorts after every value)
    want.sort_by_key(|&(a, b)| (a, b.is_none(), b));
    want.dedup();
    let got: Vec<(u64, Option<u64>)> = (0..distinct.rows.len())
        .map(|i| cell(&distinct, i))
        .collect();
    assert_eq!(got, want);
    for (i, &at) in was.iter().enumerate() {
        assert_eq!(cell(&distinct, i), cell(&all, at));
    }

    // row 4: the stage's rows (people with a pet, by name) as the next run's inputs
    let stage: Vec<Vec<Datum>> = (0..all.rows.len())
        .filter(|&i| !all.is_null(i, 1))
        .map(|i| {
            vec![
                Datum::Str(format!("p{}", all.rows[i][0])),
                Datum::U64(all.rows[i][1]),
            ]
        })
        .collect();
    let mut p = Program::new();
    let seen = p.input_typed::<2>("seen", [Type::Str, Type::U64]);
    let counted = p.input_counted::<2>("counted");
    let per = p.derived_counted::<2>("per");
    let pets = p.derived_typed::<2>("pets", [Type::Str, Type::U64]);
    let [who, pet, k] = ["W", "Q", "K"].map(|n| p.var(n));
    p.rule(pets.at([who, pet]), [seen.at([who, pet])]).unwrap();
    p.count_rule(per.at([pet, k]), [counted.at([pet, who])])
        .unwrap();
    let mut inputs = Inputs::new();
    inputs.datums(&p, &seen, &stage).unwrap();
    let pets_only: Vec<Vec<Datum>> = stage.iter().map(|r| vec![r[1].clone()]).collect();
    inputs.datums(&p, &counted, &pets_only).unwrap();
    assert!(
        inputs
            .datums(&p, &seen, &[vec![Datum::Null, Datum::U64(1)]])
            .is_ok()
    );
    assert!(
        inputs
            .datums(&p, &seen, &[vec![Datum::U64(1), Datum::Null]])
            .is_err()
    );
    inputs.datums(&p, &seen, &stage).unwrap();
    let out = engine().run(&p, &inputs).await.unwrap();
    let mut got: Vec<[Datum; 2]> = out.datums(&p, &pets).unwrap();
    got.sort_by_key(|r| format!("{r:?}"));
    let mut want: Vec<[Datum; 2]> = stage.iter().map(|r| [r[0].clone(), r[1].clone()]).collect();
    want.sort_by_key(|r| format!("{r:?}"));
    want.dedup();
    assert_eq!(got, want);
    let mut times: BTreeMap<u64, u64> = BTreeMap::new();
    for r in &stage {
        let Datum::U64(q) = r[1] else { unreachable!() };
        *times.entry(q).or_default() += 1;
    }
    let got: BTreeMap<u64, u64> = out
        .get(&per)
        .unwrap()
        .rows()
        .map(|r| (r[0], r[1]))
        .collect();
    assert_eq!(got, times);
    assert!(
        times.values().any(|&t| t > 1),
        "a row given twice counts twice"
    );
}