crates/kleene-gar/tests/gar_tables.rs
//! X.gar tables through DataFusion on a graph written here, and on a real set when
//! `KLEENE_GAR_DIR` names one.
use std::path::PathBuf;
use std::sync::Arc;
use arrow_array::{Array, ArrayRef, RecordBatch, UInt32Array, UInt64Array, cast::AsArray};
use arrow_schema::DataType;
use datafusion::catalog::TableProvider;
use datafusion::execution::context::SessionContext;
use datafusion::prelude::SessionConfig;
use graphar::mapped::{IntColumn, IntEdges, IntGraphWriter};
use kleene_gar::{EdgeType, GarGraph, GarSchema, TableKind};
/// A fresh directory under the system temp dir, removed when dropped.
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"kleene-gar-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).unwrap();
TempDir(p)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// fn: 5 vertices with `addr` (u64) and `size` (u32); call edges with a `site` property;
/// entry: 2 rows naming fns 0 and 3. The edge type's name splits two ways on purpose
/// (`fn_call_fn` with vertex types `fn` and `fn_call`): the info file decides.
fn write_graph(dir: &std::path::Path) -> PathBuf {
let mut w = IntGraphWriter::new(dir, "X").unwrap();
w.vertices(
"fn",
5,
vec![
("addr".into(), IntColumn::U64(vec![100, 200, 300, 400, 500])),
("size".into(), IntColumn::U32(vec![1, 2, 3, 4, 5])),
],
)
.unwrap();
w.vertices("fn_call", 1, vec![("x".into(), IntColumn::U8(vec![7]))])
.unwrap();
w.vertices("entry", 2, vec![("fid".into(), IntColumn::U32(vec![0, 3]))])
.unwrap();
let src = [0u32, 0, 1, 3, 4, 4];
let dst = [1u32, 2, 2, 4, 0, 1];
let edges = IntEdges::from_pairs(
("fn", "call", "fn"),
(5, 5),
&src,
&dst,
vec![("site".into(), IntColumn::U32(vec![10, 11, 12, 13, 14, 15]))],
)
.unwrap();
w.edges(edges).unwrap();
w.finish().unwrap()
}
fn u32s(batches: &[RecordBatch], col: usize) -> Vec<u32> {
batches
.iter()
.flat_map(|b| {
b.column(col)
.as_primitive::<arrow_array::types::UInt32Type>()
.values()
.to_vec()
})
.collect()
}
#[test]
fn the_tree_gives_vertex_and_edge_types() {
let t = TempDir::new("types");
write_graph(&t.0);
let g = GarGraph::open(&t.0).unwrap();
assert_eq!(g.vertex_types(), &["fn", "fn_call", "entry"]);
assert_eq!(
g.edge_type("fn_call_fn"),
Some(&EdgeType::new("fn", "call", "fn"))
);
assert_eq!(g.kind("fn"), Some(TableKind::Vertex));
assert_eq!(g.kind("fn_call_fn"), Some(TableKind::Edge));
assert_eq!(g.kind("nope"), None);
assert_eq!(g.vertex_count("fn").unwrap(), 5);
assert_eq!(g.vertex_columns("fn").unwrap(), vec!["addr", "size"]);
}
#[tokio::test]
async fn columns_reach_datafusion_without_a_copy() {
let t = TempDir::new("zero-copy");
write_graph(&t.0);
let g = GarGraph::open(&t.0).unwrap();
let table = g.table("fn_call_fn").unwrap().unwrap();
let ptr = |a: &ArrayRef| a.to_data().buffers()[0].as_ptr();
// The same buffer every time it is asked for (mapped columns and made ones alike).
for col in ["src", "dst", "site"] {
assert_eq!(
ptr(&table.column(col).unwrap()),
ptr(&table.column(col).unwrap()),
"{col}"
);
}
// Arrow IPC buffers the writer aligned: the column is the file, not a heap copy.
assert_eq!(ptr(&table.column("dst").unwrap()) as usize % 64, 0);
// A DataFusion scan hands on the very buffers.
let ctx = SessionContext::new_with_config(SessionConfig::new().with_target_partitions(1));
ctx.register_table("calls", table.clone()).unwrap();
let out = ctx
.sql("SELECT dst, site FROM calls")
.await
.unwrap()
.collect()
.await
.unwrap();
assert_eq!(out.len(), 1);
assert_eq!(ptr(out[0].column(0)), ptr(&table.column("dst").unwrap()));
assert_eq!(ptr(out[0].column(1)), ptr(&table.column("site").unwrap()));
let addr = g.vertex_column("fn", "addr").unwrap();
assert_eq!(addr.data_type(), &DataType::UInt64);
}
#[test]
fn the_edge_table_expands_sources_and_keeps_property_rows() {
let t = TempDir::new("edges");
write_graph(&t.0);
let g = GarGraph::open(&t.0).unwrap();
let table = g.table("fn_call_fn").unwrap().unwrap();
let b = table.batch(None).unwrap();
assert_eq!(b.num_rows(), 6);
let src: Vec<u32> = u32s(std::slice::from_ref(&b), 0);
let dst: Vec<u32> = u32s(std::slice::from_ref(&b), 1);
let site: Vec<u32> = u32s(std::slice::from_ref(&b), 2);
let mut rows: Vec<(u32, u32, u32)> = (0..6).map(|i| (src[i], dst[i], site[i])).collect();
rows.sort();
assert_eq!(
rows,
vec![
(0, 1, 10),
(0, 2, 11),
(1, 2, 12),
(3, 4, 13),
(4, 0, 14),
(4, 1, 15)
]
);
assert!(src.windows(2).all(|w| w[0] <= w[1]), "by-source order");
}
#[tokio::test]
async fn sql_joins_over_the_schema() {
let t = TempDir::new("sql");
write_graph(&t.0);
let g = GarGraph::open(&t.0).unwrap();
let ctx = SessionContext::new_with_config(SessionConfig::new().with_target_partitions(3));
GarSchema::register(g, &ctx, "x").unwrap();
let df = ctx
.sql(
"SELECT e.fid, f.addr, c.dst FROM x.entry e \
JOIN x.fn f ON f.id = e.fid \
JOIN x.fn_call_fn c ON c.src = e.fid ORDER BY e.fid, c.dst",
)
.await
.unwrap();
let out = df.collect().await.unwrap();
let fid = u32s(&out, 0);
let dst = u32s(&out, 2);
let addr: Vec<u64> = out
.iter()
.flat_map(|b| {
b.column(1)
.as_primitive::<arrow_array::types::UInt64Type>()
.values()
.to_vec()
})
.collect();
assert_eq!(fid, vec![0, 0, 3]);
assert_eq!(dst, vec![1, 2, 4]);
assert_eq!(addr, vec![100, 100, 400]);
let n = ctx
.sql("SELECT count(*) FROM x.fn_call_fn")
.await
.unwrap()
.collect()
.await
.unwrap();
assert_eq!(
n[0].column(0)
.as_primitive::<arrow_array::types::Int64Type>()
.value(0),
6
);
}
#[tokio::test]
async fn a_table_registers_on_its_own() {
let t = TempDir::new("one");
write_graph(&t.0);
let g = GarGraph::open(&t.0).unwrap();
let ctx = SessionContext::new();
let table: Arc<dyn TableProvider> = g.table("fn").unwrap().unwrap();
ctx.register_table("fns", table).unwrap();
let out = ctx
.sql("SELECT sum(size) FROM fns WHERE addr > 150")
.await
.unwrap()
.collect()
.await
.unwrap();
let v: ArrayRef = out[0].column(0).clone();
assert_eq!(
v.as_primitive::<arrow_array::types::UInt64Type>().value(0),
14
);
}
#[test]
fn a_real_set_opens_when_named() {
let Ok(dir) = std::env::var("KLEENE_GAR_DIR") else {
return;
};
let g = GarGraph::open(&dir).unwrap();
assert!(!g.vertex_types().is_empty());
for (name, t) in g.edge_types() {
let table = g.table(name).unwrap().unwrap();
let adj = g.adjacency(t).unwrap();
assert_eq!(table.rows(), adj.out_neighbours.len(), "{name}");
let src = table.column("src").unwrap();
let src: &UInt32Array = src.as_primitive();
let off = UInt64Array::new(adj.out_offsets.clone(), None);
assert_eq!(src.len() as u64, off.value(off.len() - 1), "{name}");
}
}