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

//! List columns of an X.gar set read by name as rows: a vertex column `T.c` as (id,
//! position, value), an edge property `E.c` as (source, destination, position, value), the
//! position from 0, an edge's list also by the edge's row `E@row.c` as (row, position,
//! value), the value typed as a plain column of the element type is; an empty or
//! null list gives no row, a null element is the element type's null (an unsigned element
//! has no null: its row is left out, the other elements keeping their positions). The
//! answers checked against plain loops over the same lists.

use std::collections::BTreeSet;
use std::path::PathBuf;
use std::sync::Arc;

use arrow_array::builder::{ListBuilder, StringBuilder};
use arrow_array::types::{Int64Type, UInt32Type, UInt64Type};
use arrow_array::{Array, ArrayRef, FixedSizeListArray, LargeListArray, ListArray, RecordBatch};
use arrow_schema::{Field, Schema};
use graphar::mapped::{IntColumn, IntEdges, IntGraphWriter, write_ipc};
use kleene_datalog::{Datum, Engine, Inputs, Program, Type};
use kleene_gar::GarGraph;
use kleene_sparse::{CpuBackend, CpuDevice};

/// `v.tags`: strings, one list empty, one null, one with a null element.
fn tags() -> Vec<Option<Vec<Option<&'static str>>>> {
    vec![
        Some(vec![Some("a"), Some("b"), Some("a")]),
        Some(vec![]),
        None,
        Some(vec![Some("c"), None]),
    ]
}

/// `v.w`: signed integers in a large list.
fn w() -> Vec<Option<Vec<Option<i64>>>> {
    vec![
        Some(vec![Some(-1), Some(2)]),
        None,
        Some(vec![Some(5)]),
        Some(vec![]),
    ]
}

/// `v.pair`: unsigned integers, two per row, one row null.
fn pair() -> Vec<Option<Vec<Option<u32>>>> {
    vec![
        Some(vec![Some(1), Some(2)]),
        None,
        Some(vec![Some(3), Some(4)]),
        Some(vec![Some(5), Some(6)]),
    ]
}

const KNOWS: [(u32, u32); 3] = [(0, 1), (1, 2), (3, 3)];

/// `knows.hops`, per edge in by-source order (a null element: no row).
fn hops() -> Vec<Option<Vec<Option<u64>>>> {
    vec![
        Some(vec![Some(7)]),
        Some(vec![]),
        Some(vec![Some(8), None, Some(9)]),
    ]
}

/// `v.bad`: unsigned elements, some null (no row; the others keep their positions).
fn bad() -> Vec<Option<Vec<Option<u32>>>> {
    vec![
        Some(vec![Some(7), None, Some(9)]),
        Some(vec![]),
        None,
        Some(vec![None, Some(2)]),
    ]
}

struct TempDir(PathBuf);

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// Column `name` written as one chunk (`chunk` under its directory in `at`) the way another
/// GraphAr writer would.
fn put(at: PathBuf, name: &str, chunk: &str, values: ArrayRef) {
    let nullable = values.null_count() > 0;
    let schema = Schema::new(vec![Field::new(name, values.data_type().clone(), nullable)]);
    let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
    write_ipc(at.join(name).join(chunk), &batch).unwrap();
}

fn set() -> TempDir {
    let dir = std::env::temp_dir().join(format!("kleene-datalog-lists-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let mut w_ = IntGraphWriter::new(&dir, "X").unwrap();
    w_.vertices(
        "v",
        4,
        vec![("n".to_string(), IntColumn::U32(vec![0, 1, 2, 3]))],
    )
    .unwrap();
    let (s, d): (Vec<u32>, Vec<u32>) = KNOWS.iter().copied().unzip();
    w_.edges(IntEdges::from_pairs(("v", "knows", "v"), (4, 4), &s, &d, vec![]).unwrap())
        .unwrap();
    w_.finish().unwrap();
    let vdir = dir.join("vertex").join("v");
    let mut b = ListBuilder::new(StringBuilder::new());
    for row in tags() {
        match row {
            Some(xs) => {
                for x in xs {
                    b.values().append_option(x);
                }
                b.append(true);
            }
            None => b.append(false),
        }
    }
    put(vdir.clone(), "tags", "chunk0", Arc::new(b.finish()));
    put(
        vdir.clone(),
        "w",
        "chunk0",
        Arc::new(LargeListArray::from_iter_primitive::<Int64Type, _, _>(w())),
    );
    put(
        vdir.clone(),
        "pair",
        "chunk0",
        Arc::new(FixedSizeListArray::from_iter_primitive::<UInt32Type, _, _>(
            pair(),
            2,
        )),
    );
    // an unsigned element that is null: no row
    put(
        vdir,
        "bad",
        "chunk0",
        Arc::new(ListArray::from_iter_primitive::<UInt32Type, _, _>(bad())),
    );
    put(
        dir.join("edge").join("v_knows_v").join("ordered_by_source"),
        "hops",
        "part0/chunk0",
        Arc::new(ListArray::from_iter_primitive::<UInt64Type, _, _>(hops())),
    );
    TempDir(dir)
}

/// (row, position, element) of every element of the lists, a null element as `None`.
fn rows<T: Clone>(lists: &[Option<Vec<Option<T>>>]) -> Vec<(u64, u64, Option<T>)> {
    let mut out = Vec::new();
    for (r, l) in lists.iter().enumerate() {
        for (k, x) in l.iter().flatten().enumerate() {
            out.push((r as u64, k as u64, x.clone()));
        }
    }
    out
}

/// `t(N, P, X) :- v.tags(N, P, X).` and the same for `v.w`, `v.pair`,
/// `h(S, D, P, X) :- knows.hops(S, D, P, X).` and `hr(R, P, X) :- knows@row.hops(R, P, X).`
#[tokio::test]
async fn list_columns_read_by_name_as_rows() {
    let dir = set();
    let g = GarGraph::open(&dir.0).unwrap();
    let catalog = g.catalog().unwrap();
    let base = g.id_space().unwrap().base("v").unwrap();

    let mut p = Program::new();
    let tags_in = p.input_from::<3>(&catalog, "v.tags").unwrap();
    let w_in = p.input_from::<3>(&catalog, "v.w").unwrap();
    let pair_in = p.input_from::<3>(&catalog, "v.pair").unwrap();
    let hops_in = p.input_from::<4>(&catalog, "knows.hops").unwrap();
    let rows_in = p.input_from::<3>(&catalog, "knows@row.hops").unwrap();
    assert_eq!(p.types(tags_in.id()), [Type::U64, Type::U64, Type::Str]);
    assert_eq!(p.types(w_in.id()), [Type::U64, Type::U64, Type::I64]);
    assert_eq!(p.types(pair_in.id()), [Type::U64, Type::U64, Type::U64]);
    assert_eq!(
        p.types(hops_in.id()),
        [Type::U64, Type::U64, Type::U64, Type::U64]
    );
    assert_eq!(p.types(rows_in.id()), [Type::U64, Type::U64, Type::U64]);
    assert!(p.input_from::<2>(&catalog, "v.tags").is_err());
    let bad_in = p.input_from::<3>(&catalog, "v.bad").unwrap();
    assert_eq!(p.types(bad_in.id()), [Type::U64, Type::U64, Type::U64]);

    let t = p.derived_typed("t", [Type::U64, Type::U64, Type::Str]);
    let wo = p.derived_typed("wo", [Type::U64, Type::U64, Type::I64]);
    let po = p.derived::<3>("po");
    let h = p.derived::<4>("h");
    let hr = p.derived::<3>("hr");
    let [n, k, x, s, d] = ["N", "P", "X", "S", "D"].map(|v| p.var(v));
    p.rule(t.at([n, k, x]), [tags_in.at([n, k, x])]).unwrap();
    p.rule(wo.at([n, k, x]), [w_in.at([n, k, x])]).unwrap();
    p.rule(po.at([n, k, x]), [pair_in.at([n, k, x])]).unwrap();
    p.rule(h.at([s, d, k, x]), [hops_in.at([s, d, k, x])])
        .unwrap();
    p.rule(hr.at([s, k, x]), [rows_in.at([s, k, x])]).unwrap();
    let bo = p.derived::<3>("bo");
    p.rule(bo.at([n, k, x]), [bad_in.at([n, k, x])]).unwrap();

    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    for threads in [1, 2, 4] {
        let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads));
        let out = e.run(&p, &inputs).await.unwrap();

        let got: BTreeSet<(u64, u64, Option<String>)> = out
            .datums(&p, &t)
            .unwrap()
            .into_iter()
            .map(|r| match r {
                [Datum::U64(n), Datum::U64(k), Datum::Str(x)] => (n, k, Some(x)),
                [Datum::U64(n), Datum::U64(k), Datum::Null] => (n, k, None),
                r => panic!("{r:?}"),
            })
            .collect();
        let want: BTreeSet<_> = rows(&tags())
            .into_iter()
            .map(|(r, k, x)| (base + r, k, x.map(String::from)))
            .collect();
        assert_eq!(got, want);

        let got: BTreeSet<(u64, u64, i64)> = out
            .datums(&p, &wo)
            .unwrap()
            .into_iter()
            .map(|r| match r {
                [Datum::U64(n), Datum::U64(k), Datum::I64(x)] => (n, k, x),
                r => panic!("{r:?}"),
            })
            .collect();
        let want: BTreeSet<_> = rows(&w())
            .into_iter()
            .map(|(r, k, x)| (base + r, k, x.unwrap()))
            .collect();
        assert_eq!(got, want);

        let got: BTreeSet<Vec<u64>> = out.get(&po).unwrap().rows().collect();
        let want: BTreeSet<_> = rows(&pair())
            .into_iter()
            .map(|(r, k, x)| vec![base + r, k, x.unwrap() as u64])
            .collect();
        assert_eq!(got, want);

        // (a null unsigned element no row, the others at their own positions)
        let got: BTreeSet<Vec<u64>> = out.get(&bo).unwrap().rows().collect();
        let want: BTreeSet<_> = rows(&bad())
            .into_iter()
            .filter_map(|(r, k, x)| Some(vec![base + r, k, x? as u64]))
            .collect();
        assert_eq!(got, want);
        assert!(want.contains(&vec![base, 2, 9]) && want.len() == 3);

        let got: BTreeSet<Vec<u64>> = out.get(&h).unwrap().rows().collect();
        let want: BTreeSet<_> = rows(&hops())
            .into_iter()
            .filter_map(|(e, k, x)| {
                let (s, d) = KNOWS[e as usize];
                Some(vec![base + s as u64, base + d as u64, k, x?])
            })
            .collect();
        assert_eq!(got, want);

        // by the edges' rows: (row, position, value), the row the edge's place in
        // by-source order
        let got: BTreeSet<Vec<u64>> = out.get(&hr).unwrap().rows().collect();
        let want: BTreeSet<_> = rows(&hops())
            .into_iter()
            .filter_map(|(e, k, x)| Some(vec![e, k, x?]))
            .collect();
        assert_eq!(got, want);
    }
}