crates/kleene-iceberg/benches/delta.rs
//! The delta path sized on a real graph: the edges of an X.gar set (`KLEENE_DELTA_SET`, its
//! edge table `KLEENE_DELTA_EDGE`, default `v_link_v`) written as an Iceberg table, then
//! changed by about 1 % in three cases: `plus` (all but every 100th edge first, those
//! appended), `minus` (all edges first, every 100th row of each data file removed by its
//! position), `both` (all but every 100th edge first, every 100th row of each file removed
//! and the held-back edges appended). Per case: the new snapshot read whole against read
//! from the first (only what the window changed, the graph changed in place), and a
//! program (a reach from 64 seeds, a join of one step, a count of the seeds' edges) run from
//! scratch on it against continued from the run on the first (`Engine::continue_with`).
//! Answers checked equal. Prints one JSON line per case. Times are the best of 3.
use std::sync::Arc;
use std::time::Instant;
use arrow_array::{ArrayRef, Int64Array, RecordBatch};
use arrow_schema::{DataType, Field, Schema};
use kleene_datalog::{Engine, Facts, Inputs, Output, Program, Rel};
use kleene_gar::GarGraph;
use kleene_iceberg::{IcebergLake, IcebergSet, MappingSpec, Version};
use kleene_plan::Catalog;
use kleene_sparse::{CpuBackend, CpuDevice};
const MAPPING: &str = r#"(version: 1, tables: [
(table: "g.link", pipeline: [
(edge: (type: "link", src: (label: "v", column: "a"), dst: (label: "v", column: "b"))),
]),
])"#;
fn best<T>(n: usize, mut f: impl FnMut() -> T) -> (f64, T) {
let mut b = f64::MAX;
let mut out = None;
for _ in 0..n {
let t = Instant::now();
let v = f();
b = b.min(t.elapsed().as_secs_f64() * 1e3);
out = Some(v);
}
(b, out.expect("ran"))
}
fn edges(a: &[i64], b: &[i64]) -> RecordBatch {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Int64, false),
Field::new("b", DataType::Int64, false),
]));
let cols: Vec<ArrayRef> = vec![
Arc::new(Int64Array::from(a.to_vec())),
Arc::new(Int64Array::from(b.to_vec())),
];
RecordBatch::try_new(schema, cols).unwrap()
}
struct Prog {
p: Program,
s: Rel<1>,
r: Rel<1>,
hop: Rel<2>,
fan: Rel<2>,
}
fn program(c: &Catalog) -> Prog {
let mut p = Program::new();
let link = p.input_from::<2>(c, "link").unwrap();
let s = p.input::<1>("s");
let r = p.derived::<1>("r");
let hop = p.derived::<2>("hop");
let fan = p.derived_counted::<2>("fan");
let [x, y, n] = ["X", "Y", "N"].map(|v| p.var(v));
p.rule(r.at([y]), [s.at([y])]).unwrap();
p.rule(r.at([y]), [r.at([x]), link.at([x, y])]).unwrap();
p.rule(hop.at([x, y]), [s.at([x]), link.at([x, y])])
.unwrap();
p.count_rule(fan.at([x, n]), [s.at([x]), link.at([x, y])])
.unwrap();
Prog { p, s, r, hop, fan }
}
fn inputs(g: &Prog, c: &Catalog, seeds: &Facts) -> Inputs {
let mut ins = Inputs::new();
ins.bind(&g.p, c).unwrap();
ins.facts(&g.s, seeds.clone()).unwrap();
ins
}
fn sizes(o: &Output, g: &Prog) -> (usize, usize) {
(o.get(&g.r).unwrap().len(), o.get(&g.hop).unwrap().len())
}
fn graph_size(c: &Catalog) -> (usize, usize) {
match c.relation("link").unwrap().0 {
kleene_plan::Source::Graph { out, .. } => (out.nrows(), out.nnz()),
_ => panic!("a graph"),
}
}
/// One case: the first snapshot written (`first`), then every 100th row of each of its
/// files removed (`remove`) and `held` appended; the reads and runs measured; one JSON line.
#[allow(clippy::too_many_arguments)]
fn case(
rt: &tokio::runtime::Runtime,
name: &str,
set: &str,
threads: usize,
first: &[RecordBatch],
held: &(Vec<i64>, Vec<i64>),
remove: bool,
vertices: u64,
) {
let tmp = tempfile::tempdir().unwrap();
let lake = tmp.path().join("lake");
let tw = Instant::now();
// the first snapshot: one append per batch, each one data file whose rows are known
let mut files: Vec<(String, usize)> = Vec::new();
for batch in first {
rt.block_on(kleene_iceberg::write::append(
&lake,
"g.link",
std::slice::from_ref(batch),
))
.unwrap();
let now = rt
.block_on(kleene_iceberg::write::data_files(&lake, "g.link"))
.unwrap();
let new: Vec<String> = now
.into_iter()
.filter(|f| !files.iter().any(|(g, _)| g == f))
.collect();
assert_eq!(new.len(), 1, "one data file per append");
files.push((new[0].clone(), batch.num_rows()));
}
let spec = MappingSpec::from_ron(MAPPING).unwrap();
let open = || IcebergSet::new(&spec, IcebergLake::Warehouse(lake.clone())).unwrap();
let first_ids = rt.block_on(open().version(&Version::new())).unwrap();
let mut removed_rows = 0usize;
if remove {
for (f, rows) in &files {
let pos: Vec<i64> = (0..*rows as i64).filter(|k| k % 100 == 49).collect();
removed_rows += pos.len();
rt.block_on(kleene_iceberg::write::delete_at(&lake, "g.link", f, &pos))
.unwrap();
}
}
if !held.0.is_empty() {
rt.block_on(kleene_iceberg::write::append(
&lake,
"g.link",
&[edges(&held.0, &held.1)],
))
.unwrap();
}
let write_ms = tw.elapsed().as_secs_f64() * 1e3;
// the first snapshot, read once (what a run before kept)
let before = rt.block_on(open().snapshot(&first_ids)).unwrap();
let (whole_ms, (whole, whole_files)) = best(3, || {
let s = open();
let snap = rt.block_on(s.snapshot(&Version::new())).unwrap();
(snap, s.files_read())
});
let (delta_ms, (delta, delta_files)) = best(3, || {
let s = open();
let d = rt.block_on(s.advance(&before, &Version::new())).unwrap();
(d, s.files_read())
});
assert!(delta.reread.is_empty(), "{:?}", delta.reread);
assert_eq!(
graph_size(delta.snapshot.catalog()).1,
graph_size(whole.catalog()).1
);
let prog = program(before.catalog());
let seeds = Facts::from_rows(1, (0..64u64).map(|i| [i * 997 % vertices])).unwrap();
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(threads));
let old = rt
.block_on(engine.run(&prog.p, &inputs(&prog, before.catalog(), &seeds)))
.unwrap();
let now_ins = inputs(&prog, delta.snapshot.catalog(), &seeds);
let mut added = Inputs::new();
added.bind(&prog.p, &delta.added).unwrap();
let mut lost = Inputs::new();
lost.bind(&prog.p, &delta.removed).unwrap();
let (scratch_ms, scratch) = best(3, || rt.block_on(engine.run(&prog.p, &now_ins)).unwrap());
let (cont_ms, cont) = best(3, || {
rt.block_on(engine.continue_with(&prog.p, &old, &now_ins, &added, &lost))
.unwrap()
});
for rel in [prog.r.id(), prog.hop.id(), prog.fan.id()] {
assert_eq!(cont.get_id(rel), scratch.get_id(rel));
}
let strata: Vec<String> = cont
.report
.strata
.iter()
.map(|s| {
format!(
"{}:{}:{:.1}",
s.relations.join(","),
s.continued,
s.compute.as_secs_f64() * 1e3
)
})
.collect();
let (nv, ne) = graph_size(whole.catalog());
println!(
"{{\"case\":\"{name}\",\"set\":\"{set}\",\"vertices\":{nv},\"edges\":{ne},\
\"added_edges\":{},\"removed_rows\":{removed_rows},\"threads\":{threads},\
\"write_ms\":{write_ms:.0},\"read_whole_ms\":{whole_ms:.1},\"read_whole_files\":{whole_files},\
\"read_delta_ms\":{delta_ms:.1},\"read_delta_files\":{delta_files},\
\"run_scratch_ms\":{scratch_ms:.1},\"run_continued_ms\":{cont_ms:.1},\
\"reached\":{},\"hop\":{},\"strata\":\"{}\"}}",
held.0.len(),
sizes(&cont, &prog).0,
sizes(&cont, &prog).1,
strata.join(";")
);
}
fn main() {
let set = std::env::var("KLEENE_DELTA_SET").expect("KLEENE_DELTA_SET: an X.gar set");
let edge = std::env::var("KLEENE_DELTA_EDGE").unwrap_or_else(|_| "v_link_v".into());
let threads: usize = std::env::var("KLEENE_DELTA_THREADS")
.ok()
.and_then(|t| t.parse().ok())
.unwrap_or(8);
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(threads)
.enable_all()
.build()
.unwrap();
let g = GarGraph::open(&set).unwrap();
let t = g.edge_type(&edge).expect("the edge table").clone();
let adj = g.adjacency(&t).unwrap();
let (mut a, mut b) = (Vec::new(), Vec::new());
let (mut a0, mut b0, mut a1, mut b1) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut k = 0usize;
for v in 0..adj.sources {
for j in adj.out_offsets[v] as usize..adj.out_offsets[v + 1] as usize {
let (x, y) = (v as i64, adj.out_neighbours[j] as i64);
a.push(x);
b.push(y);
if k % 100 == 99 {
a1.push(x);
b1.push(y);
} else {
a0.push(x);
b0.push(y);
}
k += 1;
}
}
let chunk = 1 << 22;
let batches = |a: &[i64], b: &[i64]| -> Vec<RecordBatch> {
a.chunks(chunk)
.zip(b.chunks(chunk))
.map(|(a, b)| edges(a, b))
.collect()
};
let (part, all) = (batches(&a0, &b0), batches(&a, &b));
let vertices = adj.sources as u64;
let none = (Vec::new(), Vec::new());
let held = (a1, b1);
let only = std::env::var("KLEENE_DELTA_CASES").unwrap_or_else(|_| "plus,minus,both".into());
for name in only.split(',') {
match name {
"plus" => case(&rt, name, &set, threads, &part, &held, false, vertices),
"minus" => case(&rt, name, &set, threads, &all, &none, true, vertices),
"both" => case(&rt, name, &set, threads, &part, &held, true, vertices),
other => panic!("no case {other}"),
}
}
}