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

//! A set read from its last version: only the data files added since are read, each edge
//! label's graph grows from the old one, and a program continued from the old run
//! (`Engine::continue_from` with the added rows) derives what a run from scratch derives.

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

use arrow_array::{ArrayRef, Int64Array, RecordBatch};
use arrow_schema::{DataType, Field, Schema};
use kleene_datalog::{Engine, How, Inputs, Output, Program, Rel, Term, ge};
use kleene_iceberg::{IcebergLake, IcebergSet, MappingSpec, Version};
use kleene_plan::{Catalog, Source};
use kleene_sparse::{CpuBackend, CpuDevice};

const MAPPING: &str = r#"(version: 1, tables: [
  (table: "g.node", pipeline: [(vertex: (label: "node", id_column: "id", properties: ["w"]))]),
  (table: "g.link", pipeline: [
    (edge: (type: "link", src: (label: "node", column: "a"), dst: (label: "node", column: "b"))),
  ]),
])"#;

fn batch(cols: Vec<(&str, Vec<i64>)>) -> RecordBatch {
    let fields: Vec<Field> = cols
        .iter()
        .map(|(n, _)| Field::new(*n, DataType::Int64, false))
        .collect();
    let arrays: Vec<ArrayRef> = cols
        .into_iter()
        .map(|(_, v)| Arc::new(Int64Array::from(v)) as ArrayRef)
        .collect();
    RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap()
}

struct Prog {
    p: Program,
    r: Rel<1>,
    heavy: Rel<1>,
    deg: Rel<2>,
}

/// `r` reached from the nodes of weight at least 5 along `link`; `heavy` the reached of
/// weight at least 5; `deg(X, N)` the reached successors of each node, counted.
fn program(c: &Catalog) -> Prog {
    let mut p = Program::new();
    let w = p.input_from::<2>(c, "node.w").unwrap();
    let link = p.input_from::<2>(c, "link").unwrap();
    let r = p.derived::<1>("r");
    let heavy = p.derived::<1>("heavy");
    let deg = p.derived_counted::<2>("deg");
    let [x, y, v, n] = ["X", "Y", "V", "N"].map(|s| p.var(s));
    p.rule(r.at([x]), [w.at([x, v]).into(), ge(v, Term::int(5))])
        .unwrap();
    p.rule(r.at([y]), [r.at([x]), link.at([x, y])]).unwrap();
    p.rule(
        heavy.at([x]),
        [r.at([x]).into(), w.at([x, v]).into(), ge(v, Term::int(5))],
    )
    .unwrap();
    p.count_rule(deg.at([x, n]), [link.at([x, y]), r.at([y])])
        .unwrap();
    Prog { p, r, heavy, deg }
}

fn bound(g: &Prog, c: &Catalog) -> Inputs {
    let mut ins = Inputs::new();
    ins.bind(&g.p, c).unwrap();
    ins
}

fn rows(o: &Output, g: &Prog) -> [BTreeSet<Vec<u64>>; 3] {
    let f = |id| o.get_id(id).map(|f| f.rows().collect()).unwrap_or_default();
    [f(g.r.id()), f(g.heavy.id()), f(g.deg.id())]
}

fn graph(c: &Catalog) -> (Vec<u64>, Vec<u32>) {
    match c.relation("link").unwrap().0 {
        Source::Graph { out, .. } => (
            out.pattern().offsets().to_vec(),
            out.pattern().indices().to_vec(),
        ),
        _ => panic!("a graph"),
    }
}

#[tokio::test]
async fn the_next_version_reads_only_new_files_and_the_run_continues() {
    let tmp = tempfile::tempdir().unwrap();
    let lake = tmp.path().join("lake");
    let write = kleene_iceberg::write::append;
    write(
        &lake,
        "g.node",
        &[batch(vec![
            ("id", (0..6).collect()),
            ("w", vec![1, 9, 2, 3, 1, 1]),
        ])],
    )
    .await
    .unwrap();
    write(
        &lake,
        "g.link",
        &[batch(vec![("a", vec![1, 2, 3]), ("b", vec![2, 3, 0])])],
    )
    .await
    .unwrap();
    let spec = MappingSpec::from_ron(MAPPING).unwrap();
    let set = IcebergSet::new(&spec, IcebergLake::Warehouse(lake.clone())).unwrap();
    let first = set.snapshot(&Version::new()).await.unwrap();
    assert_eq!(set.files_read(), 2);
    let g = program(first.catalog());
    let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2)).explain(true);
    let before = engine.run(&g.p, &bound(&g, first.catalog())).await.unwrap();
    // new rows: two links (one from a reached node) and two nodes, one heavy
    write(
        &lake,
        "g.link",
        &[batch(vec![("a", vec![0, 6]), ("b", vec![4, 7])])],
    )
    .await
    .unwrap();
    write(
        &lake,
        "g.node",
        &[batch(vec![("id", vec![6, 7]), ("w", vec![7, 1])])],
    )
    .await
    .unwrap();
    let delta = set.advance(&first, &Version::new()).await.unwrap();
    assert_eq!(set.files_read(), 4, "only the two new data files");
    assert!(delta.reread.is_empty());
    let now = &delta.snapshot;
    // the graph grown from the old one is the graph built whole
    let whole = IcebergSet::new(&spec, IcebergLake::Warehouse(lake.clone()))
        .unwrap()
        .snapshot(&Version::new())
        .await
        .unwrap();
    assert_eq!(graph(now.catalog()), graph(whole.catalog()));
    let next = engine
        .continue_from(
            &g.p,
            &before,
            &bound(&g, now.catalog()),
            &bound(&g, &delta.added),
        )
        .await
        .unwrap();
    let scratch = engine.run(&g.p, &bound(&g, now.catalog())).await.unwrap();
    assert_eq!(rows(&next, &g), rows(&scratch, &g));
    assert!(rows(&next, &g)[0].contains(&vec![7]));
    // (the engine explains: the counted `deg` counts again, its proofs keeping each
    // counting rule's rows; every other stratum continues)
    assert!(
        next.report
            .strata
            .iter()
            .all(|s| s.continued != (s.relations == ["deg"])),
        "{:?}",
        next.report.strata
    );
    for t in &rows(&next, &g)[2] {
        let q = next
            .why_id(&g.p, g.deg.id(), t)
            .expect("a proof of a deg row");
        assert!(
            matches!(q.how, How::Counted { .. }),
            "{}",
            next.render(&g.p, &q)
        );
    }
    let q = next.why_id(&g.p, g.r.id(), &[4]).expect("a proof");
    assert!(q.steps() >= 2, "{}", next.render(&g.p, &q));
    assert!(
        !rows(&next, &g)[0].contains(&vec![5]),
        "node 5 is light and has no edge in"
    );
    // nothing new: nothing read, every stratum kept
    let same = set.advance(now, &Version::new()).await.unwrap();
    assert_eq!(set.files_read(), 4);
    let kept = engine
        .continue_from(
            &g.p,
            &next,
            &bound(&g, same.snapshot.catalog()),
            &bound(&g, &same.added),
        )
        .await
        .unwrap();
    assert_eq!(rows(&kept, &g), rows(&scratch, &g));
}