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

nordisk/kleene

crates/kleene-iceberg/tests/read.rs

//! A set of Iceberg tables read through bifröst into kleene's catalog: the same Datalog
//! program gives the same answers on it as on the same graph written as an X.gar set
//! (kleene-gar's catalog, the existing way); typed properties; a snapshot read by its id.

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

use arrow_array::{ArrayRef, Float64Array, Int64Array, RecordBatch, StringArray};
use arrow_schema::{Field, Schema};
use graphar::mapped::{IntColumn, IntEdges, IntGraphWriter};
use kleene_datalog::{Engine, Inputs, Program, Term, ge};
use kleene_gar::GarGraph;
use kleene_iceberg::{IcebergLake, IcebergSet, MappingSpec, Version};
use kleene_plan::Catalog;
use kleene_sparse::{CpuBackend, CpuDevice};

const AGES: [i64; 5] = [20, 45, 33, 61, 18];
const KNOWS: [(i64, i64); 5] = [(1, 2), (2, 4), (4, 0), (3, 3), (0, 1)];
/// Person to pet; pets are ids 5 and 6 (as in the X.gar set's one id space).
const OWNS: [(i64, i64); 3] = [(2, 5), (4, 6), (3, 6)];

/// bifröst's mapping, in RON: three tables, a node label each for persons and pets, two
/// edge labels.
const MAPPING: &str = r#"(version: 1, tables: [
  (table: "g.person", pipeline: [
    (vertex: (label: "person", id_column: "id", properties: ["age", "name"])),
  ]),
  (table: "g.pet", pipeline: [
    (vertex: (label: "pet", id_column: "id")),
  ]),
  (table: "g.knows", pipeline: [
    (edge: (type: "knows", src: (label: "person", column: "a"), dst: (label: "person", column: "b"),
            properties: ["since"])),
  ]),
  (table: "g.owns", pipeline: [
    (edge: (type: "owns", src: (label: "person", column: "a"), dst: (label: "pet", column: "b"))),
  ]),
])"#;

fn batch(cols: Vec<(&str, ArrayRef)>) -> RecordBatch {
    let fields: Vec<Field> = cols
        .iter()
        .map(|(n, a)| Field::new(*n, a.data_type().clone(), false))
        .collect();
    RecordBatch::try_new(
        Arc::new(Schema::new(fields)),
        cols.into_iter().map(|c| c.1).collect(),
    )
    .unwrap()
}

fn ints(v: impl IntoIterator<Item = i64>) -> ArrayRef {
    Arc::new(Int64Array::from_iter_values(v))
}

/// The pairs `e` as an edge table (`a`, `b`, and `since` when asked).
fn pairs(e: &[(i64, i64)], since: bool) -> RecordBatch {
    let mut cols = vec![
        ("a", ints(e.iter().map(|p| p.0))),
        ("b", ints(e.iter().map(|p| p.1))),
    ];
    if since {
        cols.push((
            "since",
            Arc::new(Float64Array::from_iter_values(
                e.iter().map(|p| 2000.5 + p.0 as f64),
            )),
        ));
    }
    batch(cols)
}

/// Write `t` (each table name with its batches, one snapshot per batch) into the warehouse
/// at `dir`; the snapshot ids of each table, oldest first.
async fn write(dir: &std::path::Path, t: &[(&str, Vec<RecordBatch>)]) -> Vec<(String, Vec<i64>)> {
    let mut out = Vec::new();
    for (name, batches) in t {
        let ids = kleene_iceberg::write::append(dir, name, batches)
            .await
            .unwrap();
        out.push((name.to_string(), ids));
    }
    out
}

fn persons() -> RecordBatch {
    batch(vec![
        ("id", ints(0..5)),
        ("age", ints(AGES)),
        (
            "name",
            Arc::new(StringArray::from(vec!["ada", "bo", "cy", "di", "ed"])),
        ),
    ])
}

/// The program of kleene-datalog's catalog test, on `catalog`: the pets owned by persons
/// reached along `knows` from a person of at least 40.
async fn kept(catalog: &Catalog) -> BTreeSet<(u64, u64)> {
    let mut p = Program::new();
    let age = p.input_from::<2>(catalog, "person.age").unwrap();
    let knows = p.input_from::<2>(catalog, "knows").unwrap();
    let owns = p.input_from::<2>(catalog, "owns").unwrap();
    let pet = p.input_from::<1>(catalog, "pet").unwrap();
    let old = p.derived::<1>("old");
    let r = p.derived::<1>("r");
    let out = p.derived::<2>("kept");
    let [a, pv, q, x] = ["A", "P", "Q", "X"].map(|n| p.var(n));
    // (an age as the catalog types it: unsigned in the X.gar set, signed in Iceberg)
    let forty = match catalog.relation("person.age").unwrap().1[1] {
        kleene_plan::Type::I64 => Term::int(40),
        _ => Term::Const(40),
    };
    p.rule(old.at([pv]), [age.at([pv, a]).into(), ge(a, forty)])
        .unwrap();
    p.rule(r.at([q]), [old.at([pv]), knows.at([pv, q])])
        .unwrap();
    p.rule(r.at([q]), [r.at([pv]), knows.at([pv, q])]).unwrap();
    p.rule(out.at([pv, x]), [r.at([pv]), owns.at([pv, x]), pet.at([x])])
        .unwrap();
    let mut ins = Inputs::new();
    ins.bind(&p, catalog).unwrap();
    let engine = Engine::<CpuBackend>::new(CpuDevice::new(2));
    let o = engine.run(&p, &ins).await.unwrap();
    o.get(&out).unwrap().rows().map(|t| (t[0], t[1])).collect()
}

/// The same graph as an X.gar set (person 0..5 with an unsigned age, pet 5..7).
fn gar(dir: &std::path::Path) -> Catalog {
    let mut w = IntGraphWriter::new(dir, "X").unwrap();
    let ages: Vec<u32> = AGES.iter().map(|&a| a as u32).collect();
    w.vertices("person", 5, vec![("age".to_string(), IntColumn::U32(ages))])
        .unwrap();
    w.vertices("pet", 2, vec![]).unwrap();
    let split = |e: &[(i64, i64)], db: i64| -> (Vec<u32>, Vec<u32>) {
        e.iter().map(|p| (p.0 as u32, (p.1 - db) as u32)).unzip()
    };
    let (s, d) = split(&KNOWS, 0);
    w.edges(IntEdges::from_pairs(("person", "knows", "person"), (5, 5), &s, &d, vec![]).unwrap())
        .unwrap();
    let (s, d) = split(&OWNS, 5);
    w.edges(IntEdges::from_pairs(("person", "owns", "pet"), (5, 2), &s, &d, vec![]).unwrap())
        .unwrap();
    w.finish().unwrap();
    GarGraph::open(dir).unwrap().catalog().unwrap()
}

#[tokio::test]
async fn a_program_gives_the_same_answers_on_iceberg_tables_as_on_the_same_x_gar_set() {
    let tmp = tempfile::tempdir().unwrap();
    let lake = tmp.path().join("lake");
    write(
        &lake,
        &[
            ("g.person", vec![persons()]),
            ("g.pet", vec![batch(vec![("id", ints([5, 6]))])]),
            ("g.knows", vec![pairs(&KNOWS, true)]),
            ("g.owns", vec![pairs(&OWNS, false)]),
        ],
    )
    .await;
    let spec = MappingSpec::from_ron(MAPPING).unwrap();
    let set = IcebergSet::new(&spec, IcebergLake::Warehouse(lake)).unwrap();
    let snap = set.snapshot(&Version::new()).await.unwrap();
    assert_eq!(set.files_read(), 4, "one data file per table");
    assert_eq!(snap.version().len(), 4);
    let ice = kept(snap.catalog()).await;
    let set_dir = tmp.path().join("X");
    let existing = kept(&gar(&set_dir)).await;
    assert_eq!(ice, existing);
    assert_eq!(ice, BTreeSet::from([(2, 5), (3, 6), (4, 6)]));
}

#[tokio::test]
async fn properties_are_typed_by_their_columns_and_a_snapshot_is_read_by_its_id() {
    let tmp = tempfile::tempdir().unwrap();
    let lake = tmp.path().join("lake");
    let ids = write(
        &lake,
        &[
            ("g.person", vec![persons()]),
            (
                "g.pet",
                vec![
                    batch(vec![("id", ints([5]))]),
                    batch(vec![("id", ints([6]))]),
                ],
            ),
            (
                "g.knows",
                vec![pairs(&KNOWS[..2], true), pairs(&KNOWS[2..], true)],
            ),
            ("g.owns", vec![pairs(&OWNS, false)]),
        ],
    )
    .await;
    let spec = MappingSpec::from_ron(MAPPING).unwrap();
    let set = IcebergSet::new(&spec, IcebergLake::Warehouse(lake)).unwrap();
    let now = set.snapshot(&Version::new()).await.unwrap();
    let c = now.catalog();
    assert_eq!(
        c.relation("person.age").unwrap().1,
        [kleene_plan::Type::U64, kleene_plan::Type::I64]
    );
    assert_eq!(
        c.relation("person.name").unwrap().1[1],
        kleene_plan::Type::Str
    );
    assert_eq!(
        c.relation("knows.since").unwrap().1[2],
        kleene_plan::Type::F64
    );
    assert_eq!(c.relation("knows").unwrap().1.len(), 2);
    // the first snapshot of `knows` and of `pet`: two edges, one pet
    let first: Version = ids
        .iter()
        .filter(|(t, _)| t == "g.knows" || t == "g.pet")
        .map(|(t, s)| (t.clone(), s[0]))
        .collect();
    let then = set.snapshot(&first).await.unwrap();
    let pairs_of = |c: &Catalog| match c.relation("knows").unwrap().0 {
        kleene_plan::Source::Graph { out, .. } => out.nnz(),
        _ => panic!("a graph"),
    };
    assert_eq!((pairs_of(now.catalog()), pairs_of(then.catalog())), (5, 2));
    assert_eq!(then.version()["g.knows"], ids[2].1[0]);
    let mut bad = Version::new();
    bad.insert("g.nothing".into(), 1);
    assert!(set.snapshot(&bad).await.is_err());
}