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

//! Columns another GraphAr writer put in a set, of types the set's catalog once refused,
//! read by name through the catalog (`Program::input_from`) and used by a rule; each answer
//! checked against a plain loop over the written values.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_array::{
    ArrayRef, BinaryArray, FixedSizeBinaryArray, Int32Array, Int64Array, RecordBatch, UInt32Array,
    UInt64Array,
};
use arrow_schema::{Field, Schema};
use graphar::mapped::{IntColumn, IntEdges, IntGraphWriter, write_ipc};
use kleene_datalog::{Datum, Engine, Inputs, Program, Term, Type, eq, ge, gt, is_not_null};
use kleene_gar::GarGraph;
use kleene_sparse::{CpuBackend, CpuDevice};

struct TempDir(PathBuf);

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

/// The edges of the set's one edge type `v_link_v`, in by-source order.
const LINKS: [(u32, u32); 3] = [(0, 1), (1, 2), (2, 3)];

/// A set of four `v` vertices and the `link` edges, its columns written by `write`.
fn set(name: &str, write: impl FnOnce(&Path)) -> TempDir {
    let dir = std::env::temp_dir().join(format!(
        "kleene-datalog-columns-{name}-{}",
        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![("id".to_string(), IntColumn::U32(vec![7, 8, 9, 10]))],
    )
    .unwrap();
    let (s, d): (Vec<u32>, Vec<u32>) = LINKS.iter().copied().unzip();
    w.edges(IntEdges::from_pairs(("v", "link", "v"), (4, 4), &s, &d, vec![]).unwrap())
        .unwrap();
    w.finish().unwrap();
    write(&dir);
    TempDir(dir)
}

/// One chunk of column `name`: of vertex type `v`, or (`edge`) of edge type `v_link_v`.
fn put(dir: &Path, name: &str, edge: bool, values: ArrayRef) {
    let schema = Schema::new(vec![Field::new(name, values.data_type().clone(), true)]);
    let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
    let path = if edge {
        dir.join("edge")
            .join("v_link_v")
            .join("ordered_by_source")
            .join(name)
            .join("part0")
            .join("chunk0")
    } else {
        dir.join("vertex").join("v").join(name).join("chunk0")
    };
    write_ipc(path, &batch).unwrap();
}

const B: [Option<&[u8]>; 4] = [Some(b"ab"), Some(&[0xff, 0x00]), None, Some(b"z")];
const H: [[u8; 2]; 4] = [[0x00, 0xff], [0x12, 0x34], [0xab, 0xcd], [0x12, 0x34]];
const LINK_B: [Option<&[u8]>; 3] = [Some(b"x"), Some(&[0xc3]), Some(b"\x01y")];

/// The lowercase hex of `b`.
fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

/// Bytes columns by name: `T.c` of a `Binary` column is its text (a value that is not
/// UTF-8 has none), `T.c@hex` every value's hex, `T.c` of a `FixedSizeBinary` column its
/// hex. `text(N, T) :- v.b(N, T), T = "ab".  all(N, X) :- v.b@hex(N, X).
/// hash(N) :- v.h(N, X), X = "1234".  hash2(N) :- v.h@hex(N, X), X = "1234".
/// ehex(A, B, X) :- link.eb@hex(A, B, X).  etext(A, B) :- link.eb(A, B, T), T = "x".`
#[tokio::test]
async fn bytes_columns_read_as_text_or_hex_by_name() {
    let dir = set("bytes", |d| {
        put(d, "b", false, Arc::new(BinaryArray::from(B.to_vec())));
        let h = FixedSizeBinaryArray::try_from_iter(H.iter()).unwrap();
        put(d, "h", false, Arc::new(h));
        put(d, "eb", true, Arc::new(BinaryArray::from(LINK_B.to_vec())));
    });
    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 b = p.input_from::<2>(&catalog, "v.b").unwrap();
    let b_hex = p.input_from::<2>(&catalog, "v.b@hex").unwrap();
    let h = p.input_from::<2>(&catalog, "v.h").unwrap();
    let h_hex = p.input_from::<2>(&catalog, "v.h@hex").unwrap();
    let eb = p.input_from::<3>(&catalog, "link.eb").unwrap();
    let eb_hex = p.input_from::<3>(&catalog, "link.eb@hex").unwrap();
    for r in [b.id(), b_hex.id(), h.id(), h_hex.id()] {
        assert_eq!(p.types(r), [Type::U64, Type::Str]);
    }
    let text = p.derived::<1>("text");
    let all = p.derived_typed("all", [Type::U64, Type::Str]);
    let hash = p.derived::<1>("hash");
    let hash2 = p.derived::<1>("hash2");
    let ehex = p.derived_typed("ehex", [Type::U64, Type::U64, Type::Str]);
    let etext = p.derived::<2>("etext");
    let [n, t, x, a, c] = ["N", "T", "X", "A", "C"].map(|v| p.var(v));
    let (ab, k, xs) = (p.str("ab"), p.str("1234"), p.str("x"));
    p.rule(text.at([n]), [b.at([n, t]).into(), eq(t, ab)])
        .unwrap();
    p.rule(all.at([n, x]), [b_hex.at([n, x])]).unwrap();
    p.rule(hash.at([n]), [h.at([n, x]).into(), eq(x, k)])
        .unwrap();
    p.rule(hash2.at([n]), [h_hex.at([n, x]).into(), eq(x, k)])
        .unwrap();
    p.rule(ehex.at([a, c, x]), [eb_hex.at([a, c, x])]).unwrap();
    p.rule(etext.at([a, c]), [eb.at([a, c, t]).into(), eq(t, xs)])
        .unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = engine.run(&p, &inputs).await.unwrap();

    let ids = |r: &kleene_datalog::Rel<1>| -> BTreeSet<u64> {
        out.get(r).unwrap().rows().map(|v| v[0]).collect()
    };
    // the plain loops
    let want: BTreeSet<u64> = (0..4)
        .filter(|&i| B[i] == Some(b"ab".as_slice()))
        .map(|i| base + i as u64)
        .collect();
    assert_eq!(ids(&text), want);
    let got: BTreeSet<(u64, Option<String>)> = out
        .datums(&p, &all)
        .unwrap()
        .into_iter()
        .map(|[n, x]| match (n, x) {
            (Datum::U64(n), Datum::Str(x)) => (n, Some(x)),
            (Datum::U64(n), Datum::Null) => (n, None),
            other => panic!("{other:?}"),
        })
        .collect();
    let want: BTreeSet<(u64, Option<String>)> =
        (0..4).map(|i| (base + i as u64, B[i].map(hex))).collect();
    assert_eq!(got, want);
    let want: BTreeSet<u64> = (0..4)
        .filter(|&i| hex(&H[i]) == "1234")
        .map(|i| base + i as u64)
        .collect();
    assert_eq!(want.len(), 2);
    assert_eq!(ids(&hash), want);
    assert_eq!(ids(&hash2), want);
    let got: BTreeSet<(u64, u64, String)> = out
        .datums(&p, &ehex)
        .unwrap()
        .into_iter()
        .map(|[a, c, x]| match (a, c, x) {
            (Datum::U64(a), Datum::U64(c), Datum::Str(x)) => (a, c, x),
            other => panic!("{other:?}"),
        })
        .collect();
    let want: BTreeSet<(u64, u64, String)> = (0..LINKS.len())
        .map(|i| {
            let (s, d) = LINKS[i];
            (base + s as u64, base + d as u64, hex(LINK_B[i].unwrap()))
        })
        .collect();
    assert_eq!(got, want);
    let got: BTreeSet<Vec<u64>> = out.get(&etext).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..LINKS.len())
        .filter(|&i| LINK_B[i] == Some(b"x".as_slice()))
        .map(|i| vec![base + LINKS[i].0 as u64, base + LINKS[i].1 as u64])
        .collect();
    assert_eq!(got, want);
}

/// A column shaped like a real set's string table (`str.bytes`): mostly text, a few values
/// that are not UTF-8 (cut multibyte sequences, raw bytes).
const STR_BYTES: [&[u8]; 8] = [
    b"main",
    b"core::fmt",
    &[0xff, 0xfe, 0x00],
    b"alloc",
    &[0xc3, 0x28],
    b"main",
    b"",
    &[0xe2, 0x82],
];

/// `T.c` of a mostly-text bytes column keeps the rows that are text; `T.c@hex` every row.
/// `main(N) :- str.bytes(N, T), T = "main".  text(N) :- str.bytes(N, T), T IS NOT NULL.
/// raw(N, X) :- str.bytes@hex(N, X).`
#[tokio::test]
async fn a_string_table_with_some_bytes_that_are_not_text() {
    // a set of one vertex type `str`, its column written as another GraphAr writer would
    let dir = TempDir(std::env::temp_dir().join(format!(
        "kleene-datalog-columns-str-bytes-{}",
        std::process::id()
    )));
    let _ = std::fs::remove_dir_all(&dir.0);
    std::fs::create_dir_all(&dir.0).unwrap();
    {
        let mut w = IntGraphWriter::new(&dir.0, "X").unwrap();
        w.vertices("str", STR_BYTES.len() as u32, vec![]).unwrap();
        w.finish().unwrap();
        let values: ArrayRef = Arc::new(BinaryArray::from_vec(STR_BYTES.to_vec()));
        let schema = Schema::new(vec![Field::new("bytes", values.data_type().clone(), false)]);
        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
        let path = dir
            .0
            .join("vertex")
            .join("str")
            .join("bytes")
            .join("chunk0");
        write_ipc(path, &batch).unwrap();
    }
    let g = GarGraph::open(&dir.0).unwrap();
    let catalog = g.catalog().unwrap();
    let base = g.id_space().unwrap().base("str").unwrap();

    let mut p = Program::new();
    let bytes = p.input_from::<2>(&catalog, "str.bytes").unwrap();
    let raw_in = p.input_from::<2>(&catalog, "str.bytes@hex").unwrap();
    let main = p.derived::<1>("main");
    let text = p.derived::<1>("text");
    let raw = p.derived_typed("raw", [Type::U64, Type::Str]);
    let [n, t, x] = ["N", "T", "X"].map(|v| p.var(v));
    let m = p.str("main");
    p.rule(main.at([n]), [bytes.at([n, t]).into(), eq(t, m)])
        .unwrap();
    p.rule(text.at([n]), [bytes.at([n, t]).into(), is_not_null(t)])
        .unwrap();
    p.rule(raw.at([n, x]), [raw_in.at([n, x])]).unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = engine.run(&p, &inputs).await.unwrap();

    let ids = |r: &kleene_datalog::Rel<1>| -> BTreeSet<u64> {
        out.get(r).unwrap().rows().map(|v| v[0]).collect()
    };
    let rows = |f: &dyn Fn(&[u8]) -> bool| -> BTreeSet<u64> {
        (0..STR_BYTES.len())
            .filter(|&i| f(STR_BYTES[i]))
            .map(|i| base + i as u64)
            .collect()
    };
    assert_eq!(ids(&main), rows(&|b| b == b"main"));
    assert_eq!(ids(&text), rows(&|b| std::str::from_utf8(b).is_ok()));
    assert_eq!(ids(&text).len(), 5);
    let got: BTreeSet<(u64, String)> = out
        .datums(&p, &raw)
        .unwrap()
        .into_iter()
        .map(|[n, x]| match (n, x) {
            (Datum::U64(n), Datum::Str(x)) => (n, x),
            other => panic!("{other:?}"),
        })
        .collect();
    let want: BTreeSet<(u64, String)> = (0..STR_BYTES.len())
        .map(|i| (base + i as u64, hex(STR_BYTES[i])))
        .collect();
    assert_eq!(got, want);
}

const U: [Option<u32>; 4] = [Some(5), None, Some(7), None];
const LINK_U: [Option<u64>; 3] = [Some(3), None, Some(9)];

/// Unsigned columns with nulls: a row whose value is null has no value, so it is left out
/// of the `(id, value)` and `(from, to, value)` relations.
/// `has(N, X) :- v.u(N, X).  heavy(A, B) :- link.u(A, B, X), X >= 3.`
#[tokio::test]
async fn unsigned_columns_with_nulls_leave_the_null_rows_out() {
    let dir = set("unsigned-nulls", |d| {
        put(d, "u", false, Arc::new(UInt32Array::from(U.to_vec())));
        put(d, "u", true, Arc::new(UInt64Array::from(LINK_U.to_vec())));
    });
    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 u = p.input_from::<2>(&catalog, "v.u").unwrap();
    let link_u = p.input_from::<3>(&catalog, "link.u").unwrap();
    let has = p.derived::<2>("has");
    let heavy = p.derived::<2>("heavy");
    let [n, x, a, b] = ["N", "X", "A", "B"].map(|v| p.var(v));
    p.rule(has.at([n, x]), [u.at([n, x])]).unwrap();
    p.rule(
        heavy.at([a, b]),
        [link_u.at([a, b, x]).into(), ge(x, Term::Const(3))],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = e.run(&p, &inputs).await.unwrap();

    let got: BTreeSet<Vec<u64>> = out.get(&has).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..U.len())
        .filter_map(|i| U[i].map(|x| vec![base + i as u64, x as u64]))
        .collect();
    assert_eq!(got, want);
    let got: BTreeSet<Vec<u64>> = out.get(&heavy).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..LINKS.len())
        .filter(|&i| LINK_U[i].is_some_and(|x| x >= 3))
        .map(|i| vec![base + LINKS[i].0 as u64, base + LINKS[i].1 as u64])
        .collect();
    assert_eq!(got, want);
}

const KIND: [Option<&str>; 4] = [Some("fn"), Some("static"), None, Some("fn")];
const LINK_KIND: [Option<&str>; 3] = [Some("call"), None, Some("jump")];

/// Dictionary-encoded string columns (Arrow `Dictionary(Int32, Utf8)`) read as strings, of
/// a vertex and of an edge. `fns(N) :- v.kind(N, K), K = "fn".
/// calls(A, B) :- link.kind(A, B, K), K = "call".`
#[tokio::test]
async fn dictionary_strings_read_as_strings() {
    use arrow_array::DictionaryArray;
    use arrow_array::types::Int32Type;
    let dir = set("dict", |d| {
        let kinds: DictionaryArray<Int32Type> = KIND.iter().copied().collect();
        put(d, "kind", false, Arc::new(kinds));
        let kinds: DictionaryArray<Int32Type> = LINK_KIND.iter().copied().collect();
        put(d, "kind", true, Arc::new(kinds));
    });
    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 kind = p.input_from::<2>(&catalog, "v.kind").unwrap();
    let link_kind = p.input_from::<3>(&catalog, "link.kind").unwrap();
    assert_eq!(p.types(kind.id()), [Type::U64, Type::Str]);
    let fns = p.derived::<1>("fns");
    let calls = p.derived::<2>("calls");
    let [n, k, a, b] = ["N", "K", "A", "B"].map(|v| p.var(v));
    let (f, c) = (p.str("fn"), p.str("call"));
    p.rule(fns.at([n]), [kind.at([n, k]).into(), eq(k, f)])
        .unwrap();
    p.rule(calls.at([a, b]), [link_kind.at([a, b, k]).into(), eq(k, c)])
        .unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = engine.run(&p, &inputs).await.unwrap();

    let got: BTreeSet<u64> = out.get(&fns).unwrap().rows().map(|v| v[0]).collect();
    let want: BTreeSet<u64> = (0..KIND.len())
        .filter(|&i| KIND[i] == Some("fn"))
        .map(|i| base + i as u64)
        .collect();
    assert_eq!(got, want);
    let got: BTreeSet<Vec<u64>> = out.get(&calls).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..LINKS.len())
        .filter(|&i| LINK_KIND[i] == Some("call"))
        .map(|i| vec![base + LINKS[i].0 as u64, base + LINKS[i].1 as u64])
        .collect();
    assert_eq!(got, want);
}

const DAY: [Option<i32>; 4] = [Some(0), Some(19000), None, Some(-1)];
const AT_MS: [i64; 4] = [1_000, -2_500, 0, 1_700_000_000_123];
const LINK_DAY_MS: [i64; 3] = [0, 2 * 86_400_000, 5 * 86_400_000];

/// Dates and timestamps read as numbers: a date its days since 1970-01-01, a timestamp its
/// nanoseconds since 1970-01-01T00:00Z, of a vertex and of an edge.
/// `recent(N) :- v.day(N, D), D >= 19000.  at(N, T) :- v.at(N, T).
/// late(A, B) :- link.when(A, B, D), D > 1.`
#[tokio::test]
async fn dates_and_timestamps_read_as_numbers() {
    use arrow_array::{Date32Array, Date64Array, TimestampMillisecondArray};
    let dir = set("dates", |d| {
        put(d, "day", false, Arc::new(Date32Array::from(DAY.to_vec())));
        let at = TimestampMillisecondArray::from(AT_MS.to_vec()).with_timezone("+01:00");
        put(d, "at", false, Arc::new(at));
        put(
            d,
            "when",
            true,
            Arc::new(Date64Array::from(LINK_DAY_MS.to_vec())),
        );
    });
    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 day = p.input_from::<2>(&catalog, "v.day").unwrap();
    let at_in = p.input_from::<2>(&catalog, "v.at").unwrap();
    let when = p.input_from::<3>(&catalog, "link.when").unwrap();
    for r in [day.id(), at_in.id()] {
        assert_eq!(p.types(r), [Type::U64, Type::I64]);
    }
    let recent = p.derived::<1>("recent");
    let at = p.derived_typed("at", [Type::U64, Type::I64]);
    let late = p.derived::<2>("late");
    let [n, d, t, a, b] = ["N", "D", "T", "A", "B"].map(|v| p.var(v));
    p.rule(
        recent.at([n]),
        [day.at([n, d]).into(), ge(d, Term::int(19000))],
    )
    .unwrap();
    p.rule(at.at([n, t]), [at_in.at([n, t])]).unwrap();
    p.rule(
        late.at([a, b]),
        [when.at([a, b, d]).into(), gt(d, Term::int(1))],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = engine.run(&p, &inputs).await.unwrap();

    let got: BTreeSet<u64> = out.get(&recent).unwrap().rows().map(|v| v[0]).collect();
    let want: BTreeSet<u64> = (0..DAY.len())
        .filter(|&i| DAY[i].is_some_and(|x| x >= 19000))
        .map(|i| base + i as u64)
        .collect();
    assert_eq!(got, want);
    let got: BTreeSet<(u64, i64)> = out
        .datums(&p, &at)
        .unwrap()
        .into_iter()
        .map(|[n, t]| match (n, t) {
            (Datum::U64(n), Datum::I64(t)) => (n, t),
            other => panic!("{other:?}"),
        })
        .collect();
    let want: BTreeSet<(u64, i64)> = (0..AT_MS.len())
        .map(|i| (base + i as u64, AT_MS[i] * 1_000_000))
        .collect();
    assert_eq!(got, want);
    let got: BTreeSet<Vec<u64>> = out.get(&late).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..LINKS.len())
        .filter(|&i| LINK_DAY_MS[i] / 86_400_000 > 1)
        .map(|i| vec![base + LINKS[i].0 as u64, base + LINKS[i].1 as u64])
        .collect();
    assert_eq!(got, want);
}

const S: [Option<i64>; 4] = [Some(2), Some(-5), None, Some(0)];
const LINK_E: [Option<i32>; 3] = [Some(-1), Some(3), Some(9)];

/// Signed columns read as unsigned by name (`@u64`), as a set's row-number columns are: a
/// row whose value is negative or null left out.
/// `row(N, R) :- v.s@u64(N, R).  hop(A, B, R) :- link.e@u64(A, B, R), R >= 3.`
#[tokio::test]
async fn signed_columns_read_as_unsigned_by_name() {
    let dir = set("at-u64", |d| {
        put(d, "s", false, Arc::new(Int64Array::from(S.to_vec())));
        put(d, "e", true, Arc::new(Int32Array::from(LINK_E.to_vec())));
    });
    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 s = p.input_from::<2>(&catalog, "v.s@u64").unwrap();
    let e = p.input_from::<3>(&catalog, "link.e@u64").unwrap();
    let row = p.derived::<2>("row");
    let hop = p.derived::<3>("hop");
    let [n, r, a, b] = ["N", "R", "A", "B"].map(|v| p.var(v));
    p.rule(row.at([n, r]), [s.at([n, r])]).unwrap();
    p.rule(
        hop.at([a, b, r]),
        [e.at([a, b, r]).into(), ge(r, Term::Const(3))],
    )
    .unwrap();
    let mut inputs = Inputs::new();
    inputs.bind(&p, &catalog).unwrap();
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
    let out = engine.run(&p, &inputs).await.unwrap();

    let got: BTreeSet<Vec<u64>> = out.get(&row).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..S.len())
        .filter_map(|i| {
            S[i].filter(|&x| x >= 0)
                .map(|x| vec![base + i as u64, x as u64])
        })
        .collect();
    assert_eq!(got, want);
    let got: BTreeSet<Vec<u64>> = out.get(&hop).unwrap().rows().collect();
    let want: BTreeSet<Vec<u64>> = (0..LINKS.len())
        .filter_map(|i| {
            LINK_E[i]
                .filter(|&x| x >= 3)
                .map(|x| vec![base + LINKS[i].0 as u64, base + LINKS[i].1 as u64, x as u64])
        })
        .collect();
    assert_eq!(got, want);
}