crates/kleene-iceberg/tests/removed.rs
//! Rows removed from Iceberg tables between two snapshots: the next version reads only what
//! the window removed and added (equality deletes, position deletes, a rewrite), the graph
//! and the catalog equal those read whole, the facts lost come as a catalog of their own,
//! and a run continued with both (`Engine::continue_with`) derives what a run from scratch
//! derives. A removal the mapping cannot name reads its table whole; a pair another row
//! still holds stays in the graph.
use std::collections::BTreeSet;
use std::path::Path;
use std::sync::Arc;
use arrow_array::{ArrayRef, Int64Array, RecordBatch};
use arrow_schema::{DataType, Field, Schema};
use kleene_datalog::{Engine, Inputs, Output, Program, Rel, Term, ge};
use kleene_iceberg::write::{append, data_files, delete_at, delete_equal, rewrite};
use kleene_iceberg::{IcebergLake, IcebergSet, MappingSpec, Snapshot, 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()
}
fn nodes(ids: &[i64], w: &[i64]) -> RecordBatch {
batch(vec![("id", ids.to_vec()), ("w", w.to_vec())])
}
/// Links with a tag column `k` the mapping does not read.
fn links(e: &[(i64, i64)], k: i64) -> RecordBatch {
batch(vec![
("a", e.iter().map(|x| x.0).collect()),
("b", e.iter().map(|x| x.1).collect()),
("k", vec![k; e.len()]),
])
}
struct Prog {
p: Program,
r: Rel<1>,
heavy: Rel<1>,
deg: Rel<2>,
hop: 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; `hop` the
/// pairs two links apart.
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 hop = p.derived::<2>("hop");
let [x, y, z, v, n] = ["X", "Y", "Z", "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();
p.rule(hop.at([x, z]), [link.at([x, y]), link.at([y, z])])
.unwrap();
Prog {
p,
r,
heavy,
deg,
hop,
}
}
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>>; 4] {
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()), f(g.hop.id())]
}
fn edges(c: &Catalog) -> BTreeSet<(u32, u32)> {
match c.relation("link").unwrap().0 {
Source::Graph { out, .. } => (0..out.nrows())
.flat_map(|i| out.row(i).iter().map(move |&j| (i as u32, j)))
.collect(),
_ => panic!("a graph"),
}
}
/// The facts of relation `name` of `c` (a label, a property), as rows.
fn facts(c: &Catalog, name: &str) -> BTreeSet<Vec<u64>> {
match c.relation(name) {
Ok((Source::Columns(cols), _)) => {
let cols: Vec<Vec<u64>> = cols
.iter()
.map(|a| {
let a = arrow_cast_u64(a);
a.to_vec()
})
.collect();
(0..cols.first().map_or(0, Vec::len))
.map(|i| cols.iter().map(|c| c[i]).collect())
.collect()
}
Ok((Source::Graph { .. }, _)) => edges(c)
.into_iter()
.map(|(a, b)| vec![a as u64, b as u64])
.collect(),
_ => BTreeSet::new(),
}
}
fn arrow_cast_u64(a: &ArrayRef) -> Vec<u64> {
use arrow_array::Array;
use arrow_array::cast::AsArray;
use arrow_array::types::{Int64Type, UInt64Type};
match a.data_type() {
DataType::UInt64 => a.as_primitive::<UInt64Type>().values().to_vec(),
DataType::Int64 => a
.as_primitive::<Int64Type>()
.values()
.iter()
.map(|&x| x as u64)
.collect(),
d => panic!("a column of {d} ({} rows)", a.len()),
}
}
async fn whole(spec: &MappingSpec, lake: &Path) -> Snapshot {
IcebergSet::new(spec, IcebergLake::Warehouse(lake.to_path_buf()))
.unwrap()
.snapshot(&Version::new())
.await
.unwrap()
}
/// The data file `table` gained by its last write.
async fn newest(lake: &Path, table: &str, before: &[String]) -> String {
data_files(lake, table)
.await
.unwrap()
.into_iter()
.find(|f| !before.contains(f))
.expect("a new data file")
}
#[tokio::test]
async fn the_next_version_reads_what_was_removed_and_the_run_continues() {
let tmp = tempfile::tempdir().unwrap();
let lake = tmp.path().join("lake");
append(
&lake,
"g.node",
&[nodes(&[0, 1, 2, 3, 4, 5], &[9, 1, 2, 3, 1, 7])],
)
.await
.unwrap();
append(&lake, "g.link", &[links(&[(0, 1), (1, 2), (2, 3)], 0)])
.await
.unwrap();
let first_files = data_files(&lake, "g.link").await.unwrap();
append(&lake, "g.link", &[links(&[(3, 4), (5, 4), (4, 0)], 1)])
.await
.unwrap();
let second = newest(&lake, "g.link", &first_files).await;
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();
let read = set.files_read();
let g = program(first.catalog());
// the window: an equality delete of link (1, 2), a position delete of (5, 4), node 5
// removed by id, a new link and a new node
delete_equal(
&lake,
"g.link",
&batch(vec![("a", vec![1]), ("b", vec![2])]),
&["a", "b"],
)
.await
.unwrap();
delete_at(&lake, "g.link", &second, &[1]).await.unwrap();
delete_equal(&lake, "g.node", &batch(vec![("id", vec![5])]), &["id"])
.await
.unwrap();
append(&lake, "g.link", &[links(&[(4, 6)], 2)])
.await
.unwrap();
append(&lake, "g.node", &[nodes(&[6], &[2])]).await.unwrap();
let delta = set.advance(&first, &Version::new()).await.unwrap();
assert!(delta.reread.is_empty(), "{:?}", delta.reread);
assert_eq!(set.files_read() - read, 2, "only the two new data files");
let now = &delta.snapshot;
let all = whole(&spec, &lake).await;
assert_eq!(edges(now.catalog()), edges(all.catalog()));
for name in ["node", "node.w", "link"] {
assert_eq!(
facts(now.catalog(), name),
facts(all.catalog(), name),
"{name}"
);
}
assert_eq!(
facts(&delta.removed, "link"),
BTreeSet::from([vec![1, 2], vec![5, 4]])
);
assert_eq!(facts(&delta.removed, "node"), BTreeSet::from([vec![5]]));
assert_eq!(
facts(&delta.removed, "node.w"),
BTreeSet::from([vec![5, 7]])
);
assert_eq!(facts(&delta.added, "link"), BTreeSet::from([vec![4, 6]]));
for explain in [false, true] {
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2)).explain(explain);
let before = engine.run(&g.p, &bound(&g, first.catalog())).await.unwrap();
let next = engine
.continue_with(
&g.p,
&before,
&bound(&g, now.catalog()),
&bound(&g, &delta.added),
&bound(&g, &delta.removed),
)
.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![2]), "1 -> 2 is gone");
if explain {
for v in rows(&next, &g)[0].iter() {
let q = next.why_id(&g.p, g.r.id(), v).expect("a proof");
assert!(!next.render(&g.p, &q).is_empty());
}
}
}
}
#[tokio::test]
async fn a_rewrite_a_pinned_snapshot_and_rows_the_mapping_cannot_name() {
let tmp = tempfile::tempdir().unwrap();
let lake = tmp.path().join("lake");
append(&lake, "g.node", &[nodes(&[0, 1, 2], &[9, 1, 2])])
.await
.unwrap();
append(&lake, "g.link", &[links(&[(0, 1), (1, 2), (1, 2)], 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();
// one of the two rows (1, 2) removed by its position: the pair stays in the graph
let files = data_files(&lake, "g.link").await.unwrap();
delete_at(&lake, "g.link", &files[0], &[2]).await.unwrap();
let d1 = set.advance(&first, &Version::new()).await.unwrap();
assert!(d1.reread.is_empty());
assert_eq!(
edges(d1.snapshot.catalog()),
BTreeSet::from([(0, 1), (1, 2)])
);
assert!(
facts(&d1.removed, "link").is_empty(),
"a pair another row holds is no lost fact"
);
// a copy-on-write rewrite of the node table: node 2 out, its weight of node 1 changed
let node_files = data_files(&lake, "g.node").await.unwrap();
rewrite(&lake, "g.node", &node_files, &[nodes(&[0, 1], &[9, 6])])
.await
.unwrap();
let d2 = set.advance(&d1.snapshot, &Version::new()).await.unwrap();
assert!(d2.reread.is_empty());
let all = whole(&spec, &lake).await;
for name in ["node", "node.w", "link"] {
assert_eq!(
facts(d2.snapshot.catalog(), name),
facts(all.catalog(), name),
"{name}"
);
}
// an equality delete on the tag column alone names no link: the table is read whole
delete_equal(&lake, "g.link", &batch(vec![("k", vec![0])]), &["k"])
.await
.unwrap();
append(&lake, "g.link", &[links(&[(0, 2)], 1)])
.await
.unwrap();
let d3 = set.advance(&d2.snapshot, &Version::new()).await.unwrap();
assert_eq!(d3.reread, vec!["g.link".to_string()]);
assert_eq!(edges(d3.snapshot.catalog()), BTreeSet::from([(0, 2)]));
let g = program(first.catalog());
let engine: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
let before = engine
.run(&g.p, &bound(&g, d2.snapshot.catalog()))
.await
.unwrap();
let next = engine
.continue_with(
&g.p,
&before,
&bound(&g, d3.snapshot.catalog()),
&bound(&g, &d3.added),
&bound(&g, &d3.removed),
)
.await
.unwrap();
let scratch = engine
.run(&g.p, &bound(&g, d3.snapshot.catalog()))
.await
.unwrap();
assert_eq!(rows(&next, &g), rows(&scratch, &g));
// a snapshot pinned before the removals reads its rows as they were then
let pins: Version = first.version().clone();
let again = IcebergSet::new(&spec, IcebergLake::Warehouse(lake.clone()))
.unwrap()
.snapshot(&pins)
.await
.unwrap();
assert_eq!(edges(again.catalog()), edges(first.catalog()));
assert_eq!(
facts(again.catalog(), "node.w"),
facts(first.catalog(), "node.w")
);
// and one pinned after them, read fresh, holds what is live there
let late = IcebergSet::new(&spec, IcebergLake::Warehouse(lake.clone()))
.unwrap()
.snapshot(d2.snapshot.version())
.await
.unwrap();
for name in ["node", "node.w", "link"] {
assert_eq!(
facts(late.catalog(), name),
facts(d2.snapshot.catalog(), name),
"{name}"
);
}
}